0, persion entity class

package com.jf3q.study.bean;

import lombok.Data;
import lombok.ToString;
import org.springframework.stereotype.Component;


@Component
@ToString
@Data
public class Persion {
    private  int id ;
    private  String username;
    private  String password;

}
Copy the code

1. Landing page:

2, the control layer

package com.jf3q.study.control; import com.jf3q.study.bean.Persion; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import javax.servlet.http.HttpSession; @Controller public class LoginControl { @PostMapping("/login") public String login(Persion persion, Model model, HttpSession session){ System.out.println(persion.getPassword()); if(! Persion. GetPassword ().equals("123456")){model.addattribute ("mess"," password error "); Return "login"; }else { session.setAttribute("loginUser",persion); Return "redirect:/main.html"; return "redirect:/main.html"; } } @GetMapping("/main.html") public String main(){ return "main"; }}Copy the code

3. Interceptor

package com.jf3q.study.control.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session=request.getSession(); Object loginUser = session.getAttribute("loginUser"); If (loginUser ==null){// intercept request.setAttribute("mess"," please login first "); request.getRequestDispatcher("/").forward(request,response); Return false; } return true; }}Copy the code

4. Register interceptors

package com.jf3q.study.config; import com.jf3q.study.control.interceptor.LoginInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") / / all requests are intercepted, including static resources. ExcludePathPatterns ("/", "/ login", "/ img / * *", "/ js / * *", "/ CSS / * *"); // Set the path not to intercept}}Copy the code

5. Successful login page

Effect:

What do not understand can Q ME 1913284695