UsersController
package com.example.controller;
import com.example.entity.Users;
import com.example.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
public class UsersController {
@Autowired
private UsersService usersService;
@RequestMapping("/login")
public String login(String username, String password, Model model, HttpSession session){
Users login = usersService.login(username, password);
if(login!=null){
session.setAttribute("verification",login);
model.addAttribute("msg",username);
return "main";
}else{
return "index";
}
}
}
LoginHandInterceptor
package com.example.loginHandInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandInterceptor implements HandlerInterceptor {
//用户拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("verification");
if(user!=null){
return true;
}else {
request.setAttribute("msg","你还没有登录,请先登录!");
request.getRequestDispatcher("/login").forward(request,response);
// response.sendRedirect("/index.html");
return false;
}
}
}
configAdapter
package com.example.config;
import com.example.loginHandInterceptor.LoginHandInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class configAdapter implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//这里注意 我这里没有static里面没有什么 要是项目中里面有记得把这个也加进去,不然也会拦截 类如 "/css/**"加到excludePathPatterns里面即可
registry.addInterceptor(new LoginHandInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html", "/login");
}
}