目录
[编辑 测试结果](#编辑 测试结果)
1.SpringMvc的常用注解
@Controller:用于声明一个控制器类。
@RequestMapping:用于映射请求 URL 到控制器类或处理方法上。
@RequestParam:用于获取请求参数的值。
@PathVariable:用于获取 URL 中的参数值。
@ResponseBody:用于将返回值转化为 JSON 格式或其他格式的数据。
@ModelAttribute:用于将请求参数绑定到模型对象上。
@Valid:用于验证请求参数。
@InitBinder:用于定义数据类型转换和格式化规则。
@SessionAttributes:用于将模型对象存储到会话中。
@ExceptionHandler:用于处理控制器方法中抛出的异常。
@RequestMapping(value="", method=RequestMethod.GET) 用于处理 GET 请求。
@RequestMapping(value="", method=RequestMethod.POST) 用于处理 POST 请求。
@RequestMapping(value="", method=RequestMethod.PUT) 用于处理 PUT 请求。
@RequestMapping(value="", method=RequestMethod.DELETE) 用于处理 DELETE 请求。
2.参数传递
基础类型(String)
java
@RequestMapping("/hello1")
public String toHello1(Integer bid,String bname){
log.info(">>>> 基础类型+String传参:{},{}",bid,bname);
return "index";
}
创建一个paramController类:
java
package com.zking.web;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author bin人
* @site www.zking.com
* @company xy集团
* @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
java
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>立地成佛</h1>
</body>
</html>
测试结果
复杂方式
测试结果
@RequestParam
(用了这个required=false必须要传参数,要不然进入不了方法)
测试结果
必须要传bname要不然会报错,也接受不到值
传了值之后就可以正常访问了
@PathVariable
java
@RequestMapping("/hello4/{bid}")
public String hello4(@PathVariable("bid") Integer bid){
log.info("@PathVariable:bid:{}",bid);
// fail..error warning info debug
return "index";
}
测试结果
@RequestBody
java
@RequestMapping("/hello5/{bid}")
public String hello5(Map map){
log.info("@RequestBody:map:{}",map);
// fail..error warning info debug
return "index";
}
@RequestMapping("/hello6/{bid}")
public String hello6(@RequestBody Map map){
log.info("@RequestBody:map:{}",map);
// fail..error warning info debug
return "index";
}
想要用这个注解就必须导入架包依赖
pom.xml依赖导入
java
<?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.zking</groupId>
<artifactId>yxssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>yxssm 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>
<exclusions>
<exclusion>
<artifactId>commons-pool2</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>${commons.pool2.version}</version>
</dependency>
<!--4.log日志相关依赖-->
<!-- 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>
<!--核心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>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</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>
<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>
</dependencies>
<build>
<finalName>yxssm</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>
在导入依赖后我们还需要postman或者apipost/eolink等工具发送请求数据。 因为浏览器发送不了JSON数据请求。所以我们需要安装Eolink等第三方工具进行测试。
安装好后,按照以下步骤把参数填写好,query参数是往域名链接添加属性,如下:
输出结果
请看录像
通过方法五跟方法六的对比,可得出@RequestBody适用于专门接受Json
@RequestHeader
java
@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";
}
测试结果
3.返回值
void
先写工具类:
java
package com.zking.utils;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
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));
}
}
java
package com.zking.web;
import com.zking.utils.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 bing人
* @site
* @company xy集团
* @create 2023-09-06 22:12
*/
@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();
}
}
}
测试结果
Map
java
@ResponseBody//响应json数据
@RequestMapping("/hello2")
public Map hello2(HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
map.put("code", 200);
map.put("msg", "成功添加。");
return map;
}
测试结果
String
java
@RequestMapping("/hello3")
public String hello3() {
return "index";
}
测试结果
String+model
java
//String+model
@RequestMapping("/hello4")
public String hello4(Model model, HttpServletRequest request) {
model.addAttribute("currentName","浏阳鞭炮");
request.setAttribute("location","来自于刘老板的");
return "index";
}
测试结果
ModelAndView
4.页面跳转
转发
java
// 场景一:转发到后台的某一个方法(当前类)
@RequestMapping("/hello6")
public String hello6(){
System.out.println("hello6");
return "forward:hello2";
}
// 场景二:转发到后台的某一个方法(其他类)
@RequestMapping("/hello7")
public String hello7(){
System.out.println("hello7");
return "forward:/param/hello1";
}
测试结果
重定向
java
// 场景三:重定向到后台的某一个方法(当前类)
@RequestMapping("/hello8")
public String hello8(){
System.out.println("hello8");
return "forward:hello2";
}
// 场景四:重定向后台的某一个方法(其他类)
@RequestMapping("/hello9")
public String hello9(){
System.out.println("hello9");
return "forward:/param/hello1";
}