Spring与web整合

创建maven的web项目 

 这个项目src下没有test等文件——手动创建 

 

关于web-app version="3.0" 的问题

如何改成推荐使用的web-app 4.0?

 再添加 就是默认4.0版本的了

配置监听器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


    <!--配置一个监听器: 监听Tomcat启动
      帮我们创建Spring容器
      spring-web的依赖中
   -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--指定spring配置文件或者是配置类
        默认值: WEB-INF/applicationContext.xml
        使用context-param 指定
     -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>

Spring与web整合

service为空的原因:

一个项目有两个容器:tomcat容器、Spring容器

访问的servlet是tomcat启动的

@Autowire()servlet注入了service 但是servlet没有注入到spring容器里 servlet没有交给spring管理

@Controller :把这个类交给spring

但是servlet不能交给Spring容器

无法获取spring容器中的service 只能手动getBean()注入service

手动getBean()

//提供获取Spring容器的工具类
   WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(application);
​
   //手动获取bean
   userService = webApplicationContext.getBean(UserService.class);
  
        User user = userService.queryById(Integer.parseInt(id));
   //json格式发送
        String json = JSON.toJSONString(user);
   response.setContentType("application/json;charset=UTF-8");
   PrintWriter writer = response.getWriter();
   writer.print(json);
   writer.flush();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值