Spring MVC Induction-2(Session Session Session, Interceptor)

Keywords: Java Session

Main points:

HttpSession: The establishment of a session starts with a user sending the first request to the server, and ends with an explicit end of the user or session timeout. With session, user status can be recorded in a certain time.

2.ModelAndView: You can either set the URL address or render the view.

3. Handler Interceptor: The interceptor interface can customize an interceptor by implementing three methods of interface modification (preHandle, postHandle, afterCompletion).

 

Examples:

Realize login and shopping cart functions.

 

  login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Lok login</title>
</head>
<body>
    <form action="http://localhost:8888/login-commit" method="post">
        <input type="submit" value="login">
    </form>
</body>
</html>

 

  mall.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Le Tao shopping mall</title>
</head>
<body>
    <form action="http://localhost:8888/shopcar" method="POST">
        <label>Please choose the books you want to buy:<br>
            <input type="checkbox" name="bookname" value="C Prime Plus">C Prime Plus<br>
            <input type="checkbox" name="bookname" value="C Prime Plus2">C Prime Plus2<br>
            <input type="checkbox" name="bookname" value="C Prime Plus3">C Prime Plus3<br>
            <input type="checkbox" name="bookname" value="C Prime Plus4">C Prime Plus4<br>
        </label>
        <input type="submit" value="Add to cart">
    </form>
    <form action="http://localhost:8888/quit" method="POST">
        <input value="log out" type="submit">
    </form>
</body>
</html>

 

  myshoppingcar.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Letao shopping cart</title>
</head>
<body>

    <h2>My shopping cart:</h2>
    <!--Show the purchased books when there is a purchase-->
    <ul th:if="${books.size()} != 0">
        <li th:each="bookcount:${books}" th:text="${bookcount}"></li>
    </ul>
    <!--No purchase-->
    <div th:if="${books.size()} == 0">
        You haven't bought any books!        
    </div>
    <form action="http://localhost:8888/mall" method="GET">
        <input type="submit" value="Continue to buy">
    </form>
    
</body>
</html>

 

  Books.java

package com.example.demo.controller.login;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Books {
    
    private HashMap<String,Integer> books = new HashMap<String,Integer>(); 
    
    //According to request URL Get an array of forms to update existing books
    public void refreshBooks(String[] newbooks) {
        
        for (String book:newbooks) {
            
            if (books.containsKey(book)) {
                books.put(book, books.get(book)+1);
            }else {
                books.put(book, 1);
            }
        }
    }
    
    //Obtain books Collection, to page
    public Set<Entry<String, Integer>> getbooks(){
        return books.entrySet();
    }
}

 

  LoginController.java

package com.example.demo.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {
    
    //Login interface
    @GetMapping("login")
    public String getLogin(HttpServletRequest req) {
        HttpSession session = req.getSession();
        
        //Logged in and went directly to the mall
        if (session.getAttribute("login")!=null) {
            return "redirect:mall";
        }
        
        return "login";
    }
    
    //Logon request processing
    @PostMapping("login-commit")
    public String postLogin(HttpServletRequest req) {
        HttpSession session = req.getSession();
        
        //session Mark logon status
        session.setAttribute("login",true);
        
        return "redirect:mall";
    }
    
    //Log out and keep shopping records
    @PostMapping("quit")
    public String quit(HttpServletRequest req) {
        HttpSession session = req.getSession();
        
        session.removeAttribute("login");
        
        return "redirect:login";
    }
    
}

 

  ShoppingController.java

package com.example.demo.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ShoppingController {
    
    //Market
    @GetMapping("mall")
    public String getMall() {
        return "mall";
    }
    
    //My shopping cart
    @PostMapping("shopcar")
    public ModelAndView getShopCar(ModelAndView view,HttpServletRequest req) {
        
        HttpSession session = req.getSession();
        Books books = (Books) session.getAttribute("shopcar");//session Conversational acquisition of purchased books
        String[] newbooks = req.getParameterValues("bookname");//New shopping requests
        
        //Never bought
        if (books==null){
            books = new Books();
        }
        
        //Refresh session Conversation
        if (newbooks!=null) {
            books.refreshBooks(newbooks);    
            session.setAttribute("shopcar", books);
        }
        
        //Refresh model,Render view
        view.addObject("books",books.getbooks());
        view.setViewName("myshoppingcar");
        
        return view;
    }
}

 

  LoginInterceptor.java

package com.example.demo.controller.login;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


//Logon interceptor
public class LoginInterceptor implements HandlerInterceptor {
    
    @Override
    //stay Controller Call before method
    public boolean preHandle(HttpServletRequest req,HttpServletResponse res,Object handler) throws IOException {
        
        HttpSession session = req.getSession();
        
        if (session.getAttribute("login") != null) {
            System.out.println("login!");
            return true;
        }
        
        res.sendRedirect("login");
        return false;
    }
    
    @Override
    public void postHandle(HttpServletRequest req,HttpServletResponse res,Object handler,ModelAndView modelandview) throws Exception {
        //Controller The method is finished, but html Called when the page is not displayed
    }
    
    @Override
    public void afterCompletion(HttpServletRequest req,HttpServletResponse res,Object handler,Exception ex) {
        //Called after the page is rendered, usually to reclaim resources, similar to finally
    }
    
    
}

 

  SpringWebConfig.java

package com.example.demo.controller.login;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootConfiguration
public class SpringWebConfig  implements WebMvcConfigurer{
    
    //Increase interceptors to specific URL Set Interception to Check Logon
    public void addInterceptors(InterceptorRegistry registry) {
        
        //Loading an interceptor,You can use wildcards, or string arrays
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/mall","/quit");    
    }

}

Posted by jasonX on Sun, 31 Mar 2019 18:27:30 -0700