其他分享
首页 > 其他分享> > spring集成web环境

spring集成web环境

作者:互联网

1、maven工程导入依赖

除了导入常规依赖外,web项目还需要导入如下依赖

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

2、配置web.xml各个标签

配置全局参数,监听器,servlet映射。

监听器内部加载spring配置文件,创建应用上下文并存储到ServletContext(工程内servlet共享的一块内存)域中,在Web项目启动时,容器会读取listener和contex-param标签的配置。

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- 加载全局初始化参数 -->
  <context-param>
   <!-- 配置需要加载的配置文件为ApplicationContext.xml -->
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:ApplicationContext.xml</param-value>
  </context-param>

  <!-- 配置监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 配置servlet映射 -->
  <servlet>
    <servlet-name>userServlet</servlet-name>
    <servlet-class>com.syx.controller.StudentController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>userServlet</servlet-name>
    <url-pattern>/test1</url-pattern>
  </servlet-mapping>
</web-app>

3、编写web类

继承HttpServlet并重写其方法(doGet…等)
使用WebApplicationContextUtils工具类中的getWebApplicationContext获取配置文件上下文对象

public class StudentController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet是重写doGet方法时自动生成的调用父类方法的语句,这里没用,直接删掉就行了
        //super.doGet(req, resp);

        // 获取servlet上下文
        ServletContext context = req.getServletContext();
        //获取配置文件上下文,这里获取的配置文件是web.xml中配置的contextConfigLocation对应的文件
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
        //获取javaBean
        studentService studentService = (studentService) applicationContext.getBean("studentServiceId");
        //调用对象的方法
        studentService.printSuccess();
    }
}

标签:集成,web,配置文件,spring,doGet,studentService,servlet,javax
来源: https://blog.csdn.net/qq_36929123/article/details/115445967