SpringMVC-登录验证判断
1.拦截器
package com.kuang.config;
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 {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session=request.getSession();
//登录页面要放行
if (request.getRequestURI().contains("goLogin")){
return true;
}
//提交登录
if (request.getRequestURI().contains("login")){
return true;
}
//什么情况下登录了
if (session.getAttribute("LoginInfo")!=null){
return true;
}
//判断什么情况下没有登录
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
}
2.拦截器文件配置
<!--拦截器配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--拦截该目录下的所有请求-->
<mvc:mapping path="/**"/>
<bean class="com.kuang.config.MyInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<bean class="com.kuang.config.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
3.controller
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class LoginController {
//登录
@RequestMapping("/login")
public String login(HttpSession session, String username, String password, Model model){
//将用户信息存放在session中
session.setAttribute("LoginInfo",username);
model.addAttribute("username",username);
return "main";
}
@RequestMapping("/main")
public String main(){
return "main";
}
@RequestMapping("/goLogin")
public String goLogin(){
return "login";
}
//注销
@RequestMapping("/goOut")
public String goOut(HttpSession session){
session.removeAttribute("LoginInfo");
return "main";
}
}
4.效果
当用户没有登录时,就进行拦截跳转到登录页面。
好了,今天的分享就到这里了。