First, cookie introduction

1. What is session tracing technology

Session tracing is a common technique used in Web programs to track a user’s entire session. Maintain data management for the duration of user sessions. Common Session tracking techniques are cookies and sessions.

  • Cookies identify users by logging information on the client side. (Generally store less important information to prevent it from being cracked and obtained illegally)
  • Session identifies users by logging information on the server. (Important information is stored here)

2. What is a cookie

Cookie is an identification mark sent by the server to the client after the client (generally referring to the browser) requests the server and is stored in the client. When the client sends a request to the server again, it carries this identification mark and the server can use this identification mark to identify the identity or status of the client.

What cookies do: Session tracking, record a Session (i.e., Session, a Session there may be multiple requests, of course, there can be multiple cookies to keep track of different information), the server will know the status of the user, such as have login successfully, the time of payment the things in the shopping cart, etc., and is equivalent to note posted on the client side forehead, The browser doesn’t see it, but the server does.

Ii. Cookie Use (Example Demonstration)

1, create a Web project, introduce [Javaee-API-7.0. jar, jstl.jar, standard.jar], write index.jsp in the Web directory, to achieve a simple login page

<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title>$title $</title> </head> <body> <h1> Login </h1> <form action="login" Method ="post"> username :<input type="text" name="username"> <input type="password" name="pass"><br> <input type="submit" value="login"> </form> </body> </html>Copy the code

2. Write a simple LoginServlet and configure it with annotations

package com.xrh.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(urlPatterns = "/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("error.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. String username = req.getParameter("username"); String pass = req.getParameter("password"); If ("admin".equals(username)&&"123456".equals(pass)){resp.sendreDirect ("success.jsp"); }else{// Login failed (redirect to login page) resp.sendreDirect ("index.jsp"); }}}Copy the code

3, simply write error. JSP, success.jsp

4, run to see the effect

5, after filling in the user name/password, refresh the page, you will find that the input box has disappeared, but in some scenarios, you need to save the user name/password, then you need to introduce cookies. Add cookies before login failure jump page in LoginServlet

package com.xrh.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(urlPatterns = "/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("error.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. String username = req.getParameter("username"); String pass = req.getParameter("password"); If ("admin".equals(username)&&"123456".equals(pass)){resp.sendreDirect ("success.jsp"); Cookie cookie = new cookie ("uname",username); //2. Return the front-end resp.addcookie (cookie); resp.sendRedirect("index.jsp"); }}}Copy the code

6. Get the cookie from the little script in index.jsp and display it

<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <% Cookie[] cookies = request.getCookies(); String value =""; if(cookies! =null&&cookies.length>0){ for (Cookie cookie : cookies) { if(cookie.getName().equals("uname")){ value = cookie.getValue(); break; } } } pageContext.setAttribute("unamecookie",value); <form action="login" method="post"> username :<input type="text" name="username" value="${unamecookie}"><br> <input type="password" name="password"><br> <input type=" value="login"> </form> </body> </ HTML >Copy the code

7. After you click login, the user name is still the same as that entered last time

8. Use the tool to view cookies

Third, common methods of cookie

1. Delete the cookie

By setting the maximum lifetime of a Cookie with the same name to 0, deleting a Cookie means that the browser no longer saves the Cookie and the Cookie becomes invalid immediately

For example, disable the Cookie whose name is username immediately

Cookie Cookie = new Cookie("username", "aaa"); Cookie. SetMaxAge (0); //2. Response.addcookie (cookie); response.addcookie (cookie);Copy the code

2. The validity time of Cookie

After a Cookie is sent to the browser, the browser does not keep it forever, that is, the browser destroys the Cookie automatically after a certain period of time.

The default duration of cookies is one session (opening and closing the browser). You can also manually specify the duration of cookies

//setMaxAge is used to set the maximum duration of the Cookie. An int is required to represent the number of seconds in which the Cookie is valid. // If the parameter is greater than 0, cookie.setMaxAge(30) is set to the specified number of seconds; Cookie. SetMaxAge (0); // If the parameter is less than 0, the current session is valid cookie.setMaxAge(-100); Cookie. SetMaxAge (60*60*24*365*10);Copy the code

Fourth, session usage

1. What is session

Session is another mechanism for recording the client’s state, except that cookies are stored in the client browser, while sessions are stored on the server. When the client browser accesses the server, the server records the client information in some form on the server. So that’s Session. The client browser only needs to look up the client’s status from the Session when revisiting.

If the Cookie mechanism determines the identity of a customer by checking the “pass” on the customer, the Session mechanism determines the identity of the customer by checking the “customer list” on the server. A Session is a client file created by the program on the server. When a client visits the server, it only needs to query the client file table.

2. Create session format

Corresponding class Session for javax.mail. Servlet. HTTP. HttpSession class.

Each visitor corresponds to a Session object, in which all state information about that client is stored.

The Session object is created when the client first requests the server.

Session is also a key-value attribute pair. The getAttribute(Stringkey) and setAttribute(String Key, Objectvalue) methods are used to read and write customer status information.

The client’s Session is obtained in the Servlet using the request.getSession() method

HttpSession session = request.getSession(); // Get the Session object session.setAttribute("loginTime", new Date()); Println ("loginTime: "+(Date) session.getattribute ("loginTime")); // set the Session attribute out.println(" loginTime:" +(Date) session.getattribute ("loginTime")); // Get the Session attributeCopy the code

3. The life cycle of session

The Session is stored on the server side. For faster access, servers typically store sessions in memory. Each user will have a separate Session.

If the Session content is too complex, it can cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as minimal as possible. (Don’t store a lot of irrelevant information in a session.)

A Session is automatically created when a user accesses the server for the first time. Note that a Session is created only when accessing programs such as JSPS and servlets, but not when accessing static resources such as HTML and IMAGE.

Request. getSession(true) can be used to force a Session to be generated if no Session has been generated.

After a Session is generated, the server updates the last access time of the Session and maintains the Session as long as the user continues to access the Session. Each time a user accesses the server, regardless of whether the user reads or writes a Session, the server considers that the user’s Session is active. As more and more users access the server, more and more sessions are created. To prevent memory overflow, the server removes sessions that have not been active for a long time from memory. This time is the Session timeout. If the server is not accessed after the timeout period, the Session is automatically invalidated.

The Session timeout period is maxInactiveInterval. You can obtain the value from getMaxInactiveInterval() and change it from setMaxInactiveInterval(longInterval).

Session timeout can also be changed in web.xml. Alternatively, you can invalidate a Session by calling its invalidate() method.

<session-config> 
 <session-timeout>30</session-timeout>
</session-config>
Copy the code

4. Common methods

5. Session application

5.1 the login

1. After the account password is verified correctly, add session

package com.xrh.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; @WebServlet(urlPatterns = "/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("error.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. String username = req.getParameter("username"); String password = req.getParameter("password"); If ("admin".equals(username)&&"123456". Equals (password)){// Login succeeds //session saves the value HttpSession session = req.getSession(); session.setAttribute("username",username); session.setAttribute("password",password); session.setMaxInactiveInterval(60*30); Resp.sendredirect ("success. JSP "); resp.sendreDirect ("success. JSP "); resp.sendredirect ("success. Cookie cookie = new cookie ("uname",username); //2. Return the front-end resp.addcookie (cookie); resp.sendRedirect("index.jsp"); }}}Copy the code

2, write the success.jsp page

<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>success.jsp</h1> ${sessionscope. username}<br> </body> </ HTML >Copy the code

3. Enter the correct account and password. The login succeeds

5.2 quit

1. Add an exit link in success.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>success.jsp</h1> ${sessionscope. username}<br> <a href="loginout">Copy the code

2. Create LogoutServlet

package servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(urlPatterns = "/loginout") public class LoginOutServlet extends HttpServlet { @Override protected void Throws ServletException, IOException {// The hyperlink is a get request, So just override the get method req.getSession().invalidate(); Resp.sendredirect ("index.jsp"); resp.sendredirect ("index.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); }}Copy the code

3. Run the program, input the account password correctly, click exit, and find that the session cannot be obtained

Fifth, the difference between cookie and session

Cookie data is stored on the client and Session data is stored on the server.

A Session is a storage space on the server maintained by the application server. When users connect to the server, the server generates a unique SessionID and uses the SessionID as an identifier to access the Session storage space on the server. The SessionID data is saved to the client using cookies. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process is done without developer intervention. So once the client disables the Cookie, the Session is also invalidated.

Cookies are a type of Session object. Cookies, however, do not occupy server resources. Instead, they are stored in client memory or a Cookie text file. Sessions take up server resources. So try not to use sessions and use Cookies instead. However, we generally believe that Cookies are not reliable. Cookies are saved on the local machine, but their information is completely visible and easy to edit locally, which can often cause many security problems. Session is reliable. But cookies are also used by many well-known sites today.

Six, filter

1. What is a filter

Filters actually intercept Web resources, do some processing and then hand over to the next filter or servlet for processing, usually used to intercept requests for processing, can also intercept the response returned

2. Syntax format for filters

Create a class that implements the Filter interface

public class CharSetFilter implements Filter{}
Copy the code

2. Override methods in the interface

Public void doFilter(ServletRequest, ServletResponse resp, ServletResponse resp, ServletResponse resp, FilterChain chain) throws ServletException, IOException {// The filtering method mainly processes request and response. It then passes to the next filter or Servlet to process chain.dofilter (REq, RESP); } public void init(FilterConfig config) throws ServletException {/* The initialization method receives a parameter of type FilterConfig, which is some configuration of Filter */}Copy the code

3. Configure it in the web. XML file

<filter> <filter-name> Filter name </filter-name> <filter-class> Path of the filter </filter-class> </filter> <filter-mapping> <filter-name> Filter name </filter-name> <url-pattern> Resources to be filtered </url-pattern> </filter-mapping>Copy the code

3. Code demonstration

Write the FirstFilter class in the SRC /util package

package util; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class FirstFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {system.out.println (" Initialize filter"); Public void doFilter(ServletRequest ServletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {system.out.println (" Filter start "); // Call the next filter, or call the servlet filterchain.dofilter (servletRequest, servletResponse); System.out.println(" filter end "); } public void destroy() {system.out.println (" destroy filter"); }}Copy the code

2. Add the configuration to web.xml

    <filter>
        <filter-name>f1</filter-name>
        <filter-class>
            util.FirstFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>f1</filter-name>
        <url-pattern>/login</url-pattern>
    </filter-mapping>
Copy the code

3. Set multiple filters. Writing filter 2

package util; import javax.servlet.*; import java.io.IOException; public class SecondFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws Println (" initialize 2filter"); ServletException {system.out.println (" initialize 2filter"); Public void doFilter(ServletRequest ServletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {system.out.println (" Filter 2 starts "); // Call the next filter, or call the servlet filterchain.dofilter (servletRequest, servletResponse); System.out.println(" filter 2 ends "); } @override public void destroy() {system.out.println (" destroy "); }}Copy the code

    <filter>
        <filter-name>f2</filter-name>
        <filter-class>
            util.SecondFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>f2</filter-name>
        <url-pattern>/login</url-pattern>
    </filter-mapping>
Copy the code

4. Observe the order in which filters 1 and 2 are executed first, depending on the configuration file

5. Add functionality to FirstFilter to prevent unlogged users from accessing resources

package util; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class FirstFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {system.out.println (" Initialize filter"); Public void doFilter(ServletRequest ServletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {system.out.println (" Filter start "); HttpServletRequest =(HttpServletRequest)servletRequest; HttpServletResponse response=(HttpServletResponse)servletResponse; request.setCharacterEncoding("utf-8"); String requestURI = request.getrequesturi (); // Prevent users from accessing resources without logging in. System.out.println("requestURI="+requestURI); Object username = request.getSession().getAttribute("username"); // When the user accesses the testsession.jsp page, Index.jsp if(requesturi.endswith ("testsession.jsp")&&username==null){response.sendreDirect ("index.jsp"); } // Call the next filter, or call the servlet filterchain.dofilter (servletRequest, servletResponse); System.out.println(" filter end "); } public void destroy() {system.out.println (" destroy filter"); }}Copy the code

6, change the web.xml configuration so that all pages need to execute FirstFilter (/login instead of /*)

    <filter>
        <filter-name>f1</filter-name>
        <filter-class>
            util.FirstFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>f1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Copy the code

7. Operation effect

When you access the TestSession page without logging in, you are automatically redirected to index.jsp.

It can be accessed after login.

When you exit and access the TestSession page, you are automatically redirected to index.jsp.

4. Application scenarios

  • 3.1. How can I prevent subsequent operations before a user logs in

    String name=(String)session.getAttribute(“key”); If (name==null){// jump to login page}

  • 3.2. Set the encoding mode — Set the encoding uniformly
  • 3.3. Encryption and decryption (encryption and decryption of passwords)
  • 3.4. Illegal text filtering
  • 3.5. Restrictions on downloading resources

Filters are executed before and after servlets

Seven, the listener

1. What is a listener

A listener is a component that listens for state changes in a domain object

Related concepts of listeners:

  • Event source: listening object (three domain objects request, Session, servletContext)
  • Listener: Listening for event source objects Changes in the state of event source objects trigger listeners
  • Register listeners: Bind listeners to event sources
  • Response behavior: The functional code involved when listeners listen for changes in the state of the event source (programmer writing code)

2. Classification of listeners

The first dimension is divided into ServletRequest domains, HttpSession domains, and ServletContext domains

The second dimension is divided according to the monitoring content: the creation and destruction of the monitoring domain object, and the change of the properties of the monitoring domain object

3. Code demonstration

Write SessionListener and AttributeListener

package util; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent HttpSessionEvent) {system.out.println (" Session creation "); } @override public void sessionDestroyed(HttpSessionEvent HttpSessionEvent) {system.out.println ("session destruction "); }}Copy the code

package util; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class AttributeListener implements HttpSessionAttributeListener { @Override public void AttributeAdded (HttpSessionBindingEvent HttpSessionBindingEvent) {system.out.println (" Session store value, "+httpSessionBindingEvent.getName()+","+httpSessionBindingEvent.getValue()); } @Override public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) { System.out.println(" Session removes data "); } @Override public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) { } }Copy the code

2. Modify the web. XML configuration

<! SessionListener</listener-class> </listener> <listener> <listener-class>util.AttributeListener</listener-class> </listener>Copy the code

3. Operation effect

4. Listeners that listen for the creation and destruction of three domain objects

4.1 Life Cycle

The life cycle of the Servlet domain

  • Create: The server starts creation
  • Destroy: Server shutdown destroy

The lifetime of the HttpSession object

  • Created: created the first time request.getSession is called
  • Destruction: The server shuts down the destruction, the session expires (default 30 minutes, change the default 30 minutes is in Tomcat web. XML, change the expiration time of the current project is in your own project web

The lifecycle of a ServletRequest

  • Create: Request is created for each request
  • Destroy: Request terminated

4.2 ServletContextListener

A listener that listens for the creation and destruction of the ServletContext domain

  • Initialization work: initializing objects, initializing data (loading database drivers, initializing connection pools)
  • Load some initial configuration files (Spring configuration files)
  • Task scheduling (Timer – Timer/TimerTask)

4.3 HttpSessionListener

A listener that listens for the creation and destruction of the Httpsession domain

Since a session object is created by default every time a site is visited (the session attribute in the PAGE directive in the JSP page defaults to True, that is, when a session is visited), it can be used to count the number of people visited by the site.

4.4 ServletRequestListener

Listeners that listen for the creation and destruction of the ServletRequest domain

The chapter summary is here (the better we understand you guys, the better we understand you guys).

Students who are interested in learning Java are welcome to join QQ Learning exchange group: 1126298731

Have a question welcome to ask, everyone together in learning Java on the road to play strange upgrade! (O ゜ – ゜▽゜)