1. Explanation of ServletConfig
1.1. Configure Servlet initialization parameters
In the Servlet's configuration file web.xml, you can use one or more <init-param> tags to configure some initialization parameters for the servlet.
For example:
<servlet> <servlet-name>ServletConfigDemo1</servlet-name> <servlet-class>gacl.servlet.study.ServletConfigDemo1</servlet-class> <!--Configure the initialization parameters of ServletConfigDemo1 --> <init-param> <param-name>name</param-name> <param-value>gacl</param-value> </init-param> <init-param> <param-name>password</param-name> <param-value>123</param-value> </init-param> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param></servlet>
1.2. Get the initialization parameters of the Servlet through ServletConfig
When the servlet has configured initialization parameters, the web container will automatically encapsulate these initialization parameters into the ServletConfig object when creating the servlet instance object, and pass the ServletConfig object to the servlet when calling the servlet's init method. Furthermore, we can obtain the initialization parameter information of the current servlet through the ServletConfig object.
For example:
package gacl.servlet.study;import java.io.IOException;import java.util.Enumeration;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletConfigDemo1 extends HttpServlet { /** * Define ServletConfig object to receive the configured initialization parameters*/ private ServletConfig config; /** * When the servlet configures initialization parameters, when the web container creates servlet instance objects, * will automatically encapsulate these initialization parameters into the ServletConfig object, and when the servlet's init method is called, * pass the ServletConfig object to the servlet. Furthermore, the programmer can get the initialization parameter information of the current servlet through the ServletConfig object. */ @Override public void init(ServletConfig config) throws ServletException { this.config = config; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the initialization parameter String paramVal configured in web.xml = this.config.getInitParameter("name");//Get the specified initialization parameter response.getWriter().print(paramVal); response.getWriter().print("<hr/>"); //Get all initialization parameters Enumeration<String> e = config.getInitParameterNames(); while(e.hasMoreElements()){ String name = e.nextElement(); String value = config.getInitParameter(name); response.getWriter().print(name + "=" + value + "<br/>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}The operation results are as follows:
2. ServletContext object
When the WEB container is started, it creates a corresponding ServletContext object for each WEB application, which represents the current web application.
The ServletConfig object maintains a reference to the ServletContext object. When writing a servlet, developers can obtain the ServletConfig.getServletContext method through the ServletConfig.getServletContext method.
Since all Servlets in a WEB application share the same ServletContext object, communication between Servlet objects can be achieved through ServletContext objects. ServletContext objects are usually also called context domain objects.
3. Application of ServletContext
3.1. Multiple Servlets realize data sharing through ServletContext object
Example: ServletContextDemo1 and ServletContextDemo2 realize data sharing through ServletContext object
package gacl.servlet.study;import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletContextDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "xdp_gacl"; /** * The ServletConfig object maintains the reference to the ServletContext object. When developers write servlets, * can obtain the ServletConfig.getServletContext method through the ServletConfig.getServletContext method. */ ServletContext context = this.getServletConfig().getServletContext();//Get ServletContext object context.setAttribute("data", data); //Save data into ServletContext object} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }} package gacl.servlet.study;import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletContextDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); String data = (String) context.getAttribute("data");//Fetch data from the ServletContext object response.getWriter().print("data="+data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}First run ServletContextDemo1, store the data data into the ServletContext object, and then run ServletContextDemo2 to extract data from the ServletContext object, so that data sharing is realized, as shown in the figure below:
3.2. Obtain the initialization parameters of the WEB application
Use the <context-param> tag in the web.xml file to configure the initialization parameters of the WEB application as follows:
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <!-- Configure initialization parameters of WEB application --> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/test</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
Get the initialization parameters of the web application, the code is as follows:
package gacl.servlet.study;import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletContextDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); //Get the initialization parameters of the entire web site String contextInitParam = context.getInitParameter("url"); response.getWriter().print(contextInitParam); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Running results:
3.3. Use servletContext to implement request forwarding
ServletContextDemo4
package gacl.servlet.study;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.ServletContext;import javax.servlet.Servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletContextDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "<h1><font color='red'>abcdefghjkl</font></h1>"; response.getOutputStream().write(data.getBytes()); ServletContext context = this.getServletContext();//Get ServletContext object RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//Get request forwarding object (RequestDispatcher) rd.forward(request, response);//Call forward method to implement request forwarding} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }} ServletContextDemo5
package gacl.servlet.study;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletContextDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getOutputStream().write("servletDemo5".getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}Running results:
The access is ServletContextDemo4, but the browser displays the content of ServletContextDemo5. This is the use of ServletContext to implement request forwarding.
3.4. Use ServletContext object to read resource files
The project directory structure is as follows:
Code example: Use servletContext to read resource files
package gacl.servlet.study;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.text.MessageFormat;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Use servletContext to read resource files* * @author gacl * */public class ServletContextDemo6 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * response.setContentType("text/html;charset=UTF-8"); The purpose is to control the browser to decode using UTF-8; * This way, there will be no Chinese garbled code */ response.setHeader("content-type","text/html;charset=UTF-8"); readSrcDirPropCfgFile(response);//Read the properties configuration file response.getWriter().println("<hr/>"); readWebRootDirPropCfgFile(response);//Read the properties configuration file response.getWriter().println("<hr/>"); readWebRootDirPropCfgFile(response);//Read the properties configuration file response.getWriter().println("<hr/>"); readPropCfgFile(response);//Read the db3.properties configuration file in the db.config package in the src directory response.getWriter().println("<hr/>"); readPropCfgFile2(response);//Read the db4.properties configuration file in the gacl.servlet.study package in the src directory} /** * Read the db4.properties configuration file in the gacl.servlet.study package in the src directory* @param response * @throws IOException */ private void readPropCfgFile2(HttpServletResponse response) throws IOException { InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/gacl/servlet/study/db4.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("Read the db4.properties configuration file in the gacl.servlet.study package in the src directory: "); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * Read the db3.properties configuration file in the db.config package in the src directory* @param response * @throws FileNotFoundException * @throws IOException */ private void readPropCfgFile(HttpServletResponse response) throws FileNotFoundException, IOException { //Get the absolute path of web resources through ServletContext String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties"); InputStream in = new FileInputStream(path); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("Read the db3.properties configuration file in the db.config package under the src directory: "); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * Read the properties configuration file in the WebRoot directory through the ServletContext object* @param response * @throws IOException */ private void readWebRootDirPropCfgFile(HttpServletResponse response) throws IOException { /** * Read the properties configuration file in the WebRoot directory through the ServletContext object* "/" represents the project root directory*/ InputStream in = this.getServletContext().getResourceAsStream("/db2.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("Read the db2.properties configuration file in the WebRoot directory:"); response.getWriter().print( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * Read the properties configuration file in the src directory through the ServletContext object* @param response * @throws IOException */ private void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException { /** * Read the db1.properties configuration file in the src directory through the ServletContext object*/ InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db1.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("Read the db1.properties configuration file in the src directory:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}The operation results are as follows:
Code example: Read resource files using class loader
package gacl.servlet.study;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.text.MessageFormat;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Read resource files with class loader* Notes on reading resource files through class loader: It is not suitable to load large files, otherwise it will cause jvm memory overflow* @author gacl * */public class ServletContextDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * response.setContentType("text/html;charset=UTF-8"); The purpose is to control the browser to decode with UTF-8; * This will not cause Chinese garbled */ response.setHeader("content-type","text/html;charset=UTF-8"); test1(response); response.getWriter().println("<hr/>"); test2(response); response.getWriter().println("<hr/>"); //test3(); test4(); } /** * Read resource files under the classpath* @param response * @throws IOException */ private void test1(HttpServletResponse response) throws IOException { //Get the class loader that loads the current class ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //Use the class loader to read the db1.properties configuration file in the src directory InputStream in = loader.getResourceAsStream("db1.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("Use class loader to read the db1.properties configuration file in the src directory:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * Read resource files below the class path and package* @param response * @throws IOException */ private void test2(HttpServletResponse response) throws IOException { //Get the class loader that loads the current class ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //Use the class loader to read the db4.properties configuration file in the gacl.servlet.study package in the src directory InputStream in = loader.getResourceAsStream("gacl/servlet/study/db4.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("Use class loader to read the db4.properties configuration file in the gacl.servlet.study package in the src directory: "); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url,username, password)); } /** * Notes on reading resource files through class loader: It is not suitable to load large files, otherwise it will cause jvm memory overflow*/ public void test3() { /** * 01.avi is a file with more than 150 M. It will cause memory overflow when reading this large file using class loader: * java.lang.OutOfMemoryError: Java heap space */ InputStream in = ServletContextDemo7.class.getClassLoader().getResourceAsStream("01.avi"); System.out.println(in); } /** * Read 01.avi and copy to e:/root directory* 01.avi file is too large, you can only use servletContext to read* @throws IOException */ public void test4() throws IOException { // path=G:/Java learning video/JavaWeb learning video/JavaWeb/day05 video/01.avi // path=01.avi String path = this.getServletContext().getRealPath("/WEB-INF/classes/01.avi"); /** * path.lastIndexOf("//") + 1 is a very wonderful way to write it */ String filename = path.substring(path.lastIndexOf("//") + 1);//Get the file name InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/01.avi"); byte buffer[] = new byte[1024]; int len = 0; OutputStream out = new FileOutputStream("e://" + filename); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}The operation results are as follows:
4. Cache the output of Servlet on the client side
For data that does not change frequently, a reasonable cache time value can be set in the servlet to avoid the browser sending requests to the server frequently and improving the server's performance. For example:
package gacl.servlet.study;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "abcddfwerwesfasfsadf"; /** * Set a reasonable data cache time value to avoid frequent requests from the browser to improve server performance* Here is to set the data cache time to 1 day*/ response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000); response.getOutputStream().write(data.getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}The above is all about this article, and I hope it will be helpful for everyone to master the javaweb Servlet development technology.