Servlet Config object is created by servlet container for every servlet. It is used to get the information from the web.xml as a param-value. That means when param-name is called in the web.xml, it gives the pram-value. ServletConfig can manage without disturbing servlet program. Go to web.xml. Change the param-value and call param-name. So it is easy to modify the content. Following is the syntax.
First create: ServletConfig config = getServletConfig(); Next call: String param_value = config.getCofig();
Method | Description |
---|---|
getInitParameter(String name) | It returns the param-value when param-name is called and the return type is string . |
getServletContext() | It returns the ServletContext object and the return type is ServletContext. |
getInitParameterNames() | It returns the names of servlet initialization param-values as a enumeration and return type is Enumeration. |
getServletName() | It returns name of the servlet instance like server administer and the return type is string. |
<a href="servlet1">click here</a>
Here just created a button click here, when click on the button parameters will be passed from web.xml file.
DemoServlet.java
package config2; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ServletConfig config=getServletConfig(); String splesson=config.getInitParameter("splesson"); out.print("splessons: "+splesson); out.close(); } }
The getServletConfig() method of Servlet interface returns the object of ServletConfig. Here the purpose of setContentType(“text/html”) is that, It basically tells the client what content type it is so that it knows what to do with it. The doGet() method is utilized to send parameters to an URL along with the header information. The PrintWriter is utilized print content information to a character stream and getWriter Returns a PrintWriter object that can send character content to the client.
web.xml
<web-app> <servlet> <servlet-name>DemoServlet</servlet-name> <servlet-class>config2.DemoServlet</servlet-class> <init-param> <param-name>splesson</param-name> <param-value>Hey man stop thinking start coding</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DemoServlet</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> </web-app>
Make sure that servlet name should be same, here parameters passing from the web.xml file.
Output
By compiling the code the following output will be generated.
By clicking on the link following message will be displayed. This output message was placed in parameters.