×

struts2拦截器的作用

struts2拦截器的作用(struts2拦截器和过滤器的区别)

admin admin 发表于2023-12-29 11:36:49 浏览31 评论0

抢沙发发表评论

各位老铁们,大家好,今天由我来为大家分享struts2拦截器的作用,以及struts2拦截器和过滤器的区别的相关问题知识,希望对大家有所帮助。如果可以帮助到大家,还望关注收藏下本站,您的支持是我们最大的动力,谢谢大家了哈,下面我们开始吧!

本文目录

struts2拦截器和过滤器的区别

拦截器和过滤器的区别:

1、拦截器是基于java的反射机制的,而过滤器是基于函数回调

2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器

3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用

4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能

5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次

拦截器 :是在面向切面编程的就是在你的service或者一个方法前调用一个方法,或者在方法后调用一个方法比如动态代理就是拦截器的简单实现,在你调用方法前打印出字符串(或者做其它业务逻辑的操作),也可以在你调用方法后打印出字符串,甚至在你抛出异常的时候做业务逻辑的操作。

下面通过实例来看一下过滤器和拦截器的区别:

使用拦截器进行/admin 目录下jsp页面的过滤

 view plain copy

  • 《package name="newsDemo" extends="struts-default"   

  • namespace="/admin"》   

  • 《interceptors》   

  • 《interceptor name="auth" class="com.test.news.util.AccessInterceptor" /》   

  • 《interceptor-stack name="authStack"》   

  • 《interceptor-ref name="auth" /》   

  • 《/interceptor-stack》   

  • 《/interceptors》   

  • 《!-- action --》   

  • 《action name="newsAdminView!*" class="newsAction"   

  • method="{1}"》   

  • 《interceptor-ref name="defaultStack"/》   

  • 《interceptor-ref name="authStack"》   

  • 《/interceptor-ref》   

  • 下面是我实现的Interceptor class: 

     view plain copy

  • package com.test.news.util;   

  • import java.util.Map;   

  • import com.opensymphony.xwork2.ActionContext;   

  • import com.opensymphony.xwork2.ActionInvocation;   

  • import com.opensymphony.xwork2.interceptor.AbstractInterceptor;   

  • import com.test.news.action.AdminLoginAction;   

  • /**  

  • * @author chaoyin  

  • */   

  • public class AccessInterceptor extends AbstractInterceptor {   

  • private static final long serialVersionUID = -4291195782860785705L;   

  • @Override   

  • public String intercept(ActionInvocation actionInvocation) throws Exception {   

  • ActionContext actionContext = actionInvocation.getInvocationContext();   

  • Map session = actionContext.getSession();   

  • //except login action   

  • Object action = actionInvocation.getAction();   

  • if (action instanceof AdminLoginAction) {   

  • return actionInvocation.invoke();   

  • }   

  • //check session   

  • if(session.get("user")==null ){   

  • return "logout";   

  • }   

  • return actionInvocation.invoke();//go on   

  • }   

  • }   

  • 过滤器:是在javaweb中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法url(不是login.do的地址请求,如果用户没有登陆都过滤掉),或者在传入servlet或者 struts的action前统一设置字符集,或者去除掉一些非法字符.

    使用过滤器进行/admin 目录下jsp页面的过滤,首先在web.xml进行过滤器配置: 

     view plain copy

  • 《filter》   

  • 《filter-name》access filter《/filter-name》   

  • 《filter-class》   

  • com.test.news.util.AccessFilter   

  • 《/filter-class》   

  • 《/filter》   

  • 《filter-mapping》   

  • 《filter-name》access filter《/filter-name》   

  • 《url-pattern》/admin/*《/url-pattern》   

  • 《/filter-mapping》   

  • 下面是过滤的实现类: 

     view plain copy

  • package com.test.news.util;   

  • import java.io.IOException;   

  • import javax.servlet.Filter;   

  • import javax.servlet.FilterChain;   

  • import javax.servlet.FilterConfig;   

  • import javax.servlet.ServletException;   

  • import javax.servlet.ServletRequest;   

  • import javax.servlet.ServletResponse;   

  • ***隐藏网址***

  • ***隐藏网址***

  • ***隐藏网址***

  • public class AccessFilter implements Filter {   

  • /**  

  • * @author chaoyin  

  • */   

  • public void destroy() {   

  • }   

  • public void doFilter(ServletRequest arg0, ServletResponse arg1,   

  • FilterChain filterChain) throws IOException, ServletException {   

  • HttpServletRequest request = (HttpServletRequest)arg0;   

  • HttpServletResponse response = (HttpServletResponse)arg1;   

  • HttpSession session = request.getSession();   

  • if(session.getAttribute("user")== null && request.getRequestURI().indexOf("login.jsp")==-1 ){   

  • response.sendRedirect("login.jsp");   

  • return ;   

  • }   

  • filterChain.doFilter(arg0, arg1);   

  • }   

  • public void init(FilterConfig arg0) throws ServletException {   

  • }   

  • }     

struts2 alias拦截器有什么用

***隐藏网址*** 以下以实现在action链中username参数共享name参数为例: Xml代码 《package name="test_Alias" extends="struts-default" namespace="/alias"》 《action name="name" class="com.warning.interceptor.action.AliasAction1" method="_name"》 《result name="success" type="chain"》username《/result》 《/action》 《action name="username" class="com.warning.interceptor.action.AliasAction2" method="_username"》 《param name="aliases"》#{’name’:’username’}《/param》 《result name="success"》/jsp/alias/index.jsp《/result》 《/action》 《/package》 名称为username的action中有param标签,其中name属性值应该和alias拦截器参数aliasesKey的值一样,而param标签的值是一个定义map对象的OGNL表达式。 com.opensymphony.xwork2.interceptor.AliasInterceptor的intercept方法代码如下Java代码 public String intercept(ActionInvocation invocation) throws Exception { ActionConfig config = invocation.getProxy().getConfig(); ActionContext ac = invocation.getInvocationContext(); Object action = invocation.getAction(); // get the action’s parameters //获取action配置中的参数(就是param标签) final Map《String, String》 parameters = config.getParams(); //查看参数列表中是否有aliasesKey对应的参数,如果没有,直接执行action if (parameters.containsKey(aliasesKey)) { //获取出aliasesKey值参数对象的值。 String aliasExpression = parameters.get(aliasesKey); ValueStack stack = ac.getValueStack(); //利用OGNL表达式,获取参数值对应的对象 Object obj = stack.findValue(aliasExpression); //如果获取到的对象为空,或者不是Map对象,将直接执行action if (obj != null && obj instanceof Map) { //get secure stack //构建新的值栈 ValueStack newStack = valueStackFactory.createValueStack(stack); boolean clearableStack = newStack instanceof ClearableValueStack; if (clearableStack) { //if the stack’s context can be cleared, do that to prevent OGNL //from having access to objects in the stack, see XW-641 ((ClearableValueStack)newStack).clearContextValues(); Map《String, Object》 context = newStack.getContext(); ReflectionContextState.setCreatingNullObjects(context, true); ReflectionContextState.setDenyMethodExecution(context, true); ReflectionContextState.setReportingConversionErrors(context, true); //keep locale from original context context.put(ActionContext.LOCALE, stack.getContext().get(ActionContext.LOCALE)); } // override Map aliases = (Map) obj; //遍历Map中的数据 for (Object o : aliases.entrySet()) { Map.Entry entry = (Map.Entry) o; String name = entry.getKey().toString(); String alias = (String) entry.getValue(); //从值栈中获取name(原参数名)对应的值 Object value = stack.findValue(name); if (null == value) { // workaround Map《String, Object》 contextParameters = ActionContext.getContext().getParameters(); //如果获取到的值为null,则从request中获取参数值 if (null != contextParameters) { value = contextParameters.get(name); } } if (null != value) { try { //将值栈中alias对应的值设置为value newStack.setValue(alias, value); } catch (RuntimeException e) { if (devMode) { String developerNotification = LocalizedTextUtil.findText(ParametersInterceptor.class, "devmode.notification", ActionContext.getContext().getLocale(), "Developer Notification:\n{0}", new Object{ "Unexpected Exception caught setting ’" + entry.getKey() + "’ on ’" + action.getClass() + ": " + e.getMessage() }); LOG.error(developerNotification); if (action instanceof ValidationAware) { ((ValidationAware) action).addActionMessage(developerNotification); } } } } } if (clearableStack && (stack.getContext() != null) && (newStack.getContext() != null)) stack.getContext().put(ActionContext.CONVERSION_ERRORS, newStack.getContext().get(ActionContext.CONVERSION_ERRORS)); } else { LOG.debug("invalid alias expression:" + aliasesKey); } } return invocation.invoke(); } 该拦截器已经被包含于默认拦截器栈中,无需再指定。

struts2拦截器的作用是什么

拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。 拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。拦截器栈(Interceptor Stack)类似于过滤器链。拦截器栈就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器栈的拦截器就会按其之前定义的顺序被调用。也可以叫做拦截器链(Interceptor Stack),拦截器栈一词更明确的表名了连接器链的实现方式。Struts2的拦截器和Filter类似。在执行Action的execute方法之前,Struts2会首先执行在struts.xml中引用的拦截器,在执行完所有引用的拦截器的intercept方法后,会执行Action的execute方法。 当请求到达Struts 2的ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表(list),最后一个一个地调用列表中的拦截器

关于struts2拦截器的作用到此分享完毕,希望能帮助到您。