web.xml
[xml]
<web-app>
<context-param>
<param-name>user_name</param-name>
<param-value>Welcome to SpLessons</param-value>
</context-param>
<servlet>
<servlet-name>DemoServletContext</servlet-name>
<servlet-class>DemoServletContext</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServletContext</servlet-name>
<url-pattern>/com</url-pattern>
</servlet-mapping>
</web-app>
[/xml]
In the case that any data is shared to numerous servlet, it is ideal to give it from the
web.xml record utilizing the component. Here the developer is passing the details from parameters, here did not create any
HTML page.
DemoServletConText.java
[java]
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServletContext extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext context = getServletContext();
String fullname = context.getInitParameter("user_name");
out.print("
<h2>This value get from web.xml ::<b>"+fullname+"</b></h2>
");
out.print("</body></html>");
out.flush();
out.close();
}
}
[/java]
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. PrintWriter is utilized print content information to a character stream and
getWriter Returns a
PrintWriter object that can send character content to the client.
Output
Output will be as follows on the server.
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