javascript
Spring整合web开发
正常整合Servlet和Spring沒有問題的
public class UserServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService = (UserService) applicationContext.getBean("userService");userService.sayHello();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);} }但是每次執(zhí)行Servlet的時(shí)候都要加載Spring配置,加載Spring環(huán)境,極大地降低效率!!!
解決辦法
1:在Servlet的init方法中加載Spring配置文件?(不好)
當(dāng)前這個(gè)Servlet可以使用,但是其他的Servlet用不了了!!!如果要使用,必須每個(gè)Servlet的init方法中都要加載Spring配置文件,太麻煩(pass)
2:將加載的信息內(nèi)容放到ServletContext中(正確)
ServletContext對(duì)象是全局的對(duì)象.服務(wù)器啟動(dòng)的時(shí)候創(chuàng)建的.在創(chuàng)建ServletContext的時(shí)候就加載Spring的環(huán)境,ServletContextListener用于監(jiān)聽ServletContext對(duì)象的創(chuàng)建和銷毀
使用方法
1:導(dǎo)入Spring web開發(fā)jar包:spring-web-3.2.0.RELEASE.jar
2:將Spring容器初始化,交由web容器負(fù)責(zé),配置核心監(jiān)聽器 ContextLoaderListener,配置全局參數(shù)contextConfigLocation(用于指定Spring的框架的配置文件位置)
在web.xml中配置
修改程序的代碼
public class UserServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/*也可用這種方式獲得applicationContext:WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);*/WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());UserService userService = (UserService) applicationContext.getBean("userService");userService.sayHello();}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }轉(zhuǎn)載于:https://www.cnblogs.com/fengmingyue/p/6202892.html
總結(jié)
以上是生活随笔為你收集整理的Spring整合web开发的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: H5项目开发分享——用Canvas合成文
- 下一篇: 95558怎么转人工服务?可以办理哪些业