SpringMVC容器中Servlet如何呼叫service層介面
阿新 • • 發佈:2018-12-29
重寫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 花季歲月 */ public class ServletProxy extends HttpServlet { private static final long serialVersionUID = -2787541353517287396L; 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 xxxServlet extends ServletProxy{ private static final long serialVersionUID = 4655255916024403271L; @Autowired private ***Service ***Service; //...get/set方法自行生成下 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //呼叫介面 ***Service.介面方法 } }