目录
最后SpringMVC综合案例就到这里,祝大家在敲代码的路上一路通畅!
- @RequestMapping:@RequestMapping注解是一个用来处理请求地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。
@RequestParam:@RequestParam主要用于将请求参数区域的数据映射到控制层方法的参数上
@ModelAttribute:
绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;
暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;
暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。
@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 配置文件 ,以下配置(修改)完后的所有配置:
- "1.0" encoding="UTF-8"?>
-
"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">
-
4.0.0 -
-
org.example -
index -
1.0-SNAPSHOT -
war -
-
index Maven Webapp -
-
http://www.example.com -
-
-
UTF-8 -
1.8 -
1.8 -
3.7.0 -
-
-
-
5.0.2.RELEASE -
-
3.4.5 -
-
5.1.44 -
-
5.1.2 -
-
1.3.1 -
-
2.1.1 -
2.4.3 -
-
2.9.1 -
3.2.0 -
1.7.13 -
-
4.12 -
4.0.0 -
1.18.2 -
-
1.2 -
1.1.2 -
-
5.0.2.RELEASE -
2.9.3 -
-
-
-
-
-
-
org.springframework -
spring-context -
${spring.version} -
-
-
org.springframework -
spring-orm -
${spring.version} -
-
-
org.springframework -
spring-tx -
${spring.version} -
-
-
org.springframework -
spring-aspects -
${spring.version} -
-
-
org.springframework -
spring-web -
${spring.version} -
-
-
org.springframework -
spring-test -
${spring.version} -
-
-
-
-
org.mybatis -
mybatis -
${mybatis.version} -
-
-
-
mysql -
mysql-connector-java -
${mysql.version} -
-
-
-
com.github.pagehelper -
pagehelper -
${pagehelper.version} -
-
-
-
org.mybatis -
mybatis-spring -
${mybatis.spring.version} -
-
-
-
-
org.apache.commons -
commons-dbcp2 -
${commons.dbcp2.version} -
-
-
org.apache.commons -
commons-pool2 -
${commons.pool2.version} -
-
-
-
-
-
-
org.slf4j -
slf4j-api -
${slf4j.version} -
-
-
org.slf4j -
jcl-over-slf4j -
${slf4j.version} -
runtime -
-
-
-
com.fasterxml.jackson.core -
jackson-databind -
${jackson.version} -
-
-
com.fasterxml.jackson.core -
jackson-core -
${jackson.version} -
-
-
com.fasterxml.jackson.core -
jackson-annotations -
${jackson.version} -
-
-
-
-
org.apache.logging.log4j -
log4j-api -
${log4j2.version} -
-
-
org.apache.logging.log4j -
log4j-core -
${log4j2.version} -
-
-
-
org.apache.logging.log4j -
log4j-slf4j-impl -
${log4j2.version} -
-
-
-
org.apache.logging.log4j -
log4j-web -
${log4j2.version} -
runtime -
-
-
-
-
com.lmax -
disruptor -
${log4j2.disruptor.version} -
-
-
-
-
junit -
junit -
${junit.version} -
-
-
-
javax.servlet -
javax.servlet-api -
${servlet.version} -
provided -
-
-
org.projectlombok -
lombok -
${lombok.version} -
provided -
-
-
-
-
org.springframework -
spring-webmvc -
${spring.version} -
-
-
jstl -
jstl -
${jstl.version} -
-
-
taglibs -
standard -
${standard.version} -
-
-
-
-
-
index -
-
-
-
-
src/main/java -
-
**/*.xml -
-
-
-
-
src/main/resources -
-
jdbc.properties -
*.xml -
-
-
-
-
-
-
-
org.apache.maven.plugins -
maven-compiler-plugin -
${maven.compiler.plugin.version} -
-
${maven.compiler.source} -
${maven.compiler.target} -
${project.build.sourceEncoding} -
-
-
-
org.mybatis.generator -
mybatis-generator-maven-plugin -
1.3.2 -
-
-
-
mysql -
mysql-connector-java -
${mysql.version} -
-
-
-
true -
-
-
-
-
-
maven-clean-plugin -
3.1.0 -
-
-
-
maven-resources-plugin -
3.0.2 -
-
-
maven-compiler-plugin -
3.8.0 -
-
-
maven-surefire-plugin -
2.22.1 -
-
-
maven-war-plugin -
3.2.2 -
-
-
maven-install-plugin -
2.5.2 -
-
-
maven-deploy-plugin -
2.8.2 -
-
-
- @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" %>
-
Title 看你不爽哦
效果显示:
![]()

- @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 debug
- return "index";
- }
效果演示:
![]()

- @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 debug
- return "index";
- }
注意:

演示效果:

根据条件输入 正确地址:

![]()
- @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 debug
- return "index";
- }
演示效果:

在进行@RequestBody传参前先要在pom.xml传入依赖,如下:
2.9.3 -
-
-
com.fasterxml.jackson.core -
jackson-databind -
${jackson.version} -
-
-
com.fasterxml.jackson.core -
jackson-core -
${jackson.version} -
-
-
com.fasterxml.jackson.core -
jackson-annotations -
${jackson.version} -
这里我们需要在Eolink Apikit软件工具上进行测试请求地址:
按照以下步骤把参数填写好,query参数是往域名链接添加属性,如下:

然后介绍完Query参数后就开始添加我们的请求体参数,如下:


- @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 debug
- return "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 debug
- return "index";
- }
代码完成之后我们需要在Eolink中进行头部请求参数配置,如下:

然后进行测试结果如下:

最后我们再来测试以下方法八,个人配置如下:


请求方法有:
RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping
他们之间的关系为:
RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping
RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping的区别:
RequestMapping不安全,且不具备标识意义。
测试方法如下:
- //查询的请求
- @GetMapping
- public String type1(){
- System.out.println("@GetMapping:对应查询请求");
- return "index";
- }
-
- //新增的请求
- @PostMapping
- public String type2(){
- System.out.println("@PostMapping:对应新增请求");
- return "index";
- }
-
- //修改的请求
- @PutMapping
- public String type3(){
- System.out.println("@PutMapping:对应修改请求");
- return "index";
- }
-
- //删除的请求
- @DeleteMapping
- public 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
map = new HashMap(); - map.put("id",1);
- map.put("晚安","亲爱的梦");
- map.put("梦","增加成功!!!");
- ResponseUtil.writeJson(response,map);
- }
-
- @ResponseBody
- @RequestMapping("/test02")
- public Map Test02(HttpServletResponse response) throws Exception {
- Map
map = new HashMap(); - 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" %>
-
Title 字字句句喜欢你
- 歌词上句: ${Nobo1}
- 歌词下句: ${Nobo2}
处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void。
打开浏览器输入相对应地址,结果如下:

Model测试:
将test03换成test04接着输出即可:

打开浏览器输入相应请求地址,结果如下:

创建一个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
map = new HashMap(); - 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";
- }
-
-
- }
它相当于“request.getRequestDispatcher("url").forward(request,response)”。使用转发,既可以转发到jsp, 也可以转发到其他的控制器方法。
打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo02,结果如下:

打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo04,结果如下:
