<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.14</version> </dependency>
<!-- 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" > <!-- 配置DispatcherServlet:这个是SpringMVC的核心,也称为:请求分发器,前端控制器 --> <servlet> <servlet-name>springmvc</ servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>\ <!-- DispatcherServlet 要绑定 Spring 的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- 启动级别: 1 。数字越小,启动越早 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 在SpringMVC 中,/ 和 /* 存在区别 / : 只匹配所有的请求,不会去匹配jsp页面 /*: 匹配所有的请求,包括jsp页面 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<!-- Spring 配置文件 --> <!-- springmvc-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 处理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- 处理器适配器 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- 视图解析器:模板引擎 ThymeLeaf Freemarker... --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp"/> </bean> <!-- BeanNameUrlHandlerMapping: bean --> <bean id="/hello" class="com.kuang.controller.HelloController"/> </beans>
步骤如下:
- 新建一个 web 项目
- 导入相关 jar 包
- 编写 web.xml ,注册 DispatcherServlet
- 编写 SpringMVC 配置文件
- 接下来就是去创建对应的控制类,Controller
- 最后完善前端视图和 Controller 之间的对应
- 测试运行调试
使用 SpringMVC 必须配置的三大件:
处理器映射器、处理器适配器、视图解析器通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,而省去了大段的 xml 配置
<!-- Spring 配置文件 --> <!-- springmvc-servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自动扫描包,让指定包下的注解生效,由 IOC 容器统一管理 --> <context:component-scan base-package="controller"/> <!-- 让 Spring MVC 不处理静态资源.css .js .html .mp3 .mp4 --> <mvc:default-servlet-handler /> <!-- 支持mvc注解驱动 Spring中一般采用 @RequestMapping 注解来完成映射关系 要想使 @RequestMapping 注解生效必须向上下文中注册 DefauLtAnnotationHandLerMapping 和一个 AnnotationMethodHandLerAdapter 实例 这两个实例分别在类级别和方法级别处理。 而annotation-driven配置帮助我们自动完成上述两个实例的注入。 --> <mvc:annotation-driven /> <!-- 视图解析器:模板引擎 ThymeLeaf Freemarker... --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp"/> </bean> </beans>
@Controller @RequestMapping("/hello") public class Hellocontroller { // localhost:8080/hello/h1 @RequestMapping("/h1") public String hello(Model model) { //封装数据 model.addAttribute( s: "msg", o: "Hello,SpringMVCAnnotation! "); return "hello"; //会被视图解析器处理,直接跳转到视图hello.jsp; } }
<!-- hello.jsp --> <%@page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
概念
功能
传统方式操作资源:通过不同的参数来实现不同的效果!方法单一,Post和 Get
http://127.0.0.1/item/queryltem.action?id=1
查询,GEThttp://127.0.0.1/item/saveltem.action
新增,POSThttp://127.0.0.1/item/updateltem.action
更新,POSThttp://127.0.0.1/item/deleteltem.action?id=1
删除,GET或POST使用RESTful操作资源:可以通过不同的请求方式来实现不同的效果!请求地址一样,但是功能可以不同!
http://127.0.0.1/item/1
查询,GEThttp://127.0.0.1/item
新增,POSThttp://127.0.0.1/item
更新,PUThttp://127.0.0.1/item/1
删除,DELETE原来的风格:
@Controller public class RestFulController { //原来的:http://localhost:8080/add?a=1&b=2 @RequestMapping("/add") public String test1(int a,int b,Model model){ int res = a + b; model.addAttribute( "msg" , "结果为" + res ); return "test"; } }
RESTful风格:
@Controller public class RestFulController { //RestFul:http://localhost:8080]add/a/b //示例请求:http://localhost:8080]add/1/2 @RequestMapping("/add/{a}/{b}") public String test1(@PathVariable int a, @PathVariable int b, Model model){ int res = a + b; model.addAttribute( "msg" , "结果为" + res ); return "test"; } }
示例:
@Controller public class RestFulController { //@RequestMapping(path = "/add/{a}/{b}", method = RequestMethod.GET) 等价于 @GetMapping("/add/{a}/{b}") public String test1(@PathVariable int a, @PathVariable int b, Model model){ int res = a + b; model.addAttribute( "msg" , "结果为" + res ); return "test"; } }
通过SpringMVC来实现转发和重定向 — 有视图解析器
重定向,不需要视图解析器,本质就是重新请求一个新地方嘛,所以注意路径问题。
可以重定向到另外一个请求实现。
@Controller public class ResultspringMVC2 { @RequestMapping( "/rsm2/t1" ) public String test1() { //转发 return "test"; //转发时,存在视图解析器的话,直接写视图名,无需后缀 } @RequestMapping( "/rsm2/t2" ) public String test2() { //重定向 return "redirect:/index.jsp" ; //重定向时,写好路径名 // return "redirect:hello.do" ; // hello.do为另一个请求 } }
重点:在方法参数前添加注解 @RequestParam
提交数据:http://localhost:8080/hello?username=wjd
处理方法︰
//@RequestParam( "username" ) : username提交的域的名称 @RequestMapping( "/hello" ) public String hello(@RequestParam( "username" ) String name) { System.out.println( name ) ; return "hello" ; }
后台输出:wjd
提交数据:http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15
处理方法︰
@RequestMapping( "/user" ) public String user ( User user ) { System.out.println(user); return "hello" ; }
后台输出:User { id=1,name= 'kuangshen', age=15 }
说明:如果使用对象的话,前端传递的参数名和对象名必须一致,否则就是null。
@RequestMapping( "/ct2/hello" ) public String hello(@RequestParam( "username" ) String name, Model model){ //封装要显示到视图中的数据 //相当于req.setAttribute( "name", name); model.addAttribute( "msg", name ) ; System.out.println(name); return "test"; }
@RequestMapping( "/ct2/hello" ) public String hello(ModelMap model){ model.addAttribute( "msg", name ) ; return "test"; }
public class ControllerTest1 implements Controller { public ModelAndView handleRequest(){ //返回一个模型视图对象 ModelAndview mv = new ModelAndView(); mv.addObject ( "msg", "controllerTest1" ); mv.setViewName ( "test" ); return mv; } }
使用区别:
在 web.xml 中配置 Spring MVC 的乱码过滤器
<!-- web.xml --> <!-- 配置SpringMVC的乱码过滤器 --> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <!-- 这里一定要用 /* 才能过滤所有请求,如果用 / 会有个别的请求(jsp页面的请求)无法过滤 --> <url-pattern>/*</url-pattern> </filter-mapping>
上面这种过滤器,能够解决POST请求的乱码问题,对于GET请求,还是会乱码
实在不行用这种:
@RequestMapping(path = "/test", produces = "application/json; charset=utf-8")
在 springmvc-servlet.xml 中配置 mvc:annotation-driven
<!-- Spring 配置文件 springmvc-servlet.xml --> <!-- JSON乱码问题配置 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false" /> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
@Controller、@RequestMapping
@Controller public class TestController { @RequestMapping("/01") public String test() { return "已经进入了test方法"; } }
@PathVariable(URL路径段作为参数)
@Controller public class RestFulController { @RequestMapping("/add/{a}/{b}") public String test1(@PathVariable String a, @PathVariable String b, Model model){ model.addAttribute( "msg" , "结果为" + a + b ); return "test"; } }
@RequestParam(设置GET/POST请求参数名)
@RequestMapping( "/ct2/hello" ) public String hello(@RequestParam( "username" ) String name, Model model){ //封装要显示到视图中的数据 //相当于req.setAttribute( "name", name); model.addAttribute( "msg", name ) ; System.out.println(name); return "test"; }
@ResponseBody
当某一方法String返回值不想经过视图解析器时,在方法名上方使用此注解
@RestController
当控制器中的所有方法均不想经过视图解析器时,使用此注解
@Controller public class TestController { @ResponseBody @RequestMapping("/01") public String test() { return "已经进入了test方法"; } } //等价于 @RestController public class TestController { @RequestMapping("/01") public String test() { return "已经进入了test方法"; } }
在applicationContext.xml中添加配置
<!-- applicationContext.xml --> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <!-- ** 包括这个请求下面的所有的请求 --> <mvc:mapping path="/**"/> <bean class="com.kuang.config.MyInterceptor" /> </mvc:interceptor> </mvc:interceptors>
编写拦截器类
package config; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyInterceptor implements HandlerInterceptor { /* return true; 执行下一个拦截器,放行 return false; 不执行下一个拦截器 */ @Override public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception { return HandlerInterceptor.super.preHandle( request, response, handler ); } @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception { HandlerInterceptor.super.postHandle( request, response, handler, modelAndView ); } @Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception { HandlerInterceptor.super.afterCompletion( request, response, handler, ex ); } }
在applicationContext.xml中添加配置
<!-- applicationContext.xml --> <!-- 文件上传配置 --> <bean id="multipartResolver" class="org.springframework. web.multipart.commons.CommonsMultipartResolver"> <!-- 请求的编码格式,必须和JSP的pageEncoding属性一致,以便正确读取表单的内容,默认为IS0-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- 上传文件大小上限,单位为字节(10485760=10M) --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
编写文件控制器类
@RequestMapping( "/upload2" ) // @RequestParam("file")将 name=file 控件得到的文件封装成 CommonsMultipartFile 对象 // 批量上传 CommonsMultipartFile 则为数组即可 public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpservletRequest request) throws IOException { //上传路径保存设置 String path = request.getServletContext().getRealPath( "/upload" ); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上传文件地址 System.out.println("上传文件保存地址:"+realPath); //通过CommonsMultipartFile的方法 transferTo() 直接写文件 file.transferTo(new File( realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; }
<!-- pom.xml --> <dependencies> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--数据库连接池:c3p0: dbcp--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <!-- Servlet-JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.9.RELEASE</version> </dependency> </dependencies>
<!-- pom.xml --> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置数据源交给 Spring 去做 --> <typeAliases> <package name="pojo"/> </typeAliases> <mappers> <mapper class="mapper.UserMapper"/> </mappers> </configuration>
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="spring-dao.xml"/> </beans>
db.properties 必须加 jdbc. 这个前缀,不然报错
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false jdbc.username=root jdbc.password=
spring-dao.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 https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1.关联数据库配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 2.连接池 dbcp:半自动化操作,不能自动连接 c3p0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中!) druid : hikari --> <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}"/> <!-- c3p0连接池的私有属性 --> <property name="initialPoolSize" value="10"/> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000" /> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2"/> </bean> <!-- 3.sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 绑定Mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="mapperLocations" value="classpath:dao/*.xml"/> </bean> <!-- 4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中! --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 要扫描的dao包 --> <property name="basePackage" value="dao" /> </bean> </beans>
注意事项:
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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1.注解驱动 --> <mvc:annotation-driven/> <!-- 2.静态资源过滤 --> <mvc:default-servlet-handler/> <!-- 3.扫描包: controller --> <context:component-scan base-package="controller" /> <!-- 4.视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>