web 项目整合 Spring

  1. 创建一个web项目,在web - WEB-INF 下创建libs文件夹
    在这里插入图片描述
  2. 导入Spring所需的一些jar包
    链接:https://pan.baidu.com/s/12Fsy5NiJd8Gxn1cIQ4yXTA
    提取码:fgej
    在这里插入图片描述
  3. 在 src 目录下创建applicationContext配置文件,进行简单的配置,测试用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userService" class="com.jqj.service.impl.UserServiceImpl"></bean>
</beans>
  1. 配置web.xml 文件
<?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">


    <!-- 配置spring配置文件的加载路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--监听器-->
    <listener>
        <!--默认配置是 [/WEB-INF/applicationContext.xml]路径下的文件-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
  1. 测试

a. 创建IUserService 接口

public interface IUserService {
    public void add(String username);
}

b. 创建UserServiceImpl 实现类

public class UserServiceImpl implements IUserService {
    @Override
    public void add(String username) {
        System.out.println("添加用户成功。。。"+username);
    }
}

c. 创建RegisterServlet

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String username = request.getParameter("username");
        //调用service
        //service的创建,由spring创建,从spring的容器中获取user
        //取applicationContext
      	ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
	    IUserService service= (IUserService) context.getBean("userService");
		
		System.out.println(context.hashCode());
        service.add(username);
        //响应
        response.getWriter().write("Register success");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

d. 测试成功
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值