- 创建一个web项目,在web - WEB-INF 下创建libs文件夹
- 导入Spring所需的一些jar包
链接:https://pan.baidu.com/s/12Fsy5NiJd8Gxn1cIQ4yXTA
提取码:fgej
- 在 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>
- 配置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>
- 测试
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. 测试成功