First call: ServletContext context = getServletContext(); Next call: String contextName = getInitParameter();
Method | Description |
---|---|
getInitParameter(String name) | It returns the param-value in the web.xml context tag and the return type is string . |
getMimeType(String file) | It returns the MIME type of content like text/html, images and the return type is string . |
getServerInfo() | It returns the server version and name of which servlet is running and the return type is string . |
getContext(String uripath) | It returns the ServletContext object corresponding to specified URL on the server and the return type is ServletContext. |
setAttribute(String name, object) | It is for bind an object to an given attribute name is this ServletContext, if already exist the name then this method replace with the new of new attribute. |
getAttribute(String name) | It returns the servlet container attribute with the given name and the return type is object. |
getInitParameterNames() | It returns the names of context’s initialization parameter and the return type is enumerator. |
<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>
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
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(); } }
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.
ServletContext