index.html
[html]<a href="servlet1">click here</a>[/html]
Here just created a button
click here, when click on the button parameters will be passed from
web.xml file.
DemoServlet.java
[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();
}
}
[/java]
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
[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>[/xml]
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.
Difference between ServletConfig and ServletContext
ServletConfig
- It is available in javax.servlet.*; package
- It's object is one per servlet class
- The tag will be appear under tag
ServletContext
- It is available in javax.servlet.*; package
- It's object is global to all.
- The tag will be appear under tag