写一个java拦截器,用于拦截所有/jftzc/*,拦截到的请求需从请求头中获取参数uid,当uid=12345时放行,否则返回401.
时间: 2024-05-09 11:20:11 浏览: 169
以下是一个简单的Java拦截器,用于拦截所有/jftzc/*的请求,并从请求头中获取参数uid,如果uid不等于12345,则返回401错误。
```java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String uid = request.getHeader("uid");
if (uid != null && uid.equals("12345")) {
return true;
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
}
```
在配置文件中添加以下代码,将拦截器应用到所有/jftzc/*请求上:
```xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/jftzc/**"/>
<bean class="com.example.AuthInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
```
阅读全文