您的位置:首页 > 编程语言 > Java开发

SpringMVC容器中Servlet如何调用service层接口

2017-03-12 22:00 417 查看
标题:在SpringMVC容器中Servlet如何调用Service层接口?

        直接最简单有效的方法,重写Servlet的Init()方法。代码如下:

1)、 首先新建一个重写Servlet的Init()方法的类继承HttpServlet

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

import org.springframework.web.context.WebApplicationContext;

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

/**

 * 描述:Servlet重写Init()方法

 * @author WangKun

 */

public class ServletProxy extends HttpServlet {  

/**



*/

private static final long serialVersionUID = 1L;

public void init() throws ServletException {  

       super.init();  

       WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());  

       AutowireCapableBeanFactory factory = wac.getAutowireCapableBeanFactory();  

       factory.autowireBean(this);  

   }  

}  

2)、新建自己需要的Servlet再继承重写Servlet的类 (ServletProxy) 

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  

import org.springframework.beans.factory.annotation.Autowired;

public class ***Servlet extends ServletProxy {

@Autowired
private ***Service ***Service;

    private static final long serialVersionUID = 2827297299439162553L;  

  

    public void doGet(HttpServletRequest request, HttpServletResponse response)   throws Exception {  

        doPost(request, response);  

    }  

  

  
public void doPost(HttpServletRequest request, HttpServletResponse response)    throws Exception { 

         

          ***Service.自己的接口方法。

        你自己的东西自己写了。

    }

  

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  servlet