Controller层:
package com.zx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Description: com.zx.controller
* @version: 1.0
*/
@Controller
@RequestMapping("/user")
public class UserController {
//跳转到登录页面
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
//直接跳转到main
@RequestMapping("/toMain")
public String toMain(){
return "main";
}
//登录验证
@RequestMapping("/login")
public String login(HttpSession session, String username, String password){
if ("admin".equals(username) && "root".equals(password)){
//用户名信息存入session中
session.setAttribute("username",username);
//验证通过,转发到主页面
return "main";
}
//验证不通过转发到登录页面
return "login";
}
//注销
@RequestMapping("/logout")
public String logout(HttpSession session){
//移除session中的username
// session.removeAttribute("username");
//session过期
session.invalidate();
//跳转到登录页面
return "login";
}
}
拦截器的实现:
拦截器配置:
<!--拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--拦截所有请求 /**-->
<!--配置的是Controller层的requestMapping-->
<mvc:mapping path="/user/*"/>
<!--不进行拦截-->
<mvc:exclude-mapping path="/user/toLogin"/>
<mvc:exclude-mapping path="/user/login"/>
<!--拦截器的路径-->
<bean id="userInterceptor" class="com.zx.interceptor.UserInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>