欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMvc的简单入门(四)之拦截器

程序员文章站 2022-07-09 18:03:42
...

一.过滤器与拦截器的区别

1.当浏览器访问Tomcat的时候过滤器会拦截资源,过滤器什么资源都拦截,过滤器在拦截器之前,是用来拦截servlet的

2.DispatcherServlet*处理器 在所有的action实现之前的拦截,拦截器拦截的是action,拦截器是类似过滤器的一种资源,是SpringMvc内置实现的,必须实现一个接口HandlerInterceptor

二.自定义拦截器

拦截器原理

SpringMvc的简单入门(四)之拦截器

在mvc-servlet.xml中配置拦截器

 <!-- 该拦截器用于拦截URL上参数  -->
  <mvc:interceptors>
  	
  	<!-- 自定义拦截器 -->
  	<mvc:interceptor>
  		<!-- 要拦截的资源 path=/*拦截所有-->
  		<mvc:mapping path="/tm"/>
  		<!-- 实现拦截器类的路径 -->
  		<bean class="springmvc.less05.controller.MyInterController"></bean>
  	</mvc:interceptor>
  </mvc:interceptors>
实现接口HandlerInterceptor

package springmvc.less05.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterController implements HandlerInterceptor {
	//在action执行完拦截
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
	//在action执行之后拦截
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}
	//在action执行之前就拦截
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//获取设置的UUID值
		String myToken= request.getParameter("token");
		//获取session
		Object myToken1= request.getSession().getAttribute("token");
		//true 让拦截器过 false则是拦下
		//判断是否是重复提交,如何参数有值就是重复提交,需要验证重复提交
		if(myToken!=null){
			//如果session==null就是重复提交返回false拦截
			if(myToken1==null){
				return false;
			}else{
				//如果设置的UUID和session相等就不拦截action,清掉session的值
				if(myToken.equals(myToken1)){
					request.getSession().removeAttribute("token");
					return true;
				}else{
					return false;
				}
			}
		}else{
			return true;
		}
	}

}

action

package springmvc.less05.controller;

import java.io.OutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import springmvc.less05.dao.MoneyDaoImpl;
@Controller
public class InterController {
	@RequestMapping(value="/inter",method=RequestMethod.GET)
	public String quert(OutputStream os)throws Exception{
		os.write("hello".getBytes());
		return null;
	}
	@Autowired
	MoneyDaoImpl mdi;
	@RequestMapping(value="/tm",method=RequestMethod.GET)
	public String quer(Integer money,OutputStream os)throws Exception{
		//根据前台传过来的金额进行扣钱
		mdi.updateMoney(money);
		//显示剩余的金钱
		os.write(("lostedmoney is:"+mdi.selectMoney()).getBytes());
		return null;
	}
}

业务逻辑层

package springmvc.less05.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MoneyDaoImpl {
	@Autowired
	JdbcTemplate jdbc;
	//修改金额
	public void updateMoney(int money){
		String sql="update mymoney set lostedmoney=lostedmoney-"+money+" where usid=1";
		jdbc.execute(sql);
	}
	//查询剩余金额
	public int selectMoney(){
		String sql="select lostedmoney from mymoney where usid=1";
		Integer lostedMoney=jdbc.queryForObject(sql,Integer.class);
		return lostedMoney;	
	}
	
}
前台页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib tagdir="/WEB-INF/tags" prefix="my"%><!-- 引入防重复提交标签 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'money.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <form action="${pageContext.request.contextPath}/tm">
   	扣钱:<input name ='money'>
   	<!-- 引入防重复提交标签 -->
   	<my:token></my:token>
   	<input type="submit" name="扣钱">
   </form>
  </body>
</html>

三.防重复提交

防重复提交原理

SpringMvc的简单入门(四)之拦截器

 在WEB-INF设置标签 设置隐藏表单域和给session设值

<%@ tag language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@attribute name="tokename" required="false" %>
<%
String ranStr=UUID.randomUUID().toString();
String key=(tokename==null?"token":tokename);
session.setAttribute(key,ranStr);
%>
<input type='hidden' name='<%=key %>' value='<%=ranStr %>'/>


相关标签: 拦截器 SpringMvc