输入账号密码点登录还是这个页面,没变化,网址变成http://localhost:8080/login
注释掉拦截器网页都可以用,也可以登录加上拦截器就登陆不了了
```java
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.User;
import javax.servlet.http.HttpSession;
@Controller
public class UserController {
@RequestMapping("/main1")
public String main(){
return "main";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/toOrderInfo")
public String toOrderInfo(){
return "orderinfo";
}
//登录
@RequestMapping("/login")
public String login(User user, Model model,HttpSession session){
//判断用户名和密码
String username = user.getUsername();
String password = user.getPassword();
if (username!=null&&"李硕".equals(username)&&password!=null&&"123456".equals(password)){
//登录成功
session.setAttribute("user",user);
return "redirect:main";
}else{
//登陆失败
model.addAttribute("msg","用户名或者密码错误");
return "login";
}
}
//退出成功,需要跳转到登陆页面
@RequestMapping("/logout")
public String logOut(HttpSession session){
session.invalidate();
return "login";
}
}
package interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
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 {
//针对登录和跳转到登录页面的进行放行
String requestURI=request.getRequestURI();
if (requestURI.indexOf("/login")>0||
requestURI.indexOf("/toLogin")>0){
//直接放行
return true;
}
//其他请求需要做登陆权限拦截判断
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if (user!=null){
//登录成功,放行
return true;
}
//没有登录,跳转到登录页面
request.setAttribute("msg","您还没有登录,请先登录");
//此处视图解析器不生效,原生Javweb技术;
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
.forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
```