1. 程式人生 > >七、Springmvc攔截器

七、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>