写一个springmvc拦截器,用于拦截所有/jftzc/*,拦截到的请求需从请求头中获取参数uid,当uid=12345时放行,否则返回401.
时间: 2024-05-04 07:15:13 浏览: 50
Spring MVC 拦截器
4星 · 用户满意度95%
实现类似下面的代码:
```java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String uid = request.getHeader("uid");
if (uid == null || !uid.equals("12345")) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
}
}
```
然后在Spring MVC配置文件中添加拦截器:
```xml
<mvc:interceptors>
<bean class="com.example.MyInterceptor" />
</mvc:interceptors>
```
这样,所有以`/jftzc/`开头的请求都会被拦截,并检查请求头中的`uid`参数是否为`12345`。如果不是,返回401错误;否则,放行请求。
阅读全文