目录
1.创建带有web应用的maven项目并引入spring
2. 创建controller层,编写servlet
3. 添加spring-web提供的监听器包并使用
1.创建带有web应用的maven项目并引入spring
点击新建maven项目,选择这个:
点击下一步,然后设置名称进入后,首先是配置包和pom.xml,默认刚创建的项目的结构下没有java和resource文件夹,可以自行新建,一个是源,一个是资源,然后再java包下添加自己的包名和各层类和接口,再pom.xml文件中需引入:
<!-- 配置spring容器-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!--配置spring-web,这里用于方便获得spring应用上下文-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!-- 配置servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- 配置jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
这四个依赖配置好后基本完成完成了spring与web应用集成的环境,然后是自行对各类进行创建bean和依赖注入。
注意:这种方式创建时,使用注解依赖注入没有@Request这种方式,但可以用其他两种方式。
2. 创建controller层,编写servlet
我们环境搭建好后,简单测试servlet,首先是在自己的包名下新建一个web层或者controller层,再新建一个servlet的类,类中代码如下,其中两个获取上下文稍后解释:
public class userController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取监听上下文
ServletContext servletContext=this.getServletContext();
//获取spring上下文
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
userService userservice =(userService) app.getBean("userService");
userservice.save();
}
}
这个功能的作用就是当服务器收到请求调用此servlet时,调用userservice的save方法,然后我们将这个servlet再web.xml中配置好,后期可以直接使用注解,配置好后再配置我们的tomcat服务器,添加工件,运行项目,访问对应的连接,即可检测到servlet被调用。
3. 添加spring-web提供的监听器包并使用
这个包的作用简单来说就是可以在项目运行之初就创建并获取一个spring容器,并将它放在servletContext中,每次任一其他服务需要从spring容器中取数据时就可以直接从servletContext中拿这个spring对象,而不用每次都重新创建一个容器,避免资源浪费,提升用户体验。
使用这个监听器包需记住这几个个名字:
ContextLoaderListener、contextConfigLocation、WebApplicationContextUtils
首先我们先导入这个监听器,再web.xml下添加:
<!-- 配置监听器,这里使用官方的监听包-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
然后这个监听器需要告诉它,我们spring的配置文件时哪一个,方法就是再web.xml定义一个全局变量,这个变量名就是监听器里需要的:
<!-- 全局初始化参数,给官方监听包里加上我们配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config.xml</param-value>
</context-param>
到这里就配置完成了,然后再我们的servlet里,像如下方法使用它:
public class userController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取监听上下文
ServletContext servletContext=this.getServletContext();
//获取spring上下文
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
userService userservice =(userService) app.getBean("userService");
userservice.save();
}
}
getWebApplicationContext方法需要接收的对象就是我们的监听上下文。