七、Springmvc拦截器

springmvc.xml

	<!-- Springmvc的拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**"/>
			<!-- 自定义的拦截器类 -->
			<bean class="com.itheima.springmvc.interceptor.Interceptor1"/>
		</mvc:interceptor>
		
		<!-- <mvc:interceptor>
			<mvc:mapping path="/**"/>
			自定义的拦截器类
			<bean class="com.itheima.springmvc.interceptor.Interceptor2"/>
		</mvc:interceptor> -->
	</mvc:interceptors>

Interceptor1

package com.itheima.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class Interceptor1 implements HandlerInterceptor{
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("方法前1");
		//判断用户是否登录 如果没登录,重定向到登录页面,不放行  如果登陆了,就放行
		//URL http://localhost:8080/springmvc-mybatis/login.jsp
		//URI /login.jsp
		
		String requestURI = request.getRequestURI();
		if(!requestURI.contains("/login")){
			String username = (String) request.getSession().getAttribute("USER_SESSION");
			if(null == username){
				response.sendRedirect(request.getContextPath()+"/login.action");
				return false;
			}
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		System.out.println("方法后1");
		
	}
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("页面渲染后1");
		
	}
}

ItemController

@Controller
public class ItemController {

	@Autowired
	private ItemService itemService;
	
	
	//去登录的页面
	@RequestMapping(value = "/login.action",method=RequestMethod.GET)
	public String login(){
		
		return "login";
	}
	
	@RequestMapping(value="/login.action",method=RequestMethod.POST)
	public String login(String username,HttpSession session){
		session.setAttribute("USER_SESSION", username);
		return "redirect:item/itemList.action";
	}
}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/login.action" method="post">
		用户名:<input type="text" name="username" value="dfaadfd">
		<input type="submit" value="提交">
	</form>
</body>
</html>

  

  

  

 

猜你喜欢

转载自www.cnblogs.com/syj1993/p/9917050.html