1、新建一个 拦截器
3.登陆和注销controller方法
package cn.com.foha.lamppostmanagement.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 SecurityInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
System.out.println("SecurityInterceptor...preHandle...");
//获取请求的url
String url=request.getRequestURI();
//判断url是否是公开地址(实际使用时将公开地址配置到配置文件中)
if(url.indexOf("loginCheck")>=0){
//如果要进行登录提交,放行
return true;
}
//这里可以根据session的用户来判断角色的权限
if(request.getSession().getAttribute("userId") != null) {
//方形
return true;
}
//判断是否有 userId 这个session,如果没有(或者过期了)转发到登录页面
request.getRequestDispatcher("/").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2.配置 springmvc.xml
<!--拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/"/>
<mvc:exclude-mapping path="/static/**" />
<ref bean="userSecurityInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<bean id="userSecurityInterceptor" class="cn.com.foha.lamppostmanagement.Interceptor.SecurityInterceptor"></bean>
<!--<mvc:default-servlet-handler />
3.登陆和注销controller方法
@RequestMapping("/loginCheck")
@ResponseBody
public Object loginCheck(User user, HttpSession session)throws Exception
{
User user1=userService.login(user);
if(user1!=null)
{
session.setAttribute("userId",user1.getRoleid());
session.setAttribute("userName", user.getUsername());
return "true";
}
else
{
System.out.println("用户名或密码错误");
return "false";
}
}
//退出登录
@RequestMapping(value = "/logout")
public String logout(HttpSession session) throws Exception {
session.removeAttribute("userId");
session.removeAttribute("userName");
session.invalidate();
return "redirect:/lamppostmanagement";
}
代码需要根据自己情况修改
执行效果