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.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</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>

  <!-- 配置监听器 用于服务启动时加载全局参数,加载spring配置文件 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 配置servlet映射 -->
  <!-- 当网页访问test1目录时,会交由com.syx.controller.StudentController处理相应请求 -->
  <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();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值