介绍&步骤
视频教程: https://www.bilibili.com/video/BV1WZ4y1P7Bp?p=37
官方笔记链接:https://pan.baidu.com/s/1dnL5hwOPHPMNgb81yzQIOQ
提取码:2022
目录:
目录结构:
1. Spring使用web
首先创建一个spring_mvc的web项目: https://blog.csdn.net/qq_45056135/article/details/124936596
步骤:
- 导入坐标
- 编写代码
- 在spring容器中配置bean
1.1 导入坐标
pom.xml
重点的web坐标
<!--web层-->
<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.2.1</version>
<scope>provided</scope>
</dependency>
总的坐标: mysql驱动和web层的坐标尽量和下面的一致 不然可能会报错
<dependencies>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- C3P0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--web层-->
<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.2.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin></plugins>
</build>
1.2 编写Dao&Service&Servlet层的代码
1.Dao 层 UserDao接口和UserDaoImpl实现
public interface UserDao {
void save();
}
public class UserDaoImpl implements UserDao {
public void save(){
System.out.println("save running....");
}
}
2.Service层 UserService 和UserServiceImpl
public interface UserService {
void save();
}
这是实现的是依赖注入
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void save() {
userDao.save();
}
}
3.Servelt 层 这里使用的是注解配置servlet路径
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
1.3 spring容器中配置set注入
配置文件jdbc.properties 配置数据库的连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
配置数据库和在service中注入dao层信息
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!--用于加载配置文件jdbc.properties 默认是resource目录下面-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--userDao的Bean-->
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<!--userService的Bean-->
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
</beans>
2.监听器优化
问题: 当前web层每次使用都要加载applicationContext.xml
配置文件, 我们可以直接利用监听器在服务器启动时就加载applicationContext.xml
配置文件即可(加载spring容器)
解决
2.1 自定义配置监听类
创建ContextLoaderListener
上下文监听类实现监听类接口
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
// applicationContext.xml
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
// 读取web.xml中的全局参数
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
// 将Spring的应用上下文存储到servletContext域中
servletContext.setAttribute("app", app);
System.out.println("监听器执行 spring容器创建完毕");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
WebApplicationContextUtils
目的是通过类调用静态方法获取applicationContext
对象
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicaitonContext(ServletContext servletContext){
ApplicationContext applicationContext = (ApplicationContext)servletContext.getAttribute("app");
return applicationContext;
}
}
web.xml
配置监听器ContextLoaderListener
和和全局参数classpath:applicationContext.xml
全局参数通过getInitParameter
获得得到applicationContext.xml
监听器用于调用ContextLoader
类的方法contextInitialed
方法生成applicaitonContext
对象和存储在servletContext
域中
然后通过WebApplicationContextUtils
获取得到applicationContext
对象
<?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">
<!--全局参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>com.itheima.listener.ContextLoaderListener</listener-class>
</listener>
</web-app>
- controller层的代码
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 得到servletContext对象
ServletContext servletContext = this.getServletContext();
// 传入servletContext对象 通过工具类得到applicationContext对象
ApplicationContext app = WebApplicationContextUtils.getWebApplicaitonContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
整体步骤:
服务器先执行监听器—>找到监听器对应的全局参数—> 加载配置文件applicationContext.xml–>通过WebApplicationContextUtils得到应用上下文对象—>得到Bean对象
2.2 利用spring的监听类
刚刚是我们自定义的监听器,接下来我们使用spring定义好的监听类
- 导入坐标
- 配置ContextLoaderListener监听器
- 使用WebApplicationContextUtils获得应用上下
2.2.1 pom.xml导入坐标
<!--spring-mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2.2.2 web.xml配置监听器
注意这里使用的是org.springframework.web.context.ContextLoaderListener
(spring实现的)不是自己定义的
<?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">
<!--全局参数-->
<context-param>
<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>
</web-app>
2.2.3 controller层代码
不用改变 只是WebApplicationContextUtils现在是org之前是导入自己定义的类
现在导入的包是(spring实现的)
import org.springframework.web.context.support.WebApplicationContextUtils;
之前导入的包是(自定义的)
import com.itheima.listener.WebApplicationContextUtils;
controller层代码
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
3.SpringMVC快速入门
controller层
applicationContext.xml配置文件
spring-mvc.xml配置文件
web.xml加载上面这个文件
目录结构:
3.1 导入坐标
pom.xml文件
<dependencies>
<!--Spring坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--spring-web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- C3P0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!--web层-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</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>
</dependencies>
<build>
<plugins>
<!-- tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin></plugins>
</build>
3.2 Webapp创建index.jsp/success.jsp
index.jsp 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hello ${username}, this is index.jsp
</body>
</html>
success.jsp 页面
hello ${username}, this is index.jsp
3.3 创建Controller和业务方法
这里我在resource有一个success.jsp的简单页面 访问quick会自动跳转
@Controller // 放在spring容器中 不配这个前端控制器找不到映射路径
public class UserController {
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running...");
return "/success.jsp";
}
}
3.4 文件配置
3.2.1 applicationContext.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
</beans>
3.2.2 spring-mvc.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!--Controller组件扫描-->
<context:component-scan base-package="com.itheima.controller"/>
</beans>
3.2.3 web.xml文件配置(前端控制器)
(用于加载applicationContext.xml,spring-mvc.xml这两个文件)
使用ContextLoaderListener监听器加载applicationContext.xml
配置文件
配置前端控制器DispatcherServlet加载spring-mvc.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">
<!--配置springMVC的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置映射地址-->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--全局参数-->
<context-param>
<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>
</web-app>
3.5 启动服务器进行访问测试
总结
4. SpringMVC 组件解析
4.1 SpringMVC的执行流程
4.2 SpringMVC注解解析
例如: 访问user/quick 利用get方法而且必须携带username参数 不带username参数会报错
@Controller // 放在spring容器中
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/quick", method = RequestMethod.GET, params = {"username"})
public String save(){
System.out.println("Controller save running...");
return "/success.jsp"; // 默认执行转发 如有想要重定向加一个前缀redirect:
}
}
4.3 SpringMVC注解解析
spring-mvc.xml
的组件扫描中
<!--Controller组件扫描-->
<context:component-scan base-package="com.itheima.controller"/>
等价于
<!--Controller组件扫描-->
<context:component-scan base-package="com.itheima">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
都表示扫描controller层
4.4 Spring-mvc.xml配置视图解析器
其实也就是set注入 默认为空
配置完成之后默认会有前后缀拼接
<!--配置内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
配置成功之后 success
—> /success.jsp
4.5 配置完之后完整的sprign-mvc.xml
代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!--Controller组件扫描-->
<context:component-scan base-package="com.itheima">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>