Servlet
The full instance is in the TomcatTest file of Eclipse
Introduction of the servlet
-
Servlets are one of the JavaEE specifications, and the specification is the interface
-
Servlets are one of the three components of JavaWeb. The other two components are a Filter and a Listener
-
A Servlet is a Small Java program that runs on a server.
In the middle layer between the browser and the Web server, servlets can take data from the browser and deliver it to the server, or they can deliver information from the server-side database to the browser.
Servlets can be created using the Javax. Servlet and javax.servlet. HTTP packages
Serlvet creation and configuration of Tomcat
Meaning of tomcat server files
- Bin: binary execution file. The most commonly used startup file is startup.bat. For Linux or Mac OS, the startup file is startup.sh.
- Conf: indicates the configuration directory. The core file is server.xml. You can change the port number and so on inside. The default port number is 8080, which means that this port number cannot be used by other applications.
- Lib: library file. Directory for storing jar packages required for tomcat running
- Logs: log
- Temp: a temporary file, that is, a cache
- Webapps: Web applications. The Web application can be directly accessed by the browser after being placed in this directory
- Work: compiled class file.
Double-click startup.bat to start Tomcat. A dialog box is displayed indicating that the local server is successfully started. Enter http://localhost:8080/ to switch to the Tomcat page. Tomcat is successfully installed and started
Servlet environment configuration in Eclipse
-
Download tomcat
-
Add the Tomcat server in Eclipse preference –> Server –> Runtime enviorment
-
New dynamic Web project –> add JDK and Tomcat, remember to generate web.xml file
Engineering document structure drawing
- Deployment descriptor: Deployment descriptor.
- Web App Libraries: Store self-added packages in the Web App Libraries.
- Build: Places the compiled file.
- WebContent: Put into the written page.
Create a new JSP file in the WebContent directory and type <%out.print(” Hello world”); %> Start the project to output the correct results in the browser
The life cycle of a servlet
Execute the Servlet’s constructor method —–> execute init() method –> execute service method —-> execute deStory method
-
The Servlet is initialized by calling the init () method.
-
Only called once. It is called the first time the Servlet is created and not again on each subsequent user request.
-
public void init(a) throws ServletException { // Initialize code... } Copy the code
-
-
The Servlet calls the service() method to handle requests from the client.
-
The main way to perform an actual task is to call the Service method every time the browser requests it. The Servlet container (that is, the Web server) calls the service() method to handle requests from the client (browser), generating a thread for each request and writing the formatted response back to the client. The service() method checks HTTP request types (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., when appropriate.
-
DoGet () : Handles an HTTP request without specifying method
-
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { / / the Servlet code } Copy the code
-
-
DoPost () : Handles an HTTP request with method specified as POST
-
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { / / the Servlet code } Copy the code
-
-
-
The Servlet terminates by calling the destroy() method.
-
Called at the end of the Servlet life cycle, it is called only once. The destroy() method lets your Servlet close database connections, stop background threads, write Cookie lists or click counters to disk, and perform other similar cleanup activities. After calling the destroy() method, the servlet object is marked for garbage collection.
-
public void destroy(a) { // Terminating code... } Copy the code
-
-
Finally, servlets are garbage collected by the JVM’s garbage collector.
Servlet instance creation
There are two creation methods: inherit HttpServlet abstract classes and declare Servlet interfaces. The former is usually used.
Inherit the HttpServlet abstract class
See the TomcatTest file in Eclipse for details. Inheriting this class in IDEA requires you to override the methods yourself
Web application developers often write Servlet to extend the javax.mail. Servlet. HTTP. HttpServlet, and implement the Servlet interface of an abstract class is dedicated to the processing of HTTP requests.
Under Dynamic Web Project, servlets can be created just like any other Java class, as follows:
-
Create a new package com.hsh.test under the SRC package and add a new Serlvet class named HelloServlet that inherits the Abstract HttpServlet class.
public class HelloServlet extends HttpServlet{ // Local variables / / init () method @Override public void init(ServletConfig config) throws ServletException { super.init(config); // The ServletConfig object of this Servlet object cannot be obtained // Because the ServletConfig object is stored in the Init method of GenericServlet, if the subclass overrides the Init method and does not call the Init method of GenericServlet, You can't get your ServletConfig object in the current HelloServlet } // methods in service / / destory () method } Copy the code
-
Fill in the following code in the doGet method of the HelloServlet class
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // Use GBK to set the Normal display of Chinese response.setCharacterEncoding("GBK"); response.getWriter().write("hello world"); } Copy the code
-
Configure in the web.xml file to add the servlet object you just created to the server as follows
<web-app version="2.5" 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/web-app_2_5.xsd"> <servlet> <! - the name of the class -- -- > <servlet-name>HelloServlet</servlet-name> <! -- Where is the bag --> <servlet-class>com.runoob.test.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <! -- Visit the url --> <url-pattern>/TomcatTest/HelloServlet</url-pattern> </servlet-mapping> </web-app> Copy the code
Use the servlet tag and the servlet-mapping tag
-
Start the project and see Hello World in your browser
Declare the Servlet Interface
See the ServletTest file in IDEA for details; this method is not commonly used.
-
Create a new HelloServlet class in your Web project that declares the Servlet interface
public class HelloServlet implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException {}@Override public ServletConfig getServletConfig(a) { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("helloServlet accessing"); } @Override public String getServletInfo(a) { return null; } @Override public void destroy(a) {}}Copy the code
-
Configure the HelloServlet in web.xml
The function is to map the domain name to the Java source code
<servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.hsh.test.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> <! --/ : Server address is http://ip: port number/project path --> <! - / hello: the server address when parsing for http://localhost:8080/ServletTest/hello - > <! When the browser accesses the domain name, the server sends the request to the HelloServlet class --> </servlet-mapping> Copy the code
-
Start Tomcat and you can see the printed information on the console
Common configuration errors in web.xml
- The domain name in the URl-pattern tag does not start with a slash
- The full class name in the servlet-class tag is incorrect. You are advised to copy the full class name
- The contents of the two servlet-name tags are different
Pay attention to
- You can create a Servlet object directly in idea that automatically generates the doGET and doPost methods
Classes and interfaces involved in servlets
Servlet class inheritance system
Servlet interface —–> GenericServlet class ——> HttpServlet class —–> Implementation class of HttpServlet
- The Servlet interface defines the behavior of servlets
- The GenericServlet class declares the Servlet interface, makes many empty implementations, and holds a reference to the ServletConfig class
- The HttpServlet class implements the Service method and distributes browser GET and POST requests
- The HttpServlet implementation class overrides the doGet and doPost methods based on the business requirements
ServletConfig class
The ServletConfig class occurs when you create a Servlet instance using the declare Servlet interface method, which defines methods that return information about servlets. But you can also call getServletConfig() in addition to the init method to get the ServletConfig class object for the Servlet.
A Servlet object has a corresponding ServletConfig object.
role
- You can get an alias for the Servlet program, which is the value in the servlet-name tag in web.xml.
- Gets the initialization parameter init-param.
- Get the ServletContext object.
ServletConfig Example
public class HelloServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
String initParameter = servletConfig.getInitParameter("abc"); / / 1234
String servletName = servletConfig.getServletName(); //HelloServlet
ServletContext servletContext = servletConfig.getServletContext();
//org.apache.catalina.core.ApplicationContextFacade@515de15
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { ServletConfig servletConfig = getServletConfig(); }... }Copy the code
Content in web.xml
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.hsh.test.HelloServlet</servlet-class>
<init-param> <! The initialization parameter must be defined in the servlet tag, and only the current servlet can use this parameter.
<param-name>abc</param-name>
<param-value>1234</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Copy the code
The ServletContext interface
- An interface that represents a context object for a Servlet.
- A Web project corresponds to a ServletContext object.
- The ServletContext is a domain object, and this domain is the entire Web project.
- The ServletContext object is created when the Web project is started and destroyed when it is closed.
Domain objects: Objects that access data like maps, where domain refers to the scope of operations that access data. Domain objects generally access data by setAttribute() and getAttribute().
role
- Gets the context parameter context-param configured in web.xml
- Obtain the current project path in/project path format
- Obtain the absolute path where the project is deployed to the hard disk of the server
- Access data like map
ServletContext Example
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletContext();
String a = context.getInitParameter("a");
String b = context.getInitParameter("b");
String contextPath = context.getContextPath();
String realPath = context.getRealPath("/resources");
System.out.println("Initialization parameter:"+a+","+b);
System.out.println("Current project path:+contextPath); // Outputs the address of the web directory in the current module
System.out.println("Project deployment Path:"+realPath); // Outputs the location in the Web directory where resources are deployed on the server disk
/** Initialization parameters: apple,banana Current project path: /servletTest_war_exploded Project deployment path: H:\ideaworkpath\workspace01\out\artifacts\servletTest_war_exploded\resources */
context.setAttribute("key1"."value1");
Object key1 = context.getAttribute("key1");
System.out.println(key1); / / output value1
}
Copy the code
<! The ServletContext object can only get the parameters of the context-param tag, not the contents of the init-param tag of a Servlet tag.
<context-param>
<param-name>a</param-name>
<param-value>apple</param-value>
</context-param>
<context-param>
<param-name>b</param-name>
<param-value>banana</param-value>
</context-param>
Copy the code
Idea engineering structure drawing
It kind of
Every time an HTTP Request is sent to Tomcat, Tomcat will parse the HTTP protocol information into a Request object and then pass it to the Service method for us to use. We can use HttpServletRequest to obtain all the Request information.
Commonly used method
- GetRequestURI () : Gets the requested resource path
- GetRequestURL () : Uniform resource path to get the request (absolute path)
- GetRemoteHost () : obtains the CLIENT IP address
- GetHeader (paraName) : Gets the value of a parameter in the request header
- GetParameter (paraName) : Gets the value of the parameter
- GetParameterValue () : Gets the values of multiple parameters
- GetMethod () : How to GET the request (GET/POST)
- SetAttribute (key,value) : Sets domain data. The life cycle of the domain data depends on the current request
- GetAttribute (key) : Returns domain data
- GetRequestDispatcher () : Gets the request forward object
- Req. setEncoding (“UTF-8”) : To resolve the Character encoding problem, set it before obtaining the parameter
HttpServletResponse class
Each time an HTTP request is sent to Tomcat, Tomcat creates a response object that is passed to the Servlet for use, and then passed to the Service method for us to use. We can use HttpServletRequest to get all the request information.
-
Only one of the getWriter() and getOutputStream() output character streams can be used simultaneously.
-
The response. SetCharacterEncoding (” utf-8 “) set the server’s character set to utf-8
response.setHeader(“Content-Type”,”text/html; Charset =UTF-8″) set the browser to use the UTF-8 character set via the response header
response.setContentType(“text/html; Charset =UTF-8”) set the server, browser, and response headers to use UTF-8
Servlet form data
The browser uses two methods to pass information to the Web server, the GET method and the POST method.
In the front-end HTML page, only the HTTP protocol POST is used when the form sends requests in POST mode, and the rest are used in GET mode
The GET method
- The default method used by browsers, which generates a long string to contain information in the browser and is not suitable for transmitting important information such as passwords. Also, the GET method has a size limit, transferring up to 1024 characters
- The server uses the doGet() method to process GET requests
POST method
- A reliable way for the browser to transfer data to the background, wrapping the information into a single message that is sent to the server in a standard form. The server handles POST requests using the doPost() method
Use a servlet to read form data
Servlets process form data, which is automatically parsed using different methods depending on the situation:
- GetParameter () : Call the request.getParameter() method to get the values of the form parameters.
- GetParameterValues () : This method is called if the parameter appears more than once and returns multiple values, such as check boxes.
- GetParameterNames () : This method is called if you want a complete list of all the parameters in the current request.
GET the instance
-
Use an instance of the GET method of the URL
-
Create a servlet object called HelloForm that takes the parameters from the request and prints them to the browser, and then configure this class object in web.xml
@WebServlet("/HelloForm") public class HelloForm extends HttpServlet {...// omit the constructor protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Read form data using GET method"; // Handle Chinese String name =new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"); String docType = " \n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
- :
+ name + "\n" +- url :
+ request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // The method that handles the POST method request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code -
Enter the URL in your browser: http://localhost:8080/TomcatTest/HelloForm? Name = hee hee haw &url=www.xxhh.com
-
The browser retrieves the name and URL and displays them
-
-
Use the GET method instance of the form
So let’s build on that
-
Create a new hello. HTML file in the WebContent folder
<form action="HelloForm" method="GET">Site name:<input type="text" name="name"> <br />Web site:<input type="text" name="url" /> <input type="submit" value="Submit" /> </form> Copy the code
-
Then visit: http://localhost:8080/TomcatTest/Hello.html to fill out the form and submit, show as below
-
POST instance
-
Use the POST method instance of the form
- Instead of using the doPost method in the HelloServlet, which calls the doGet method to handle the request, simply change the form submission method in hello.html to POST.
-
Pass the checkbox data to the Servlet program
-
Create a checkbox. HTML file under WebContent
<form action="CheckBox" method="POST" target="_blank"> <input type="checkbox" name="java"/>Java <input type="checkbox" name="c"/>C <input type="checkbox" name="php"/>PHP <input type="submit" value="Submit"/> </form> Copy the code
-
Create a Servlet class called CheckBox and configure it in web.xml
. out.println(docType+"<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
- :
+ request.getParameter("java") + "\n" + // Check the name property of the checkbox "- C: :"
+ request.getParameter("c") + "\n" +- :
+ request.getParameter("php") + "\n" + "</ul>\n" + "</body></html>" ); Copy the code -
Run, you can get the form information
-
-
Reading all the forms’ parameters: too tedious
Servlet client HTTP request
When a browser requests a web page, it sends information to the Web server that is transmitted as part of the HTTP request header. You can get this information on the server side using the HttpServletRequest object.
HTTP requests in GET mode
It consists of the request line and the first two parts of the request.
Request information in the row
Request mode GET/ POST
The requested resource path
The version number of the requested protocol
HTTP requests are made in POST mode
By the request line, request header, request body composition.
The request line and header are the same as GET requests, except for the request body. The request body stores the data sent to the server.
Common method of reading HTTP request headers
The serial number | Methods & Description |
---|---|
1 | Enumeration getHeaderNames()Returns an enumeration containing all the headers contained in the request. |
2 | String getHeader(String name)Returns the value of the request header specified by the argument as a string. |
1 | Cookie[] getCookies()Returns an array containing all Cookie objects that the client sent the request to |
Commonly used request header information
Header information | describe |
---|---|
Accept | Represents the type of data that the client can receive |
Accept-Language | Represents the language type that the client can receive |
Cookie | This header returns cookies previously sent to the browser to the server. |
Host | Represents the server and port number at request time |
User-Agent | Represents information about the client’s browser |
Common status codes
- 200: Request succeeded
- 302: Request redirection
- 404: Request server received, but the requested content does not exist (wrong address)
- 500: Request server received, but server internal error (code error)
Gets an instance of the client’s HTTP request
-
Create a servlet class called DisplayerHeader
/ / doGet method. Enumeration<String> header = request.getHeaderNames();// Return all the information in the request header while(header.hasMoreElements()) { String paramName = (String)header.nextElement(); out.print("<tr><td>" + paramName + "</td>\n"); String paramValue = request.getHeader(paramName); // Returns the value of the parameter with the same name in the request header out.println("<td> " + paramValue + "</td></tr>\n"); }...Copy the code
-
Configure the DisplayerHeader class in web.xml and run it
The servlet server responds to an HTTP request
When a Web server responds to an HTTP request, the response usually consists of the response line, the response header, and the response body. The response line includes the HTTP version (HTTP/1.1 in this case), a status code (200 in this case), and a short message corresponding to the status code (OK in this case). The response body is used to store information sent to the client.
Implemented using the HttpServletResponse object. The setContentType method we’ve been using is how the server responds to the request.
Refresh the time in the browser every 5 seconds
-
Create a Servlet class named Refresh
/ / doGet method.// Set the refresh auto loading time to 5 seconds response.setIntHeader("Refresh".5); // Set the response content type response.setContentType("text/html; charset=UTF-8"); Calendar ca = Calendar.getInstance(); Date time = ca.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime = sdf.format(time); PrintWriter out = response.getWriter(); String title = "Auto refresh Header Settings - Rookie tutorial Example"; String docType = " \n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "
Current time is:"
+ nowTime + "</p>\n"); .Copy the code -
Configure it in web.xml
Servlet request forwarding
When multiple servlets are required to process a service, a forwarding request is required. For example, Servlet1 performs basic validation of the request and Servlet2 performs complete validation of the request.
When obtaining the request forwarding object, the parameter must start with /, indicating that it is mapped to the current project path
//Servlet1 doGet method.// Get the forward object of the request, the parameter is the forward target, then jump to the target Servlet2
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/Servlet2"); requestDispatcher.forward(req,resp); .Copy the code
Note:
- Although Servlet2 is accessed by the browser, the address bar does not change because it is treated as a single Request rather than two, and Servlet1 and Servlet2 share the same Request domain.
- Request forwarding can access resources in the WEB-INF directory, but cannot access resources outside the current project (cannot be forwarded to baidu website).
The base label
Defines the base for jumping to the current HTML document, that is, to jump to another page based on the address defined by the Base tag.
<head>
<meta charset="UTF-8">
<title>Title</title>
<base href="http://localhost:8080/servletTest/web/resources/a.html">
</head>
<body>
<a href=".. /b.html">Jump to b.h HTML</a>
<! - a label will jump to http://localhost:8080/servletTest/web/b.html-- >
</body>
Copy the code
/ Meaning in different locations
In the Web, the slash is an absolute path
- In browsers, / is resolved to http://ip:port/, for example, the href of the a tag is equal to /
- / is resolved to http://ip:port/ project path on the server
- Server side: Response.sendreDirect (“/”), which sends/to the browser for parsing. The browser gets http://ip:port/
The Servlet requests redirection
When the browser still accesses the old domain name, the server sends a response with status code 302 and the new address. When the browser receives the response, it accesses the new domain name, so this is two requests, different from request forwarding.
// The first method
/ / doGet method. response.setStatus(302);
response.setHeader("location"."http://www.baidu.com"); // The WEB-INF directory cannot be accessed. -------------------// The second method
response.sendRedirect("http://www.baidu.com");
----------------------
Copy the code
Note: the/in the redirection represents the port number, not the project path, which needs to be obtained using the req.getContextPath() method.
Servlet writes Filter filters
A Filter is a Java class that implements the Javax.servlet.filter interface. Act upon intercepting the request
You can attach one or more Servlet filters to a Servlet or set of servlets. Servlet filters and servlets have a many-to-many relationship.
Servlet filters can also be attached to JavaServer Pages (JSP) files and HTML Pages. JSP and HTML pages can also be filtered.
- Intercepts client requests before they access back-end resources.
- The server’s responses are processed before they are sent back to the client.
Filters are declared by XML tags in the Web deployment descriptor (web.xml), and when the Web container launches the Web application, it creates an instance for each filter you declare in the deployment descriptor.
Filter usage scenarios: permission checking, transaction management, diary operation, and so on.
The order in which filters are executed is the same as in the web.xml configuration file, which generally precedes all servlets.
Configure filters in web.xml
Filters need to be configured in web. XML before being used
<filter>
<filter-name>LogFilter</filter-name> <! --LogFilter is the class that implements the Filter interface and its package name -->
<filter-class>com.hsh.test.LogFilter</filter-class>
<init-param>
<param-name>Site</param-name> <! -- Set an initialization parameter -->
<param-value>Xi xi ha ha</param-value>
</init-param>
</filter>
<filter-mapping> <! Set LogFilter to filter all servlets, /* to filter all servlets -->
<filter-name>LogFilter</filter-name>
<url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code
Filter does not use the label
<servlet-name>
Specifies the name of the Servlet that the filter intercepts.dispatcher>
Specifies how the resource intercepted by the filter is invoked by the Servlet containerREQUEST
.INCLUDE
.FORWARD
andERROR
One, defaultREQUEST
. You can set multiple Settings<dispatcher>
The child element is used to specify that the Filter intercepts multiple calls to the resource.<dispatcher>
The values that children can set and their meaningsREQUEST
The Web container invokes the filter when the user accesses the page directly. This filter is not invoked if the target resource is accessed through the RequestDispatcher’s include() or forward() methods.INCLUDE
This filter is called if the target resource is accessed through the RequestDispatcher’s include() method. Otherwise, the filter is not called.FORWARD
This filter will be called if the target resource is accessed through the Forward () method of the RequestDispatcher, otherwise it will not be called.ERROR
: This filter is invoked if the target resource is invoked through declarative exception handling. Otherwise, the filter is not called.
The Filter interface
Creating an implementation class that declares a Filter interface creates a Filter, with three methods in the Filter interface
-
Public void init(FilterConfig FilterConfig) :
When the Web application starts, the Web server creates an instance object of Filter and invokes its init method to read the web.xml configuration and initialize the object, thus preparing it for subsequent interception of user requests (the Filter object is created once and the init method is executed only once). The developer gets the FilterConfig object representing the current Filter configuration information through the parameters of the init method.
-
Public void doFilter (ServletRequest, ServletResponse, FilterChain) The Servlet container first calls the doFilter method of the filter. FilterChain Users access subsequent filters.
-
Public void Destroy () This method is called by the Servlet container before the filter instance is destroyed, freeing resources occupied by the Servlet filter in this method.
Filter Life cycle
1. Constructor method
- Init () : 1,2 are executed when the web project is started
- DoFilter () : executes each time a request is intercepted
- Destory () : executed when the Web server is shut down
The FilterConfig class
Filter configuration file class. Tomcat creates a FilterConfig each time it creates a Filter, which contains the configuration information of the Filter.
Function:
- Gets the content of Filter filter-name configured on the Web, along with the value of init-param
- Get the ServletContext object
FilterChain interface
A FilterChain is a FilterChain that controls the execution of multiple filters.
The order in which filters are executed is determined by the order in which they are defined in web.xml.
If you comment out chester.dofilter () and postcode 2 of Filter2, postcode 2 of Filter1 will be executed after precode 1 of Filter2 is executed, not the target resource.
Filter Intercepting path
- < url-pattern>/resource/a.jsp < /url-pattern>
- < url-pattern>/resource/* < /url-pattern>
- The suffix matches: < url-pattern>*.jsp < /url-pattern>, without a slash, intercepts all requests ending in.jsp
Filter instance
-
The filters have already been configured in web.xml
-
Create a Filter interface implementation class named LogFilter
public class LogFilter implements Filter {...// public void init(FilterConfig fConfig) throws ServletException { String filterName =fConfig.getFilterName(); //LogFilter String initParameter = fConfig.getInitParameter("Site"); // Get the parameters set in filter in init ServletContext servletContext = fConfig.getServletContext(); //ServletContext System.out.println("Site name:"+ initParameter); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Site address: http://www.xxhh.com"); // pass the request along the filter chain chain.doFilter(request, response); } public void destroy(a) {}}Copy the code
When you visit any domain name when you start the server, the console first prints “site name: Hee Hee Ha ha” and then prints “site URL: www.xxhh.com” once. Continue to visit the current page will print again “site url… “.
Servlet Exception Handling
Instances of exception handling inherit from HttpServlet
When a Servlet throws an exception, the Web container searches the web.xml that uses the exception-type element for the configuration that matches the type of exception thrown. Use the error-Page element in web.xml to specify the corresponding Servlet call for a particular exception or HTTP status code.
Exception Handling Example
-
Create an exception handling instance named ErrorHandler and place it in /webapps/ROOT/WEB-INF/classes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the exception information in the request Throwable throwable = (Throwable)request.getAttribute("javax.servlet.error.exception"); Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code"); String servletName = (String)request.getAttribute("javax.servlet.error.servlet_name"); if (servletName == null){ servletName = "Unknown"; } String requestUri = (String)request.getAttribute("javax.servlet.error.request_uri"); if (requestUri == null){ requestUri = "Unknown"; } // Display instructions according to the exception information. }Copy the code
-
Configure the ErrorHandler exception handling instance and HTTP fault code in web. XML.
<servlet> <servlet-name>ErroeHandler</servlet-name> <! -- --> <servlet-class>com.hsh.test.ErroeHandler</servlet-class> </servlet> <servlet-mapping> <servlet-name>ErroeHandler</servlet-name> <url-pattern>/TomcatTest/ErroeHandler</url-pattern> </servlet-mapping> <error-page> <! -- Register error code --> <error-code>404</error-code> <location>/TomcatTest/ErroeHandler</location> </error-page> <error-page> <error-code>java.lang.Throwable</error-code> <! Servlet exceptions are also handled by ErrorHander --> <location>/ErrorHandler</location> </error-page> Copy the code
-
Start the server and search for an incorrect URL
servlet cookie
Cookie is a text file stored on the client computer, which retains various user information. Java servlets support handling HTTP cookies.
Identifying returned users involves three steps:
- The server script sends a set of cookies to the browser. For example: name, age or identification number, etc.
- The browser stores this information on the local computer for future use.
- The next time the browser sends any request to the Web server, the browser sends this Cookie information to the server, which uses it to identify the user.
Cookie parsing
Cookies are usually set in HTTP headers, but JavaScript can also set a Cookie directly on the browser
Set cookies through servlets
There are three main steps:
-
Creating a cookie object
Cookie cookie = new Cookie("key"."value"); ----------- // Gets the URL property in the submission form and uses it to create a cookie object Cookie url = new Cookie("url",request.getParameter("url")); Copy the code
-
The cookie survival time is set
cookie.setMaxAge(60*60*24); // The unit is seconds ------- url.setMaxAge(60*60*24); Copy the code
-
Adds the cookie object to the response
response.addCookie(cookie); ------- response.addCookie(url); Copy the code
Cookies are obtained through servlets
Cookie[] cookies = request.getCookies(); // Get all the name value objects stored in the Cookie in the request header
Cookie cookie = cookies[0]; // Assign the first object in the request header to cookie
cookie.getName(); // Get the name of the cookie
cookie.getValue(); // Get the value of the cookie
Copy the code
Cookies are deleted through servlets
Change the maximum lifetime of the cookie object to 0 and add it to the response header
cookie.setMaxAge(0); // The cookie object is deleted
response.addCookie(cookie);
Copy the code
servlet session
The HTTP protocol is a “stateless” protocol, meaning that each request made by a client establishes a separate connection to the Web server, which does not keep any record of previous requests made by the client.
The following four methods are used to maintain session sessions between web servers and clients
Cookies
The Web server assigns a unique session ID as the client’s cookie, which the server uses in subsequent requests to identify the received cookie. Most browsers don’t support it, so it’s not recommended
Hidden form fields
The URL rewrite
The httpSession object
Servlets provide the HttpSession interface, which provides a way to identify users and store information about them when requesting or visiting a web site across multiple pages
Servlet database access
Servlet file upload
Servlets can be used with HTML form tags, and uploaded files can be text files or image files, or any document.
Servlet processing date
The servlet redirects
The simplest way is to use the sendRedirect() method of the Response object
The servlet counter
Page click counter
Website hit counter
supplement
The role of the servlet
Between the browser and the server, used to receive and send data
The role of the web.xml
It’s kind of a container between the server and the code, so the server knows what instances are in the code, how to talk to the code,