interceptor登录的判断
Posted 池鱼i_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了interceptor登录的判断相关的知识,希望对你有一定的参考价值。
所需的jar包
Controller类
package cn.hp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class UserController {
@RequestMapping("/login")
public String login(String username , String password, HttpServletRequest request){
System.out.println("用户登录"+username+":"+password);
request.getSession().setAttribute("username",username);
return "success";
}
@RequestMapping("/selectAll")
public String selectAll(){
return "selectAll";
}
@RequestMapping("/add")
public String add(){
return "add";
}
}
interceptor类
package cn.hp.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String username = (String) request.getSession().getAttribute("username");
if(username!=null && !username.equals(" ")){
return true;
}else{
request.setAttribute("msg","用户未登录");
request.getRequestDispatcher("index.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 {
}
}
登录jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="login">
${msg}<br/>
账号: <input type="text" name="username"> <br/>
密码: <input type="password" name="password"> <br/>
<input type="submit" value="登录">
</form>
</body>
</html>
以上是关于interceptor登录的判断的主要内容,如果未能解决你的问题,请参考以下文章