目录
一.常用注解
实例:
二.参数转递
2.1. 基础类型
2.2. 复杂类型
2.3. @RequestParam
2.4.@PathVariable
2.5.@RequestBody
2.6.RequestHeader
2.7. 请求方法
三.返回值
3.1.void
3.2.String
3.3 String+Model
3.4 ModelAndView
四、页面跳转
4.1.转发
4.2.重定向
最后SpringMVC综合案例就到这里,祝大家在敲代码的路上一路通畅!
感谢大家的观看 !
一.常用注解
- @RequestMapping:@RequestMapping注解是一个用来处理请求地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。
@RequestParam:@RequestParam主要用于将请求参数区域的数据映射到控制层方法的参数上
@ModelAttribute:
绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;
暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;
暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。
@SessionAttributes:用于将数据存储到会话(Session)中,在多个请求之间共享数据。
@RequestBody:用于将方法的返回值直接作为响应体返回给客户端,常用于返回JSON数据。
@RequestHeader:使用 @RequestHeader 注解可以获取指定的请求头信息。
@PathVariable:该注解请求URI中的模板变量部分到处理器功能处理方法的方法参数上的绑定。
@CookieValue:@CookieValue注解主要是将请求的Cookie数据,映射到功能处理方法的参数上。
实例:
@RequestMapping:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = "active=true")public String getActiveUser(@PathVariable("id") int id) {// ...}
}
@RequestParam:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/create", method = RequestMethod.POST)public String createUser(@RequestParam("user") User user) {// ...}
}
@ModelAttribute:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/create", method = RequestMethod.POST)public String createUser(@ModelAttribute("user") @Valid User user, BindingResult result) {// ...}
}
@SessionAttributes:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/edit", method = RequestMethod.GET)public String editUser(@ModelAttribute("user") User user) {// ...}
}
@RequestBody:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/create", method = RequestMethod.POST)public String createUser(@RequestBody @Valid User user, BindingResult result) {// ...}
}
@RequestHeader:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/info", method = RequestMethod.POST)public String updateUserInfo(@RequestHeader("Content-Type") String contentType, @RequestHeader("Authorization") String authorization) {// ...}
}
@PathVariable:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/{id}/info/{name}", method = RequestMethod.GET)public String getUserInfo(@PathVariable("id") int userId, @PathVariable("name") String userName) {// ...}
}
@CookieValue:
@Controller
@RequestMapping("/users")
public class UserController {@RequestMapping(value = "/info", method = RequestMethod.GET)public String getUserInfo(@CookieValue("sessionId") String sessionId, @CookieValue("userId") int userId) {// ...}
}
二.参数转递
配置项目中的 pom.xml 配置文件 ,以下配置(修改)完后的所有配置:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>index</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>index Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version><!--添加jar包依赖--><!--1.spring 5.0.2.RELEASE相关--><spring.version>5.0.2.RELEASE</spring.version><!--2.mybatis相关--><mybatis.version>3.4.5</mybatis.version><!--mysql--><mysql.version>5.1.44</mysql.version><!--pagehelper分页jar依赖--><pagehelper.version>5.1.2</pagehelper.version><!--mybatis与spring集成jar依赖--><mybatis.spring.version>1.3.1</mybatis.spring.version><!--3.dbcp2连接池相关 druid--><commons.dbcp2.version>2.1.1</commons.dbcp2.version><commons.pool2.version>2.4.3</commons.pool2.version><!--4.log日志相关--><log4j2.version>2.9.1</log4j2.version><log4j2.disruptor.version>3.2.0</log4j2.disruptor.version><slf4j.version>1.7.13</slf4j.version><!--5.其他--><junit.version>4.12</junit.version><servlet.version>4.0.0</servlet.version><lombok.version>1.18.2</lombok.version><!-- jstl+standard --><jstl.version>1.2</jstl.version><standard.version>1.1.2</standard.version><!-- spring --><spring.version>5.0.2.RELEASE</spring.version><jackson.version>2.9.3</jackson.version></properties><dependencies><!--1.spring相关--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><!--2.mybatis相关--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!--pagehelper分页插件jar包依赖--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>${pagehelper.version}</version></dependency><!--mybatis与spring集成jar包依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis.spring.version}</version></dependency><!--3.dbcp2连接池相关--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-dbcp2</artifactId><version>${commons.dbcp2.version}</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>${commons.pool2.version}</version></dependency><!-- log4j2日志相关依赖 --><!-- log配置:Log4j2 + Slf4j --><!-- slf4j核心包--><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId><version>${slf4j.version}</version><scope>runtime</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>${jackson.version}</version></dependency><!--核心log4j2jar包--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>${log4j2.version}</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>${log4j2.version}</version></dependency><!--用于与slf4j保持桥接--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j-impl</artifactId><version>${log4j2.version}</version></dependency><!--web工程需要包含log4j-web,非web工程不需要--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-web</artifactId><version>${log4j2.version}</version><scope>runtime</scope></dependency><!--需要使用log4j2的AsyncLogger需要包含disruptor--><dependency><groupId>com.lmax</groupId><artifactId>disruptor</artifactId><version>${log4j2.disruptor.version}</version></dependency><!--5.其他--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><!-- <scope>test</scope>--></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>${servlet.version}</version><scope>provided</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version><scope>provided</scope></dependency><!-- spring mvc相关依赖 --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>${standard.version}</version></dependency></dependencies><build><finalName>index</finalName><resources><!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--><resource><directory>src/main/resources</directory><includes><include>jdbc.properties</include><include>*.xml</include></includes></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>${maven.compiler.plugin.version}</version><configuration><source>${maven.compiler.source}</source><target>${maven.compiler.target}</target><encoding>${project.build.sourceEncoding}</encoding></configuration></plugin><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.2</version><dependencies><!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency></dependencies><configuration><overwrite>true</overwrite></configuration></plugin><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></build>
</project>
2.1. 基础类型
@RequestMapping("/hello1")public String toHello1(Integer bid,String bname){log.info(">>>> 基础类型+String传参:{},{}",bid,bname);return "index";}
新建一个paramController类:
package com.junlinyi.web;import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;/*** @author 君临沂* @site www.junlinyi.com* @company 君氏集团* @create 2023-09-05-14:44*/
@Slf4j
@Controller
@RequestMapping("/param")
public class ParamController {@RequestMapping("/hello1")public String index(String bname,Integer bid){
// System.out.println("刘三金去拿奶茶喽。。。");log.info("简单类型参数:bname:{},bid:{}",bname,bid);return "index";}
}
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<h1>看你不爽哦</h1>
</body>
</html>
效果显示:
2.2. 复杂类型
@RequestMapping("/hello2")public String toHello2(Book book,HttpServletRequest req,HttpServletResponse resp,HttpSession session){System.out.println(book);log.info(">>>> HttpServletRequest/HttpServletResponse/HttpSession等等传参:{}", req.getRequestURI());return "index";}
在paramController类中添加以下方法:
@RequestMapping("/hello2")public String hello2(Book book, HttpServletRequest request){
// System.out.println("靓仔来了喽。。。");//servlet参数获取方式log.info("复杂类型参数:bname:{},bid:{}",request.getParameter("bname"),request.getParameter("bid"));//复杂传参log.info("复杂类型参数:book:{}",book.toString());
// fail..error warning info debugreturn "index";}
效果演示:
2.3. @RequestParam
@RequestMapping("/hello3")public String toHello3(@RequestParam Integer bid,@RequestParam(required = false,value = "price") Integer bookPrice,@RequestParam("bookName") String bname){log.info(">>>> 使用@RequestParam注解传递参数:{},{},{}", bid,bname,bookPrice);return "index";}
在paramController类中添加以下方法:
@RequestMapping("/hello3")public String hello3(@RequestParam String bname,@RequestParam(required = false) Integer bid){
// System.out.println("靓仔来了喽。。。");log.info("@requestParam参数:bname:{},bid:{}",bname,bid);
// fail..error warning info debugreturn "index";}
注意:
演示效果:
根据条件输入 正确地址:
2.4.@PathVariable
@RequestMapping("/hello4/{bid}")public String toHello4(@PathVariable("bid") Integer bid){log.info(">>>> 使用@PathVariable注解传递参数:{}", bid);return "index";}
在paramController类中添加以下方法:
@RequestMapping("/hello4/{bid}")public String hello4(@PathVariable("bid") Integer bid){
// System.out.println("靓仔来了喽。。。");log.info("@requestParam参数:bid:{}",bid);
// fail..error warning info debugreturn "index";}
演示效果:
2.5.@RequestBody
在进行@RequestBody传参前先要在pom.xml传入依赖,如下:
<jackson.version>2.9.3</jackson.version><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>${jackson.version}</version></dependency>
这里我们需要在Eolink Apikit软件工具上进行测试请求地址:
按照以下步骤把参数填写好,query参数是往域名链接添加属性,如下:
然后介绍完Query参数后就开始添加我们的请求体参数,如下:
2.6.RequestHeader
@RequestMapping("/hello7")public String toHello7(Book book, @RequestBody Map map, @RequestHeader("jwt") String jwt){System.out.println(map);System.out.println(book);System.out.println(jwt);return "index";}
方法代码如下:
@RequestMapping("/hello7")public String hello7(@RequestHeader("jwt") String jwt){
// System.out.println("靓仔来了喽。。。");log.info("@RequestHeader参数:jwt:{}",jwt);
// fail..error warning info debugreturn "index";}@RequestMapping("/hello8")public String hello8(Book book,@RequestBody Map map,@RequestHeader("jwt") String jwt){
// System.out.println(""靓仔来了喽。。。");log.info("Book:Book:{}",book.toString());log.info("@RequestBody参数:Map:{}",map);log.info("@RequestHeader参数:jwt:{}",jwt);
// fail..error warning info debugreturn "index";}
代码完成之后我们需要在Eolink中进行头部请求参数配置,如下:
然后进行测试结果如下:
最后我们再来测试以下方法八,个人配置如下:
2.7. 请求方法
请求方法有:
RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping
他们之间的关系为:
RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping
RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping的区别:
RequestMapping不安全,且不具备标识意义。
测试方法如下:
//查询的请求@GetMappingpublic String type1(){System.out.println("@GetMapping:对应查询请求");return "index";}//新增的请求@PostMappingpublic String type2(){System.out.println("@PostMapping:对应新增请求");return "index";}//修改的请求@PutMappingpublic String type3(){System.out.println("@PutMapping:对应修改请求");return "index";}//删除的请求@DeleteMappingpublic String type4(){System.out.println("@DeleteMapping:对应删除请求");return "index";}//RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping//RequestMapping不安全,且不具备标识意义
依次进行请求,请求的方式不同会进行不同的请求注解,具体操作与效果如下:
三.返回值
创建一个ResponseUtil工具类,辅助完成测试代码,如下:
package com.junlinyi.utils;import com.fasterxml.jackson.databind.ObjectMapper;import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;public class ResponseUtil {public static void write(HttpServletResponse response,Object o)throws Exception{response.setContentType("text/html;charset=utf-8");PrintWriter out=response.getWriter();out.println(o.toString());out.flush();out.close();}public static void writeJson(HttpServletResponse response,Object o)throws Exception{ObjectMapper om = new ObjectMapper();
// om.writeValueAsString(o)代表了json串write(response, om.writeValueAsString(o));}
}
创建一个ReturnController类,来进行方法的请求测试(包含关于返回值的所以方法)。如下:
package com.junlinyi.web;import com.junlinyi.utils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;/*** @author 君临沂* @site www.junlinyi.com* @company 君氏集团* @create 2023-09-05-14:44*/
@Controller
@RequestMapping("/rs")
public class ReturnController {@RequestMapping("/test01")public void Test01(HttpServletResponse response) throws Exception {Map<String,Object> map = new HashMap<String,Object>();map.put("id",1);map.put("晚安","亲爱的梦");map.put("梦","增加成功!!!");ResponseUtil.writeJson(response,map);}@ResponseBody@RequestMapping("/test02")public Map Test02(HttpServletResponse response) throws Exception {Map<String,Object> map = new HashMap<String,Object>();map.put("id",1);map.put("晚安","亲爱的梦");map.put("梦","增加成功!!!");return map;}@RequestMapping("/test03")public String Test03() {return "index02";}@RequestMapping("/test04")public String Test04(Model model,HttpServletRequest request) {model.addAttribute("Nobo1","他字字句句喜欢你");request.setAttribute("Nobo1","我曾经也想过一了百了");return "index02";}@RequestMapping("/test05")public ModelAndView Test05() {ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("Nobo2","他字字句句喜欢你");modelAndView.addObject("Nobo2","我曾经也想过一了百了");modelAndView.setViewName("index02");return modelAndView;}}
创建一个index.jsp页面进行显示测试,如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<h1>字字句句喜欢你</h1>
歌词上句: ${Nobo1}<br>
歌词下句: ${Nobo2}
</body>
</html>
3.1.void
处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void。
3.2.String
3.3 String+Model
打开浏览器输入相对应地址,结果如下:
Model测试:
将test03换成test04接着输出即可:
3.4 ModelAndView
打开浏览器输入相应请求地址,结果如下:
四、页面跳转
创建一个PathConterller测试类,进行页面跳转的各种方法测试,代码如下:
package com.junlinyi.web;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;/*** @author 君临沂* @site www.junlinyi.com* @company 君氏集团* @create 2023-09-06-16:19*/@Controller
@RequestMapping("/ts")
public class PathConterller {@ResponseBody@RequestMapping("/test02")public Map Test02(HttpServletResponse response) throws Exception {Map<String,Object> map = new HashMap<String,Object>();map.put("id",1);map.put("晚安","亲爱的梦");map.put("梦","增加成功!!!");return map;}//返回值中有转发(forward)和重定向(redirect)这两种跳转方式将会绕开视图解析器的前缀和后缀//转发到(当前类)的某一个方法@RequestMapping("/Demo01")public String Demo01(){System.out.println("请求地址:Demo01");System.out.println("转发到(当前类)的某一个方法");return "forward:test02";}//转发到(其他类)的某一个方法@RequestMapping("/Demo02")public String Demo02(){System.out.println("请求地址:Demo02");System.out.println("转发到(其他类)的某一个方法");return "forward:/rs/test04";}//重定向到(其他类)的某一个方法@RequestMapping("/Demo03")public String Demo03(){System.out.println("请求地址:Demo03");System.out.println("重定向到(其他类)的某一个方法");return "redirect:test02";}//重定向到(其他类)的某一个方法@RequestMapping("/Demo04")public String Demo04(){System.out.println("请求地址:Demo04");System.out.println("重定向到(其他类)的某一个方法");return "redirect:/rs/test04";}}
4.1.转发
它相当于“request.getRequestDispatcher("url").forward(request,response)”。使用转发,既可以转发到jsp, 也可以转发到其他的控制器方法。
打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo02,结果如下:
4.2.重定向
打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo04,结果如下: