Spring开发Web项目
![38186c4e015f33cef0b143e13039eba7.png](https://img-blog.csdnimg.cn/img_convert/38186c4e015f33cef0b143e13039eba7.png)
Web项目初始化SpringIoc容器
先新建一个Web项目,然后再导入开发项目必须的jar包,需要的jar包有:spring-java的6个jar和spring-web.jar。
导入jar包后我们要在项目的web.xml文件中配置spring-web.jar提供的监听器,该监听器可以在服务器启动时初始化Ioc容器。
org.springframework.web.context.ContextLoaderListener
然后再用context-param告诉监听器Ioc容器的位置,在 param-value里面通过classpath可指出要用哪些SpringIoc容器
contextConfigLocation classpath:applicationContext.xml, classpath:applicationContext-*
通过"*"可引入星号前面名称相同,但后面名称不同的所有SpringIoc容器。
classpath:applicationContext-* classpath:applicationContext-Controller, classpath:applicationContext-Dao, classpath:applicationContext-Service
拆分Spring配置文件
有两种拆分方法,一种是根据三层结构拆分,另一种是根据功能结构拆分。例如
classpath:applicationContext-Controller, classpath:applicationContext-Service, classpath:applicationContext-Dao
就是根据三层结构,在一个xml配置文件中配置所有Servlet文件,在一个xml配置文件中配置所有Service文件,在一个xml配置文件中配置所有Dao文件。有时候还需要在一个xml配置文件中配置所有数据库文件。
从SpringIoc容器中获取数据
先建好各个层的文件,然后在SpringIoc容器中通过bean实例化每个层的对象。
在web.xml配置文件中定义好运行Servlet文件所需的代码后,然后在Servlet文件通过重写init方法来获取bean,最后运行服务器即可。
@WebServlet(name = "QueryStudentByIdServlet")public class QueryStudentByIdServlet extends HttpServlet { IStudentService studentService; //通过springioc容器的set注入将studentService 注入给Servlet public void setStudentService(IStudentService studentService) { this.studentService = studentService; } //servlet初始化方法:在初始化时,获取SpringIoc容器中的bean对象 @Override public void init() throws ServletException { //在Web项目中用此方法获取Spring上下文对象,需要spring-web.jar ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); //在Servlet容器中,通过getBean获取Ioc容器中的Bean studentService = (IStudentService) context.getBean("studentService"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = studentService.queryStudentById(); request.setAttribute("name