目录
前言
一、常用注解
二、参数传递
编辑
1. 基础类型+String类型
2. 复杂类型
3. @RequestParam
4. @PathVariable
5.@RequestBody
6. @RequestHeader
三、方法返回值
一:void
二:String
三:String+model
四:ModelAndView
四、页面跳转
前言
在上一篇的博客中我们初步的了解学习SpringMVC基础知识,我们继续来学习SpringMVC常用注解、参数传递、返回值,希望这篇博客能够帮助到您!!!
一、常用注解
一、SpringMVC之常用注解
1.Controller:用于标识一个类是SpringMVC的控制器,它接收用户请求并返回相应的视图或数据。2.RequestMapping:用于映射请求的URL路径到控制器的处理方法。可以在类级别和方法级别使用,用于处理各种HTTP请求(GET、POST、PUT等)。
标注在方法上
用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法
@Controller public class HelloController {@RequestMapping("/requestTest")public String requestTest(){return "index";} }
标注在类和方法上
用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。注意:当你在类上添加RequestMapping注解后,如果要请求映射,就意味着请求要先映射到标注类的位置,然后再映射到该类的方法上
@Controller @RequestMapping("/hello") public class HelloController {@RequestMapping("/requestTest")public String requestTest(){return "index";} }
3.RequestParam:用于将请求参数绑定到处理方法的参数上。可以指定参数的名称、是否必须以及默认值。
4.PathVariable:用于将URL中的占位符参数绑定到处理方法的参数上。通常用于RESTful风格的URL。
5.ResponseBody:用于将方法的返回值直接作为HTTP响应的内容返回给客户端。适用于返回JSON、XML等非HTML格式的数据。
6.ModelAttribute:用于将请求参数绑定到一个对象上,并将该对象添加到模型中,可以在视图中获取。
7.RequestHeader:注解可以获取指定的请求头信息。
8.CookieValue:主要是将请求的Cookie数据,映射到功能处理方法的参数上。
具体操作
1.将pom.xml文件中原有的log4j的插件依赖替换为Slf4j的插件依赖
替换 pom.xml文件,(这里全部替换,未免大家copy错)
<?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>com.yx</groupId><artifactId>yx_ssm</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>yx_ssm 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日志相关--><!-- 替换为slf4j日志相关 --><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></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><!--4.log日志相关依赖--><!--核心log4j2jar包--><!--替换为 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><!--核心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><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>compile</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>yx_ssm</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>
测试插件是否成功安装
二、参数传递
配置运行项目
1. 基础类型+String类型
package com.lya.web;import com.lya.model.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;
import java.util.Map;/*** @author 程序猿-小李哥* @site www.xiaolige.com* @company 猪八戒有限集团* @create 2023-09-05-15:50*/
@Slf4j
@Controller
@RequestMapping("/param")
public class ParamController {@RequestMapping("/hello1")public String index(Integer bid ,String bname) {log.info("简单参数:bid:{},bname:{} ",bid,bname);return "index";}
}
2. 复杂类型
@RequestMapping("/hello2")public String hello2(Book book , HttpServletRequest httpServletRequest) {log.info("复杂参数:bid:{},bname:{} ",httpServletRequest.getParameter("bid"),httpServletRequest.getParameter("bname"));log.info("复杂参数:book:{} ",book.toString());return "index";}
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";}
控制台输出
不会输出任何结果。
注:@RequestParam的required属性
该参数是否为必传项。默认是true,表示请求中一定要传入对应的参数,否则会报404错误,如果设置为false时,当请求中没有此参数,将会默认为null,而对于基本数据类型的变量,则必须有值,这时会抛出空指针异常。如果允许空值,则接口中变量需要使用包装类来声明。
4. @PathVariable
@RequestMapping("/hello4/{bid}")public String toHello4(@PathVariable("bid") Integer bid){log.info(">>>> 使用@PathVariable注解传递参数:{}", bid);return "index";}
5.@RequestBody
<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>
测试代码
@RequestMapping("/hello5")public String toHello5(@RequestBody Map map){System.out.println(map);return "index";}
请使用postman或者apipost/eolink等工具发送请求数据。因为浏览器无法携带集合参数,所以借助第三方软件进行测试。
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";}
三、方法返回值
创建一个ReturnController类模拟测试案例
一:void
借助工具类
package com.lya.untils;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();write(response, om.writeValueAsString(o));}
}
代码
package com.lya.web;import com.lya.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;/*** @author 程序猿-小李哥* @site www.xiaolige.com* @company 猪八戒有限集团* @create 2023-09-06-15:50*/
@Controller
@RequestMapping("/rs")
public class ReturnController {@RequestMapping("/hello1")public void hello1(HttpServletResponse response){Map<String,Object> map=new HashMap<>();map.put("code",200);map.put("msg","成功添加...");try {ResponseUtil.writeJson(response,map);} catch (Exception e) {e.printStackTrace();}}}
二:String
该返回值类型在前面的参数传递中已经体现了。
三:String+model
<%--Created by IntelliJ IDEA.User: 86158Date: 2023/9/5Time: 15:49To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<h1>Hello</h1>
名称:${name}
地址:${address}
</body>
</html>
测试代码
package com.lya.web;import com.lya.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;/*** @author 程序猿-小李哥* @site www.xiaolige.com* @company 猪八戒有限集团* @create 2023-09-06-16:50*/
@Controller
@RequestMapping("/rs")
public class ReturnController {@RequestMapping("/hello2")public String hello2(Model model,HttpServletRequest request){model.addAttribute("name","刘彬彬");request.setAttribute("address","傻鸟");return "index";}}
四:ModelAndView
测试代码
package com.lya.web;import com.lya.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
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.xiaolige.com* @company 猪八戒有限集团* @create 2023-09-05-15:50* 测试类*/
@Controller
@RequestMapping("/rs")
public class ReturnController {@RequestMapping("/hello3")public ModelAndView hello3(){ModelAndView mv=new ModelAndView();mv.addObject("sign","耗子没有摸鱼");mv.setViewName("index");return mv;}
}
四、页面跳转
转发(forward:path)和重定向(redirect:path)这两种跳转方式将会绕开视图解析器的前缀和后缀;还有就是如果是在同一controller中则不用使用"/"从根目录开始,而如果是在不同的controller则一定要从根目录开始。
path为请求处理方法名,而非逻辑视图名。
-
转发(地址栏不变)
@RequestMapping("/helloPage1")public String toHelloPage1(){System.out.println("helloPage1");return "forward:toHello2";}
它相当于“request.getRequestDispatcher("url").forward(request,response)”。使用转发,既可以转发到jsp, 也可以转发到其他的控制器方法。
-
重定向(地址栏改变)
@RequestMapping("/helloPage2")public String toHelloPage2(){System.out.println("helloPage2");return "redirect:toHello2";}
它相当于“response.sendRedirect(url)”。需要注意的是,如果重定向到jsp页面,则jsp页面不能写在WEB-INF目录中,否则无法找到。
跳其它的controller
@RequestMapping("/helloPage3")public String toHelloPage3(){System.out.println("helloPage3");return "forward:/demo/hello";}
@RequestMapping("/helloPage4")public String toHelloPage4(){System.out.println("helloPage4");return "redirect:/demo/hello";}