更新時間:2020-03-24 09:43:13 來源:動力節點 瀏覽2642次
Spring開發Web項目
Web項目初始化SpringIoc容器
先新建一個Web項目,然后再導入開發項目必須的jar包,需要的jar包有:spring-java的6個jar和spring-web.jar。
導入jar包后我們要在項目的web.xml文件中配置spring-web.jar提供的監聽器,該監聽器可以在服務器啟動時初始化Ioc容器。
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
然后再用context-param告訴監聽器Ioc容器的位置,在param-value里面通過classpath可指出要用哪些SpringIoc容器
<context-param> <!--監聽器的父類ContextLoader中有一個屬性contextConfigLocation,該屬性值保存著配置文件xml的位置--> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml, classpath:applicationContext-* </param-value> </context-param>
通過"*"可引入星號前面名稱相同,但后面名稱不同的所有SpringIoc容器。
<param-value> classpath:applicationContext-* </param-value> <!--上面代碼等同于下面的代碼--> <param-value> classpath:applicationContext-Controller, classpath:applicationContext-Dao, classpath:applicationContext-Service </param-value>
拆分Spring配置文件
有兩種拆分方法,一種是根據三層結構拆分,另一種是根據功能結構拆分。例如
<param-value> <!--Servlet文件--> classpath:applicationContext-Controller, <!--Service文件--> classpath:applicationContext-Service, <!--Dao文件--> classpath:applicationContext-Dao </param-value>
就是根據三層結構,在一個xml配置文件中配置所有Servlet文件,在一個xml配置文件中配置所有Service文件,在一個xml配置文件中配置所有Dao文件。有時候還需要在一個xml配置文件中配置所有數據庫文件。
從SpringIoc容器中獲取數據
先建好各個層的文件,然后在SpringIoc容器中通過bean實例化每個層的對象。
<!--在Dao層的xml配置文件定義如下--> <beanid="studentDao"class="dao.impl.StudentDaoImpl"> <!--在Service層的xml配置文件定義如下--> <beanid="studentService"class="service.impl.StudentServiceImpl"> <propertyname="studentDao"ref="studentDao"></property> </bean> <!--在Controller層的xml配置文件定義如下--> <beanid="studentServlet"class="servlet.QueryStudentByIdServlet"> <propertyname="studentService"ref="studentService"></property> </bean>
在web.xml配置文件中定義好運行Servlet文件所需的代碼后,然后在Servlet文件通過重寫init方法來獲取bean,最后運行服務器即可。
@WebServlet(name="QueryStudentByIdServlet") publicclassQueryStudentByIdServletextendsHttpServlet{ IStudentServicestudentService; //通過springioc容器的set注入將studentService注入給Servlet publicvoidsetStudentService(IStudentServicestudentService){ this.studentService=studentService; } //servlet初始化方法:在初始化時,獲取SpringIoc容器中的bean對象 @Override publicvoidinit()throwsServletException{ //在Web項目中用此方法獲取Spring上下文對象,需要spring-web.jar ApplicationContextcontext=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); //在Servlet容器中,通過getBean獲取Ioc容器中的Bean studentService=(IStudentService)context.getBean("studentService"); } protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ } protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ Stringname=studentService.queryStudentById(); request.setAttribute("name",name); request.getRequestDispatcher("result.jsp").forward(request,response); } }
以上就是動力節點Java培訓機構小編介紹的“2020年最新Javaweb項目視頻教程”的內容,希望對大家有幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習