servlet怎么使用拦截器

2025-05-12 23:06:26
推荐回答(2个)
回答1:

abstractInterceptor这个是xwork里面的包才有的类,就是你要在struts里面也是要用它。

import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class AuthorizationInterceptor extends AbstractInterceptor {
private static final String USER_KEY = "user";
public String intercept(ActionInvocation invocation) throws Exception {
Map session = invocation.getInvocationContext().getSession();
if(session.get(USER_KEY) == null) {
addActionError(invocation, "You must be authenticated to access this page");
return Action.ERROR;
}
return invocation.invoke();
}
private void addActionError(ActionInvocation invocation, String message) {
Object action = invocation.getAction();
if(action instanceof ValidationAware) {
((ValidationAware) action).addActionError(message);
}
}
}

回答2:

实现Servlet.Filter接口
public class AdminLoginFilter implements Filter
新建一个实现filter接口的类,实现dofilter方法,在dofilter方法里面写一个判读,比如如果用户名密码为空,则返回到登录页面
public class TestFilter implements Filter {
public void doFilter(ServletRequest srt, ServletResponse sre,
FilterChain filterChain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest)srt;
HttpServletResponse response = (HttpServletResponse)sre;

String name= (String)request.getSession().getAttribute("name");

if( name== null || name.trim().length() < 1) {

response.sendRedirect( "/denglu.jsp" );
}else {
filterChain.doFilter(request, response);
}
}
web.xml配置过滤器

TestFilter
/test/TestFilter


配置多个映射,哪些请求执行过滤器

TestFilter
/web-inf/test/*


TestFilter
/login.do


TestFilter
/loginin.do