当前位置: 代码迷 >> Web前端 >> servlet与spring流入
  详细解决方案

servlet与spring流入

热度:398   发布时间:2012-11-09 10:18:47.0
servlet与spring注入
在servlet中操作程序,需要用到spring管理时,由于脱离了struts的跳转层,所以需要来配置servlet代理来注入spring
web.xml配置

代码: 全选
    <servlet>
    <servlet-name>PayMoneyApi</servlet-name>
    <servlet-class>com.holpe.action.systemPack.ServletToBeanProxy</servlet-class>//代理类,下面有贴出代码
    <init-param>
    <param-name>targetBean</param-name>
    <param-value>servletBean</param-value>
    </init-param>
    </servlet>

    <servlet-mapping>
       <servlet-name>PayMoneyApi</servlet-name>
       <url-pattern>/PayMoneyApi</url-pattern>
    </servlet-mapping>


spring的配置文件

代码: 全选
    <bean id="servletBean"
       class="com.holpe.action.systemPack.PayMoneyInteface">//servlet处理类
    //注入
       <property name="dealMangerAction">
          <ref bean="Service"/>
       </property>
       <property name="userService">
          <ref bean="userCenterService"/>
       </property>
       <property name="userMoneySer">
          <ref bean="userMoneyService"/>
       </property>
    </bean>


下面贴出代理类的写法

代码: 全选
    package com.holpe.action.systemPack;

    import java.io.IOException;

    import javax.servlet.GenericServlet;
    import javax.servlet.Servlet;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;

    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;

    @SuppressWarnings("serial")
    public class ServletToBeanProxy extends GenericServlet {

    private String targetBean;

    private Servlet proxy;


    public void init() throws ServletException {
    System.out.println("proxy init");
    this.targetBean = getInitParameter("targetBean");
    getServletBean();
    proxy.init(getServletConfig());
    }


    public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException {

    proxy.service(req, res);

    }


    private void getServletBean() {

    WebApplicationContext wac =
    WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    this.proxy = (Servlet)wac.getBean(targetBean);

    }


    }
  相关解决方案