拦截器:拦截的是请求
拦截器是基于java的反射机制
preHandle:访问请求就开始,在执行业务之前
postHandle:在执行业务之后,解析视图之前,?跳转之前
afterCompletion:在请求完成之后,执行业务逻辑之后,
视图渲染之后
<mvc: mapping path=”拦截路径“>
<mvc:exclude-maooing path="不拦截的路径 ">
当有多个拦截器的时候,
根据代码的前后顺序执行,preHandle,1,2
然后反序执行postHandle2 1 afterCompletion2 1
用户名为空的拦截器:
Springmvc.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!--<mvc:exclude-mapping path="/api/user/login"/>-->
<bean class="org.wby.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
切记在action这里需要用绝对路径${pageContext.request.contextPath},要不拿不到路径。
login.jsp
<div align="center">
<form method="post" action="${pageContext.request.contextPath}/api/user/login" >
<table>
<caption>用户登录</caption>
<tr>
<th>账号:</th>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<th>密码:</th>
<td>
<input type="password" name="pwd" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="提交"></td>
</tr>
</table>
</form>
</div>
package org.wby.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object o) throws Exception {
System.out.println("请求执行前,执行的内容");
String user =request.getParameter("name");
System.out.println(user);
//用户已存在,则放行,否则拦截
if (user.equals("")||user==null) {
//放行,执行处理器
request.getRequestDispatcher("/index.jsp").forward(request, resp);
return false;
} else {
//放行,执行处理器
return true;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("解析视图之前,执行的内容");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("请求跟视图渲染执行完毕后执行的内容");
}
}
package org.wby.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/api/user")
public class Actioncontroller {
@RequestMapping("/login")
public String login(String name, String pwd,HttpServletRequest req) {
req.getSession().setAttribute("name",name);
req.getSession().setAttribute("pwd",pwd);
return "success";
}
}
以上就是代码实现了