Introduction to Servlet foundation of JavaWeb (Part 3) - filter and listener
The three major components of Java Web are Servlet program, Filter filter and Listener listener. Earlier, we learned about servlets. Next, we'll learn about Filter filters and Listener listeners.
1. Filter filter
1.1 what is a Filter
Filter filter, which is the specification of Java EE. That is, the interface. The specified URL request can be intercepted and then processed / judged in the filter.
Filter filter is used to intercept requests and filter responses.
Common application scenarios for intercepting requests include: 1) permission check; 2) Journal operation; 3) Transaction management... Etc.
1.2 introduction to Filter
Case description: on the home page, visit the personal information page. If you don't log in, you are not allowed to visit.
1) Write a class to implement the Filter interface
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class FilterDemo implements Filter{ /** * Used to intercept requests */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession session = httpServletRequest.getSession(); Object user = session.getAttribute("user"); // If it is equal to null, it indicates that you have not logged in: you are not allowed to access the private page if (user == null) { request.getRequestDispatcher("/login.jsp").forward(request, response); return; } else { // Let the program continue to access the user's target resources: if there are no other filters, it will access the requested resources; If there is a filter, continue to other filters chain.doFilter(request,response); } } }
2) Write an InfoServlet
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InfoServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gbk"); PrintWriter out = response.getWriter(); out.println("Private space, please check carefully!"); } }
3) Modify the index.jsp home page
<body> <div>I'm the top of the page</div> <a href="/persion/infoServlet">View my info</a> <div>I'm at the end of the page</div> </body>
4) Configure web.xml
<!--filter Label is used to configure a Filter filter--> <filter> <filter-name>FilterDemo</filter-name> <filter-class>com.cn.filterAndListener.FilterDemo</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo</filter-name> <!-- Matching rules are the same as servlet,support/*Also support*.do .../persion/infoServlet Access to this link will be blocked --> <url-pattern>/persion/infoServlet</url-pattern> </filter-mapping>
Case effect:
Successfully intercepted, but we found a problem. My previous login page was forwarded. How come the verification code is not displayed? After checking, it seems that the path is wrong:
Extension: supplement the function of base tag
public class FilterDemo implements Filter{ /** * Used to intercept requests */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession session = httpServletRequest.getSession(); Object user = session.getAttribute("user"); // If it is equal to null, it indicates that you have not logged in: you are not allowed to access the private page if (user == null) { //Note: "/" follows the directory request.getRequestDispatcher("/"), indicating the current project http://localhost:8080/ //When I use / login.jsp, it can indeed be forwarded to the login page, but the url of the login page at this time: http://localhost:8080/persion/infoServlet request.getRequestDispatcher("/login.jsp").forward(request, response); return; } else { // Let the program continue to access the user's target resources: if there are no other filters, it will access the requested resources; If there is a filter, continue to other filters chain.doFilter(request,response); } } }
<!--hold src Copy the directory--> <img id="codeimg" style="width: 60px;height:20px;" src="ImageServlet?0.14947579772812647"> The link to jump is: http://localhost:8080/persion/ImageServlet?0.14947579772812647 We're not here login.jsp Statement in<base>there base The default path is http://localhost:8080/persion/ <!--base The address of the reference address when the relative path of the label setting page works href Property is the address value of the parameter --> So we got the appeal address, so the verification code could not be displayed hold js The code in is changed as follows: it's found to be normal, but it's not good. We don't know the layer of the business. This practice is not common window.document.getElementById("codeimg").src="../"+url+"?"+Math.random(); We are login.jsp Add to page base Set the reference address when the page relative path works <base href="/">
Finally we see:
1.3. Filter application
1.3.1 the filter solves the problem of Chinese garbled code
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { //First set a wave of character coding for full interception request.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); }
2. Listener listener
2.1. What is a listener
If you have a GUI Graphical interface of JAVA, you should have contacted many listeners. For example, monitor keyboard events and button click events, and then trigger an action. This is the function of the listener: it triggers automatically without active call.
A listener is an ordinary java program that implements a specific interface. This program is specially used to listen for method calls or property changes of another java object. When the above events occur on the monitored object, a method of the listener will be executed immediately.
Several types of listeners are defined in the Servlet specification:
1) Creation and destruction of listening objects
a) ServletRequestListener: can be notified when a request is made
b) HttpSessionListener: it can be used to collect online user information or get notification when changing the session list
c) ServletContextListener: you can get the parameter configuration in web.xml
2) Listening object attribute change
a)ServletContextAttributeListener
b)HttpSessionAttributeListener
c)ServletRequestAttributeListener
3) Listen to Session object
a)HttpSessionBindingListener
b)HttpSessionActivationListener
2.2 introduction to listener
1) Create a new ListenerDemo
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class ListenerDemo implements HttpSessionListener,HttpSessionAttributeListener{ // This operation is triggered when a new session is created public void sessionCreated(HttpSessionEvent se) { System.out.println("Create a new session"); } // This action is triggered when a session is added public void attributeAdded(HttpSessionBindingEvent e) { HttpSession session = e.getSession(); String name = (String) session.getAttribute(session.getAttributeNames().nextElement()); System.out.println("I can put session Add to object,Value is:"+name); } public void attributeRemoved(HttpSessionBindingEvent e) { System.out.println("I can put session Remove from object"); } public void attributeReplaced(HttpSessionBindingEvent e) { System.out.println("replace"); } }
2) Modify xml
<listener> <!-- <display-name>ListenerDemo</display-name> --> <listener-class>com.cn.filterAndListener.ListenerDemo</listener-class> </listener>
3) Use our previous case: SessionDemo
Case effect:
Note: the execution sequence of the three: listener - > filter - > servlet. It is simply recorded as: listener, filter and servlet
3. Other knowledge supplement
3.1. Error page
1) New ExceptionServletDemo
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 ExceptionServletDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int i = 9/0; System.out.println("Big brother, the code is wrong!!!"); } }
2)web.xml
<servlet> <servlet-name>ExceptionServletDemo</servlet-name> <servlet-class>com.cn.filterAndListener.ExceptionServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>ExceptionServletDemo</servlet-name> <url-pattern>/ExceptionServletDemo</url-pattern> </servlet-mapping> <!--Page to enter in case of configuration error--> <error-page> <exception-type>java.lang.ArithmeticException</exception-type> <location>/error.jsp</location> </error-page> <!--It can also be configured--> <error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page>
Case effect:
3.2. Upload and download
3.2.1 upload
Required: (SmartUpload.jar) package
import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.File; import com.jspsmart.upload.Files; import com.jspsmart.upload.Request; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String dirPath = this.getServletContext().getRealPath("/images"); // Receive files uploaded by the client // Create a SmartUpload object to receive file uploads SmartUpload su = new SmartUpload(); // Initialize the data in the request through the su object su.initialize(this.getServletConfig(), request, response); // Set the limit information of the file su.setAllowedFilesList("jpg,png,bmp,gif"); // Set a single uploaded file to 2M su.setMaxFileSize(2 * 1024 * 1024); // Execute upload: after uploading, the data submitted by the page is in the su object su.upload(); // Get data (files and fields) from su objects // Get the file uploaded in su Files files = su.getFiles(); // Gets the request object containing all text fields Request r = su.getRequest(); // Traverse files to get all uploaded files (batch upload is allowed) for (int i = 0; i < files.getCount(); i++) { File file = files.getFile(i); file.saveAs(dirPath + "/" + file.getFileName()); } // Get the required fields from r String name = r.getParameter("userName"); String pass = r.getParameter("userPass"); String[] fns = new java.io.File(dirPath).list(); ArrayList<String> fileNames = new ArrayList<String>(); for (String f : fns) { fileNames.add(f); } request.setAttribute("fileNames", fileNames); request.getRequestDispatcher("list.jsp").forward(request, response); } catch (SmartUploadException e) { e.printStackTrace(); } } }
3.2.2 Download
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Accept the file name that the client needs to download String fileName = request.getParameter("fname"); // Get the directory where the file is stored String dirPath = this.getServletContext().getRealPath("/images"); // The file to download is File f = new File(dirPath + "/" + fileName); // Before sending the picture information to the client, set the format of the response information // Set the format of the corresponding data to a format that cannot be parsed by the browser response.setContentType("application/pdf"); // Set the header information of the file response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // Sets the size of the response data response.setContentLength((int) f.length()); // Start downloading FileInputStream fis = new FileInputStream(f); OutputStream out = response.getOutputStream(); byte[] buff = new byte[102400]; int len = -1; while ((len = fis.read(buff)) != -1) { out.write(buff, 0, len); out.flush(); } out.close(); } }