[Spring MVC]教程――使用拦截器实现权限控制(二)

2014-11-24 00:35:20 · 作者: · 浏览: 1
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.cat.interceptor.MemberInterceptor; /** * @author chenlf * * 2014-3-24 */ @Controller public class LoginController { @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login(String redirectURL, HttpServletRequest request) { ModelAndView view = new ModelAndView(); //把拦截前路径存下来,以便登入成功可以直接请求到登录前的页面 view.addObject("redirectURL", redirectURL); view.setViewName("/login"); return view; } @RequestMapping(value = "/submit", method = RequestMethod.POST) public String submit(String username, String password, String redirectURL, HttpServletRequest request) { //模拟登陆成功 用户admin 密码admin的用户 if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) && username.equals("admin") && password.equals("admin")) { //当登陆成功是,将用户信息存放到session中去 HttpSession session = request.getSession(); session.setAttribute(MemberInterceptor.SEESION_MEMBER, "admin"); if (StringUtils.isNotBlank(redirectURL)) { return "redirect:" + URLDecoder.decode(redirectURL); } return "redirect:/member/index.htm"; } else { if (StringUtils.isNotBlank(redirectURL)) { return "redirect:/login.htm " + URLDecoder.decode(redirectURL); } return "redirect:/login.htm"; } } }

6、下面就是login.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="utf-8"%>

mvc权限登陆login

账号 密码

7、剩下的就是一些正常的mvc请求处理的文件,这里就不赘诉了

8、到这里看看效果吧

a、当非登陆状态的时候,请求localhost:8010/demo-mvc/member/list.htm时,被拦截拦截,重定向到login页面,并携带了当前的这个路径(/member/list.htm)作为参数传到页面 \
b、输入正确的用户名admin 密码admin后登陆,会跳转到拦截前的页面 \
c、当登陆完成后,输入地址为http://localhost:8010/demo-mvc/member/index.htm,session中记录着当前用户的信息,不需要重新登陆了 \

9、因为篇幅问题,一些不重要的文件没有一一贴出来,有需要的可以到http://download.csdn.net/detail/a124753561/7098925下载源代码。