`
liangjian103
  • 浏览: 177572 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

struts2与WebService整合

阅读更多

     最近一项目,遇到一个变态客户,要用WebService作验证,来进行单点登陆,本来单点登陆也没有这么搞的,没办法,客户是蛮不讲理的那种,下面我们来小试牛刀一下。

     一、创建WebService服务端的代码我就不说了,网上有不少用AXIS编写的代码,不过抄袭者众多,而且很多代码是很难与实际项目整合的,实际布署起来更是不可行,比如布署到IBM AIX系统上。

    二、创建好服务端后,我们需要对Struts2的过滤器进行简单的改写,以便让客户端程序能正常访问WebService服务端。

    三、在你的项目中创建一个包:org.apache.struts2.dispatcher,注意,这个包必须和Struts2中的过滤器包一样,并创建一个类,FilterDispatcher,接下来我们在doFilter中加入如下代码:

    if("/WebServiceTest2/services/HelloWordWeb".endsWith(request.getRequestURI())||"/servlet/".endsWith(request.getRequestURI()))
        {
         
              chain.doFilter(req,res);
        }

         这段代码是把webService中的服务器地址和AXIS中配置的servlet让过滤器放行。这样,我们的服务端就不会被拦截了。

    四、整段代码如下:

         /*
 * $Id: FilterDispatcher.java 674498 2008-07-07 14:10:42Z mrdon $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.struts2.dispatcher;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.RequestUtils;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.ng.filter.FilterHostConfig;
import org.apache.struts2.util.ClassLoaderUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import com.opensymphony.xwork2.util.profiling.UtilTimerStack;

/**
 * Master filter for Struts that handles four distinct
 * responsibilities:
 * <p/>
 * <ul>
 * <p/>
 * <li>Executing actions</li>
 * <p/>
 * <li>Cleaning up the {@link ActionContext} (see note)</li>
 * <p/>
 * <li>Serving static content</li>
 * <p/>
 * <li>Kicking off XWork's interceptor chain for the request lifecycle</li>
 * <p/>
 * </ul>
 * <p/>
 * <p/> <b>IMPORTANT</b>: this filter must be mapped to all requests. Unless you know exactly what you are doing, always
 * map to this URL pattern: /*
 * <p/>
 * <p/> <b>Executing actions</b>
 * <p/>
 * <p/> This filter executes actions by consulting the {@link ActionMapper} and determining if the requested URL should
 * invoke an action. If the mapper indicates it should, <b>the rest of the filter chain is stopped</b> and the action is
 * invoked. This is important, as it means that filters like the SiteMesh filter must be placed <b>before</b> this
 * filter or they will not be able to decorate the output of actions.
 * <p/>
 * <p/> <b>Cleaning up the {@link ActionContext}</b>
 * <p/>
 * <p/> This filter will also automatically clean up the {@link ActionContext} for you, ensuring that no memory leaks
 * take place. However, this can sometimes cause problems integrating with other products like SiteMesh. See {@link
 * ActionContextCleanUp} for more information on how to deal with this.
 * <p/>
 * <p/> <b>Serving static content</b>
 * <p/>
 * <p/> This filter also serves common static content needed when using various parts of Struts, such as JavaScript
 * files, CSS files, etc. It works by looking for requests to /struts/*, and then mapping the value after "/struts/"
 * to common packages in Struts and, optionally, in your class path. By default, the following packages are
 * automatically searched:
 * <p/>
 * <ul>
 * <p/>
 * <li>org.apache.struts2.static</li>
 * <p/>
 * <li>template</li>
 * <p/>
 * </ul>
 * <p/>
 * <p/> This means that you can simply request /struts/xhtml/styles.css and the XHTML UI theme's default stylesheet
 * will be returned. Likewise, many of the AJAX UI components require various JavaScript files, which are found in the
 * org.apache.struts2.static package. If you wish to add additional packages to be searched, you can add a comma
 * separated (space, tab and new line will do as well) list in the filter init parameter named "packages". <b>Be
 * careful</b>, however, to expose any packages that may have sensitive information, such as properties file with
 * database access credentials.
 * <p/>
 * <p/>
 * <p/>
 * <p>
 * <p/>
 * This filter supports the following init-params:
 * <!-- START SNIPPET: params -->
 * <p/>
 * <ul>
 * <p/>
 * <li><b>config</b> - a comma-delimited list of XML configuration files to load.</li>
 * <p/>
 * <li><b>actionPackages</b> - a comma-delimited list of Java packages to scan for Actions.</li>
 * <p/>
 * <li><b>configProviders</b> - a comma-delimited list of Java classes that implement the
 * {@link ConfigurationProvider} interface that should be used for building the {@link Configuration}.</li>
 * <p/>
 * <li><b>loggerFactory</b> - The class name of the {@link LoggerFactory} implementation.</li>
 * <p/>
 * <li><b>*</b> - any other parameters are treated as framework constants.</li>
 * <p/>
 * </ul>
 * <p/>
 * <!-- END SNIPPET: params -->
 * <p/>
 * </p>
 * <p/>
 * To use a custom {@link Dispatcher}, the <code>createDispatcher()</code> method could be overriden by
 * the subclass.
 *
 * @version $Date: 2008-07-07 22:10:42 +0800 (星期一, 07 七月 2008) $ $Id: FilterDispatcher.java 674498 2008-07-07 14:10:42Z mrdon $
 * @deprecated Since Struts 2.1.3, use {@link org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter} instead or
 * {@link org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter} and {@link org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter}
 * if needing using the {@link ActionContextCleanUp} filter in addition to this one
 *
 * @see ActionMapper
 * @see ActionContextCleanUp
 * @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
 * @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter
 * @see org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter
 */
public class FilterDispatcher implements StrutsStatics, Filter {

    /**
     * Provide a logging instance.
     */
    private Logger log;

    /**
     * Provide ActionMapper instance, set by injection.
     */
    private ActionMapper actionMapper;

    /**
     * Provide FilterConfig instance, set on init.
     */
    private FilterConfig filterConfig;

    /**
     * Expose Dispatcher instance to subclass.
     */
    protected Dispatcher dispatcher;

    /**
     * Loads stattic resources, set by injection
     */
    protected StaticContentLoader staticResourceLoader;

    /**
     * Initializes the filter by creating a default dispatcher
     * and setting the default packages for static resources.
     *
     * @param filterConfig The filter configuration
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            this.filterConfig = filterConfig;

            initLogging();

            dispatcher = createDispatcher(filterConfig);
            dispatcher.init();
            dispatcher.getContainer().inject(this);

            staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));
        } finally {
            ActionContext.setContext(null);
        }
    }

    private void initLogging() {
        String factoryName = filterConfig.getInitParameter("loggerFactory");
        if (factoryName != null) {
            try {
                Class cls = ClassLoaderUtils.loadClass(factoryName, this.getClass());
                LoggerFactory fac = (LoggerFactory) cls.newInstance();
                LoggerFactory.setLoggerFactory(fac);
            } catch (InstantiationException e) {
                System.err.println("Unable to instantiate logger factory: " + factoryName + ", using default");
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                System.err.println("Unable to access logger factory: " + factoryName + ", using default");
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                System.err.println("Unable to locate logger factory class: " + factoryName + ", using default");
                e.printStackTrace();
            }
        }

        log = LoggerFactory.getLogger(FilterDispatcher.class);

    }

    /**
     * Calls dispatcher.cleanup,
     * which in turn releases local threads and destroys any DispatchListeners.
     *
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
        if (dispatcher == null) {
            log.warn("something is seriously wrong, Dispatcher is not initialized (null) ");
        } else {
            try {
                dispatcher.cleanup();
            } finally {
                ActionContext.setContext(null);
            }
        }
    }

    /**
     * Create a default {@link Dispatcher} that subclasses can override
     * with a custom Dispatcher, if needed.
     *
     * @param filterConfig Our FilterConfig
     * @return Initialized Dispatcher
     */
    protected Dispatcher createDispatcher(FilterConfig filterConfig) {
        Map<String, String> params = new HashMap<String, String>();
        for (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            String value = filterConfig.getInitParameter(name);
            params.put(name, value);
        }
        return new Dispatcher(filterConfig.getServletContext(), params);
    }

    /**
     * Modify state of StrutsConstants.STRUTS_STATIC_CONTENT_LOADER setting.
     * @param staticResourceLoader val New setting
     */
    @Inject
    public void setStaticResourceLoader(StaticContentLoader staticResourceLoader) {
        this.staticResourceLoader = staticResourceLoader;
    }

    /**
     * Modify ActionMapper instance.
     * @param mapper New instance
     */
    @Inject
    public void setActionMapper(ActionMapper mapper) {
        actionMapper = mapper;
    }

    /**
     * Provide a workaround for some versions of WebLogic.
     * <p/>
     * Servlet 2.3 specifies that the servlet context can be retrieved from the session. Unfortunately, some versions of
     * WebLogic can only retrieve the servlet context from the filter config. Hence, this method enables subclasses to
     * retrieve the servlet context from other sources.
     *
     * @return the servlet context.
     */
    protected ServletContext getServletContext() {
        return filterConfig.getServletContext();
    }

    /**
     * Expose the FilterConfig instance.
     *
     * @return Our FilterConfit instance
     */
    protected FilterConfig getFilterConfig() {
        return filterConfig;
    }

    /**
     * Wrap and return the given request, if needed, so as to to transparently
     * handle multipart data as a wrapped class around the given request.
     *
     * @param request  Our ServletRequest object
     * @param response Our ServerResponse object
     * @return Wrapped HttpServletRequest object
     * @throws ServletException on any error
     */
    protected HttpServletRequest prepareDispatcherAndWrapRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        Dispatcher du = Dispatcher.getInstance();

        // Prepare and wrap the request if the cleanup filter hasn't already, cleanup filter should be
        // configured first before struts2 dispatcher filter, hence when its cleanup filter's turn,
        // static instance of Dispatcher should be null.
        if (du == null) {

            Dispatcher.setInstance(dispatcher);

            // prepare the request no matter what - this ensures that the proper character encoding
            // is used before invoking the mapper (see WW-9127)
            dispatcher.prepare(request, response);
        } else {
            dispatcher = du;
        }

        try {
            // Wrap request first, just in case it is multipart/form-data
            // parameters might not be accessible through before encoding (ww-1278)
            request = dispatcher.wrapRequest(request, getServletContext());
        } catch (IOException e) {
            String message = "Could not wrap servlet request with MultipartRequestWrapper!";
            log.error(message, e);
            throw new ServletException(message, e);
        }

        return request;
    }

    /**
     * Process an action or handle a request a static resource.
     * <p/>
     * The filter tries to match the request to an action mapping.
     * If mapping is found, the action processes is delegated to the dispatcher's serviceAction method.
     * If action processing fails, doFilter will try to create an error page via the dispatcher.
     * <p/>
     * Otherwise, if the request is for a static resource,
     * the resource is copied directly to the response, with the appropriate caching headers set.
     * <p/>
     * If the request does not match an action mapping, or a static resource page,
     * then it passes through.
     *
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        if("/WebServiceTest2/services/HelloWordWeb".endsWith(request.getRequestURI())||"/servlet/".endsWith(request.getRequestURI()))
        {
         
         chain.doFilter(req,res);
        }
        else
        {
            HttpServletResponse response = (HttpServletResponse) res;
               ServletContext servletContext = getServletContext();
                
               String timerKey = "FilterDispatcher_doFilter: ";
               try {

                   // FIXME: this should be refactored better to not duplicate work with the action invocation
                   ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
                   ActionContext ctx = new ActionContext(stack.getContext());
                   ActionContext.setContext(ctx);

                   UtilTimerStack.push(timerKey);
                   request = prepareDispatcherAndWrapRequest(request, response);
                   ActionMapping mapping;
                   try {
                       mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());
                   } catch (Exception ex) {
                       log.error("error getting ActionMapping", ex);
                       dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
                       return;
                   }

                   if (mapping == null) {
                       // there is no action in this request, should we look for a static resource?
                       String resourcePath = RequestUtils.getServletPath(request);

                       if ("".equals(resourcePath) && null != request.getPathInfo()) {
                           resourcePath = request.getPathInfo();
                       }

                       if (staticResourceLoader.canHandle(resourcePath)) {
                           staticResourceLoader.findStaticResource(resourcePath, request, response);
                       } else {
                           // this is a normal request, let it pass through
                           chain.doFilter(request, response);
                       }
                       // The framework did its job here
                       return;
                   }

                   dispatcher.serviceAction(request, response, servletContext, mapping);

               } finally {
                   try {
                       ActionContextCleanUp.cleanUp(req);
                   } finally {
                       UtilTimerStack.pop(timerKey);
                   }
               }
        }
     
    }
}

分享到:
评论

相关推荐

    spring+hibernate+struts2+webservice示例

    这是个采用apache cxf实现webservice的示例,主要由spring整合hibernate、struts2实现webservice,里面struts2用到得较少……对于学习很有帮助,另外我觉得若是初学者,不过采用那方式,现在按照套方案做熟练后再去...

    struts2的整合

    Struts2是一个强大的MVC(Model-View-...通过Struts2与Hibernate的整合,开发者能够利用两者的优点,构建出高效、健壮的Java Web应用。这种整合方式在实际项目中非常常见,对于提升开发效率和应用质量具有显著效果。

    精通soa基于服务总线的struts+ejb+webservice整合应用开发

    精通soa基于服务总线的struts+ejb+webservice整合应用开发 作者:梁爱虎 书中光盘内容:org.eclipse.jdt.ui_3.1.2.jar weblogic91.server axis

    struts2+spring连接webservice jar包

    在整合Struts2、Spring和Webservice时,通常会采取以下步骤: 1. 在Spring配置文件中,定义Webservice的客户端bean,包括URL、端口等信息,以及调用方法的映射。 2. 使用Spring的JAX-WS或JAX-RS支持,生成...

    Webservice+spring+struts小例子,简单方法调用

    【标题】:“Webservice+Spring+Struts小例子,简单方法调用”是一个典型的Java Web应用程序开发示例,它展示了如何将三种核心技术整合在一起,实现服务接口调用。在这个项目中,Web服务(Webservice)作为数据交互...

    strust2.0必须的几个jar整合

    1. **struts2-core.jar**:这是Struts2框架的核心库,包含了Struts2框架的基本组件,如Action、Interceptor、Result等。这个JAR文件提供了Struts2的基础架构,使得开发者能够定义和执行Action,实现请求的处理和视图...

    SSH2注解,Lucene全文检索,WebService整合例子。

    在IT行业中,SSH2、Lucene全文检索以及WebService是三个重要的技术领域,它们在构建高效、可扩展的应用程序中发挥着关键作用。SSH2是指Struts2、Spring和Hibernate的集成,提供了MVC(模型-视图-控制器)架构、依赖...

    零配置spring 整合cxf、struts2

    本文将深入探讨如何在不进行繁琐配置的情况下,实现Spring与CXF和Struts2的整合。 首先,让我们关注"零配置"的概念。在传统的Java开发中,大量的XML配置文件使得项目变得复杂且难以维护。Spring Boot的出现,倡导了...

    jbpm应用实例(Struts2+Spring2+iBatis2.3+WebService)

    【jbpm应用实例(Struts2+Spring2+iBatis2.3+WebService)】是一个典型的Java企业级应用集成示例,它展示了如何在项目中整合多种技术来实现业务流程管理(Business Process Management, BPM)。jbpm是一个开源的工作...

    使用axis2与ssh整合开发webService文档与源码

    当我们谈论“使用Axis2与SSH整合开发WebService”时,我们实际上是在讨论如何将Apache Axis2,一个强大的Java Web服务框架,与Spring(S)、Hibernate(H)和Struts(S)这三大流行开源框架相结合,来构建高效、可...

    SSH整合cxf webservice实例

    3. **Struts2整合** Struts2作为MVC框架,主要负责视图和控制器之间的交互。整合CXF时,我们可以在Struts2的Action中调用之前定义的CXF服务。首先,确保Struts2的配置文件中引入了CXF插件,然后在Action中通过...

    Axis2(WebService)经典教程

    - **企业级集成**:利用WebService技术,Axis2可以整合多种技术栈和平台,提高系统的可扩展性和可维护性。 #### 三、Axis2核心功能详解 ##### 1. POJO实现0配置的WebService - **概念**:通过简单的Java类(POJO...

    spring+hibernate+struts+XFire的webService实例

    本实例"Spring+Hibernate+Struts+XFire的WebService"提供了一个全面的框架整合,用于创建功能丰富的Web服务。以下将详细解析这个实例所涉及的技术点: 1. **Spring框架**:Spring是一个开源的Java平台,它为开发...

    SSH整合WebService框架XFire搭建总结.pdf

    ### SSH整合WebService框架XFire搭建总结 #### 一、SSH框架搭建 SSH框架是指Struts、Hibernate和Spring三个开源框架的结合使用。这三个框架分别负责Web层、持久层和业务逻辑层,通过它们的整合可以构建出高效稳定...

    CXF2.1.3+spring3.0+struts2.3.4

    通过Spring,可以将CXF和Struts2整合起来,使得各个组件之间的协作变得更加流畅。 【Struts2】是ActionServlet的一个实现,用于处理HTTP请求。Struts2.3.4版本包含了一些关键改进,如增强了拦截器的灵活性,提供了...

    WebService CXF+struts+spring 示例

    在"WebService CXF+Struts+Spring 示例"项目中,这三者如何协同工作呢? - **CXF**:作为Web服务的核心,CXF负责处理Web服务的发布、调用以及协议转换。在Spring环境中,CXF可以通过Spring配置文件进行配置,定义...

    ssh+cxf整合发布webservice实例

    在SSH+CXF的整合中,Struts2负责视图层和控制层,Spring处理依赖注入和事务管理,Hibernate处理持久化操作,而CXF则作为Web服务的发布平台。这种组合使得开发人员能够利用SSH的成熟性和CXF的灵活性,轻松地创建和...

Global site tag (gtag.js) - Google Analytics