hprose spring集成 -- 让hproseservlet 使用spring的 bean

来源:互联网 发布:java asm问题处理 编辑:程序博客网 时间:2024/06/07 12:21
使用第一添加springcontextutil到项目中,这样没有session 和 servlet环境我们只根据bean id我们也可以获取到 spring 维护的 bean
package com.eluotuo.common.spring;import org.springframework.beans.BeansException;import org.springframework.beans.factory.NoSuchBeanDefinitionException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;import com.eluotuo.common.util.Logger;/** * spring上下文配置 * @author Mingchenchen * */@Componentpublic class SpringContextUtil implements ApplicationContextAware {    private static Logger logger = Logger.getLogger(SpringContextUtil.class);    private static ApplicationContext applicationContext = null;    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException    {        logger.info("------SpringContextUtil setApplicationContext-------");        SpringContextUtil.applicationContext = applicationContext;    }    public static ApplicationContext getApplicationContext() {        return applicationContext;    }    /**     * 注意 bean name默认 = 类名(首字母小写)     * 例如: A8sClusterDao = getBean("k8sClusterDao")     * @param name     * @return     * @throws BeansException     */    public static Object getBean(String name) throws BeansException {        return applicationContext.getBean(name);    }    /**     * 根据类名获取到bean     * @param <T>     * @param clazz     * @return     * @throws BeansException     */    @SuppressWarnings("unchecked")    public static <T> T getBeanByName(Class<T> clazz) throws BeansException {        try {            char[] cs=clazz.getSimpleName().toCharArray();            cs[0] += 32;//首字母大写到小写            System.out.println(applicationContext.getBean(String.valueOf(cs)));            return (T) applicationContext.getBean(String.valueOf(cs));        } catch (Exception e) {            e.printStackTrace();            return null;        }     }    public static boolean containsBean(String name) {        return applicationContext.containsBean(name);    }    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {        return applicationContext.isSingleton(name);    }}


接着把web.xml 里面配置的 hprose的servlet改为我重写过的。

package hprose.server;import hprose.common.FilterHandler;import hprose.common.HproseFilter;import hprose.common.HproseMethods;import hprose.common.InvokeHandler;import hprose.io.HproseClassManager;import hprose.io.HproseMode;import hprose.util.StrUtil;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.eluotuo.common.spring.SpringContextUtil;public class HproseServletForSpring extends  HttpServlet{    /**     * serialVersionUID     */    private static final long serialVersionUID = 1L;    protected final HproseHttpService service = new HproseHttpService();    @Override    public void init(ServletConfig config) throws ServletException {        super.init(config);        String param = config.getInitParameter("mode");        if (param != null) {            param = param.toLowerCase();            if (param.equals("propertymode")) {                service.setMode(HproseMode.PropertyMode);            }            else if (param.equals("fieldmode")) {                service.setMode(HproseMode.FieldMode);            }            else if (param.equals("membermode")) {                service.setMode(HproseMode.MemberMode);            }        }        param = config.getInitParameter("debug");        if (param != null) {            param = param.toLowerCase();            if (param.equals("true")) {                service.setDebugEnabled(true);            }        }        param = config.getInitParameter("crossDomain");        if (param != null) {            param = param.toLowerCase();            if (param.equals("true")) {                service.setCrossDomainEnabled(true);            }        }        param = config.getInitParameter("origin");        if (param != null) {            String[] origins = StrUtil.split(param, ',', 0);            for (int i = 0, n = origins.length; i < n; ++i) {                service.addAccessControlAllowOrigin(origins[i]);            }        }        param = config.getInitParameter("p3p");        if (param != null) {            param = param.toLowerCase();            if (param.equals("true")) {                service.setP3pEnabled(true);            }        }        param = config.getInitParameter("get");        if (param != null) {            param = param.toLowerCase();            if (param.equals("false")) {                service.setGetEnabled(false);            }        }        param = config.getInitParameter("event");        if (param != null) {            try {                Class<?> type = Class.forName(param);                if (HproseServiceEvent.class.isAssignableFrom(type)) {                    service.setEvent((HproseServiceEvent) SpringContextUtil.getBeanByName(type));                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("filter");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    Class<?> type = Class.forName(classNames[i]);                    if (HproseFilter.class.isAssignableFrom(type)) {                        service.addFilter((HproseFilter) SpringContextUtil.getBeanByName(type));                    }                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("beforeFilter");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    Class<?> type = Class.forName(classNames[i]);                    if (FilterHandler.class.isAssignableFrom(type)) {                        service.beforeFilter.use((FilterHandler) SpringContextUtil.getBeanByName(type));                    }                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("afterFilter");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    Class<?> type = Class.forName(classNames[i]);                    if (FilterHandler.class.isAssignableFrom(type)) {                        service.afterFilter.use((FilterHandler) SpringContextUtil.getBeanByName(type));                    }                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("invoke");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    Class<?> type = Class.forName(classNames[i]);                    if (InvokeHandler.class.isAssignableFrom(type)) {                        service.use((InvokeHandler) SpringContextUtil.getBeanByName(type));                    }                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        HproseMethods methods = service.getGlobalMethods();        param = config.getInitParameter("class");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    String[] name = StrUtil.split(classNames[i], '|', 3);                    Class<?> type = Class.forName(name[0]);                    Object obj = SpringContextUtil.getBeanByName(type);                    System.out.println(11);                    Class<?> ancestorType;                    switch (name.length) {                        case 1:                            methods.addInstanceMethods(obj, type);                            break;                        case 2:                            for (ancestorType = Class.forName(name[1]);                                    ancestorType.isAssignableFrom(type);                                    type = type.getSuperclass()) {                                methods.addInstanceMethods(obj, type);                            }                            break;                        case 3:                            if (name[1].equals("")) {                                methods.addInstanceMethods(obj, type, name[2]);                            }                            else {                                for (ancestorType = Class.forName(name[1]);                                        ancestorType.isAssignableFrom(type);                                        type = type.getSuperclass()) {                                    methods.addInstanceMethods(obj, type, name[2]);                                }                            }                            break;                    }                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("staticClass");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    String[] name = StrUtil.split(classNames[i], '|', 2);                    Class<?> type = Class.forName(name[0]);                    if (name.length == 1) {                        methods.addStaticMethods(type);                    }                    else {                        methods.addStaticMethods(type, name[1]);                    }                }            }            catch (ClassNotFoundException ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("type");        if (param != null) {            try {                String[] classNames = StrUtil.split(param, ',', 0);                for (int i = 0, n = classNames.length; i < n; ++i) {                    String[] name = StrUtil.split(classNames[i], '|', 2);                    HproseClassManager.register(Class.forName(name[0]), name[1]);                }            }            catch (ClassNotFoundException ex) {                throw new ServletException(ex);            }        }        param = config.getInitParameter("topic");        if (param != null) {            try {                String[] topics = StrUtil.split(param, ',', 0);                for (int i = 0, n = topics.length; i < n; ++i) {                    String[] item = StrUtil.split(topics[i], '|', 3);                    switch (item.length) {                        case 1:                            service.publish(item[0]);                            break;                        case 2:                            service.publish(item[0],                                    Integer.parseInt(item[1], 10));                            break;                        case 3:                            service.publish(item[0],                                    Integer.parseInt(item[1], 10),                                    Integer.parseInt(item[1], 10));                            break;                    }                }            }            catch (Exception ex) {                throw new ServletException(ex);            }        }        setGlobalMethods(methods);    }    protected void setGlobalMethods(HproseMethods methods) {    }    protected void processRequest(HttpServletRequest request, HttpServletResponse response)            throws ServletException {        service.handle(new HttpContext(service,                                       request,                                      response,                       this.getServletConfig(),                    this.getServletContext()));    }    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException {        processRequest(request, response);    }    @Override    protected void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException {        processRequest(request, response);    }    @Override    protected void doOptions(HttpServletRequest request, HttpServletResponse response)            throws ServletException {        processRequest(request, response);    }    @Override    public String getServletInfo() {        return "Hprose Servlet 2.0";    }    }

如果觉得这篇文章帮助到你,给作者打赏点咖啡钱吧。


0 0