3、SpringMVC PostMan工具使用
PostMan简介
Postman 是一款功能超级强大的用于发送 HTTP 请求的 Chrome插件 。做web页面开发和测试的人员会使用到该工具其主要特点 特点: 创建 + 测试:创建和发送任何的HTTP请求,使用PostMan发送 Get、Post、Delete请求等。
PostMan安装包下载:
📎Postman-win64-9.24.2-Setup.rar
4、SpringMVC 请求与响应
@RequestMapping
@RequestMapping注解是一个用来处理请求地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。
如果加载方法上就是具体访问路径 如果加载类上就是我们访问的前缀
springmvc 定义url路径是不允许重复
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'userController' method com.mayikt.controller.UserController#add() to { /add}: There is already 'orderController' bean method com.mayikt.controller.OrderController#add() mapped.
package com.mayikt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* /add UserController.add OrderController.add?
* 如果我们将@RequestMapping注解加在我们的类上面 是访问该接口前缀
* 如果加在方法上就是我们具体的访问路径
* /user/add
* @return
*/
@RequestMapping("/add")
@ResponseBody
public String add() {
return "add ok";
}
@RequestMapping("/delete")
@ResponseBody
public String delete() {
return "delete ok";
}
@RequestMapping("/select")
@ResponseBody
public String select() {
return "delete ok";
}
}
package com.mayikt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/order")
public class OrderController {
@RequestMapping("/add")
@ResponseBody
public String add() {
return "add ok";
}
@RequestMapping("/delete")
@ResponseBody
public String delete() {
return "delete ok";
}
}
接受Get/Post请求参数
和Controller层方法的形参同名,那么可以直接通过参数名接收值 即可
package com.mayikt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MemberController {
/**
* addMember
* <p>
* RequestMapping 默认的情况下 RequestMapping支持所有请求方式 例如 get、post 、delete
* method = RequestMethod.POST 设定该接口支持的类型 post
*
* @return
*/
@RequestMapping(value = "/addMember", method = RequestMethod.POST)
@ResponseBody
public String addMemberPost(Integer id, String name) {
System.out.println("id:" + id);
System.out.println("name:" + name);
return "ok";
}
/**
* addMember
* <p>
* RequestMapping 默认的情况下 RequestMapping支持所有请求方式 例如 get、post 、delete
* method = RequestMethod.POST 设定该接口支持的类型 post
*
* @return
*/
@RequestMapping(value = "/addMember", method = RequestMethod.GET)
@ResponseBody
public String addMemberGet(Integer id, String name) {
System.out.println("id:" + id);
System.out.println("name:" + name);
return "ok---get";
}
}
4.1、springmvc5种接受参数类型
1.普通参数
2.对象参数
3.嵌套对象参数
4.数组参数
5.集合普通参数
普通参数
1.url地址传参,地址参数名与形参变量名相同,定义形参即可接收参数;
2.如果发生url地址传参,地址参数名与形参变量名不同,使用@RequestParam绑定参数关系;
参数:
required:是否为必传参数
defaultValue:参数默认值
HTTP Status 400 - Required Integer parameter 'mayiktAge' is not present
//springmvc5种接受参数类型
//1.普通参数
@RequestMapping("/demo01")
@ResponseBody
public String demo01(String name, Integer age) {
return "name:" + name + ",age:" + age;
}
//1.普通参数
/**
* 1.@RequestParam("name")地址栏 传递参数名称name 方法形参名称mayiktName
* 2.required 是否必须传递该参数 默认是为true 也就是需要传递该参数 required = false 不需要必须传递该参数
* required
*/
@RequestMapping("/demo02")
@ResponseBody
public String demo02(@RequestParam(name = "name", required = false) String mayiktName,
@RequestParam(name = "age", required = false) Integer mayiktAge) {
return "name:" + mayiktName + ",age:" + mayiktAge;
}
对象参数
请求参数名与形参对象属性名相同,定义对象类型形参即可接收参数
嵌套对象参数
嵌套对象参数:请求参数名与形参对象属性名相同,按照对象层次结构关系即可接收嵌套对象属性参数
/**
* 使用对象来进行接受参数
* 地址栏中传递的参数名称与对象中成员属性名称保持一致即可
*
* @param mayiktUser
* @return
*/
@RequestMapping("/demo03")
@ResponseBody
public String demo02(MayiktUserEntity mayiktUser) {
return "name:" + mayiktUser.getUserName() + ",age:" + mayiktUser.getAge() + ",addres" +
mayiktUser.getMayiktUserInfo().getAddres().getBytes("ISO-8859-1","UTF-8");
}
package com.mayikt.entity;
public class MayiktUserEntity {
/**
* ?userName=mayikt&age=22
*/
private String userName;
private Integer age;
/**
* ?mayiktUserInfo.addres=湖北武汉市
*/
private MayiktUserInfoEntity mayiktUserInfo;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public MayiktUserInfoEntity getMayiktUserInfo() {
return mayiktUserInfo;
}
public void setMayiktUserInfo(MayiktUserInfoEntity mayiktUserInfo) {
this.mayiktUserInfo = mayiktUserInfo;
}
}
数组参数
请求参数名与形参属性名相同且请求参数为多个,定义数组类型形参即可接收参数
http://localhost:85/demo04?arrays=1&arrays=2
@RequestMapping("/demo04")
@ResponseBody
public String demo02(String[] arrays) {
return Arrays.toString(arrays);
}
集合保存普通参数
请求参数名与形参集合对象名相同且请求参数为多个,@RequestParam绑定参数关系
http://localhost:85/demo05?arrays=1&arrays=2
@RequestParam :同名请求参数可以使用@RequestParam注解映射到对应名称的集合对象中作为数据
@RequestMapping("/demo05")
@ResponseBody
public String demo02(@RequestParam List<String> arrays) {
return Arrays.toString(arrays.toArray());
}
4.2、springmvc接受json数据
开启接受json数据
@Configuration
@ComponentScan("com.mayikt.controller")
@EnableWebMvc
public class SpringMVCConfig {
maven依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
接受参数加上@RequestBody MayiktUserEntity mayiktUserEntity 标记 接受json数据
自动根据json数据反序列化成对象mayiktUserEntity
1.以实体类方式接收
{
"userName":"mayikt",
"age":22,
"mayiktUserInfo":{
"addres":"yushengjun"
}
}
/**
* 接受json数据(以实体类方式)
* {
* "userName":"mayikt",
* "age":22
* }
*
* @return
*/
@RequestMapping("/demo06")
@ResponseBody
public String demo06(@RequestBody MayiktUserEntity mayiktUserEntity) {
return mayiktUserEntity.toString();
}
2.以Map接收
json数据 key是为 Map的key value Map的value
需要注意json数据value与Map集合value类型保持一致否则报错
@RequestMapping("/demo08")
@ResponseBody
public String demo08(@RequestBody Map<String, String> paramMap) {
return paramMap.toString();
}
3.以List接收
[
{
"userName": "mayikt",
"age": "20"
},
{
"userName": "mayikt",
"age": "22"
}
]
@RequestMapping("/demo10")
@ResponseBody
public String demo10(@RequestBody List<MayiktUserEntity> list) {
return list.toArray().toString();
}
<h1>HTTP Status 415 - </h1>
<HR size="1" noshade="noshade">
<p><b>type</b> Status report</p>
<p><b>message</b> <u></u></p>
<p><b>description</b> <u>The server refused this request because the request entity is in a format not supported by
the requested resource for the requested method.</u></p>
没有开启@EnableWebMvc
4.3、springmvc响应json数据
1.在接口上加上@ResponseBody 根据该方法返回值 返回对应json数据 底层 根据返回值 序列化成json数据。
2.@RestController 标记该控制类所有接口都是返回json数据
@Controller
@ResponseBody
@RestController
public class MayiktRestController {
4.4、使用HttpServletRequest 获取参数
springmvc底层基于Servlet
Servlet HttpServletRequest HttpServletResponse
获取httprequest/response三种方式
1.public String mayikt(HttpServletRequest request,HttpServletResponse response)
2.HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
3. @Autowired
private HttpServletRequest request;
/**
* 获取到我们的 HttpServletRequest httpServletRequest
*
* @param id
* @param name
* @param httpServletRequest
* @return
*/
@RequestMapping(value = "/httprequestDemo01", method = RequestMethod.GET)
@ResponseBody
public String httprequestDemo01(Integer id, String name, HttpServletRequest httpServletRequest) {
System.out.println("id:" + id);
System.out.println("name:" + name);
String reqId = httpServletRequest.getParameter("id");
String reqName = httpServletRequest.getParameter("name");
System.out.println("reqId:" + reqId);
System.out.println("reqName:" + reqName);
/**
* 2.HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
*/
// 从ThreadLocal获取HttpServletRequest springmvc 底层基于Servlet 提前缓存好了ttpServletRequest
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return "ok---get";
}
/**
* 获取到我们的 HttpServletRequest httpServletRequest
*
* @param id
* @param name
* @return
*/
@RequestMapping(value = "/httprequestDemo02", method = RequestMethod.GET)
@ResponseBody
public String httprequestDemo02(Integer id, String name) {
System.out.println("id:" + id);
System.out.println("name:" + name);
/**
* 2.HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
*/
// 从ThreadLocal获取HttpServletRequest springmvc 底层基于Servlet 提前缓存好了ttpServletRequest
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String reqId = request.getParameter("id");
String reqName = request.getParameter("name");
System.out.println("reqId:" + reqId);
System.out.println("reqName:" + reqName);
return "ok---get";
}
4.5、springmvc restful简单介绍
什么是restful
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格规范。基于这个风格设计的软件可以更简洁,更有层次。
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
传统方式操作资源:通过不同的参数来实现不同的效果,post 和 get。
http://127.0.0.1/mayikt/getUser?id=1 查询,GET 用户id是为1信息
http://127.0.0.1/mayikt/saveUser 新增,POST
http://127.0.0.1/mayikt/updateUser 更新,POST
http://127.0.0.1/mayikt/deleteUser?id=1 删除,GET
(查询、删除)get 写操作(新增、修改)Post
使用RESTful操作资源 :可以通过不同的请求方式来实现不同的效果
例如:请求地址一样,但是实现的效果不一样 例如
发送请求get 执行查询、 发送POST 执行新增、发送PUT执行更新、发送DELETE
执行删除
http://127.0.0.1/user/1 查询,GET
http://127.0.0.1/user 新增数据,POST
http://127.0.0.1/user 更新,PUT
http://127.0.0.1/user/1 删除,DELETE
根据发送不同的类型 判断 访问不同的接口
restful案例演示
在@RequestMapping的value中使用URI template({变量名}),然后在@RequestMapping注解方法的需要绑定的参数前,使用@PathVariable指定变量名(如果变量名和参数名一致也可以不指定),从而将URL中的值绑定到参数上。
@RequestMapping组合注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
package com.mayikt.controller;
import com.mayikt.entity.MayiktUserEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class MayiktUserRestfulController {
/**
* Restful api 请求地址都是一样 根据不同请求方法判断
* User 增加/删除/修改/查询 api接口
* 提供根据id查询接口 ---请求方法类型 get 指定请求类型 是为get
* /user/{id} /user/1
*/
// @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
@GetMapping(value = "/user/{id}")
public MayiktUserEntity getUser(@PathVariable("id") Integer id) {
System.out.println("[getUser] id:" + id);
return new MayiktUserEntity("mayikt" + id, 22);
}
/**
* 根据id删除数据 发送请求类型 delete
*
* @param id
* @return
*/
// @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
@DeleteMapping(value = "/user/{id}")
public String deleteUser(@PathVariable("id") Integer id) {
System.out.println("[deleteUser] id:" + id);
return "ok:id" + id;
}
/**
* 新增添加数据 Post类型 传递 json数据
*
* @return
*/
// @RequestMapping(value = "/user", method = RequestMethod.POST)
@PostMapping(value = "/user")
public String addUser(@RequestBody MayiktUserEntity mayiktUserEntity) {
System.out.println("[addUser] mayiktUserEntity:" + mayiktUserEntity);
return "ok";
}
/**
* 修改数据 put类型 传递 json数据
*
* @return
*/
// @RequestMapping(value = "/user", method = {RequestMethod.PUT})
@PutMapping(value = "/user")
public String updateUser(@RequestBody MayiktUserEntity mayiktUserEntity) {
System.out.println("[updateUser] mayiktUserEntity:" + mayiktUserEntity);
return "ok";
}
/**
* @RequestMapping 没有指定请求方法 则 包含所有请求类型 get、put、post等 指定请求方法类型 method = RequestMethod.PUT
*/
}
4.6、springmvc 整合jsp技术(过时 了解该技术)
核心配置
package com.mayikt.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan("com.mayikt.controller")
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {
/**
* 1.@Configuration 定义SpringMVCConfig.xml配置文件
* 2.需要将我们的控制类注入到ioc容器 @ComponentScan("com.mayikt.controller")
* @ComponentScan("com.mayikt.controller")将该包下所有的类 注入到IOC容器种
* 3.在springmvc原理 所有请求过来先达到我们的 DispatcherServlet 分发具体控制类 方法执行
*
*
* @Configuration
* SpringMVCConfig.java @Configuration
* springmvc.xml=== SpringMVCConfig.java
* -->
*/
//WebMvcConfigurer
@Bean
public InternalResourceViewResolver resourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//请求视图文件的前缀地址
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
//请求视图文件的后缀
internalResourceViewResolver.setSuffix(".jsp");
internalResourceViewResolver.setExposeContextBeansAsAttributes(true);
return internalResourceViewResolver;
}
/**
* 视图配置
*
* @param registry
*/
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(resourceViewResolver());
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
webapp 目录下创建 WEB-INF/jsp 存放jsp
定义控制器
package com.mayikt.controller;
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;
@Controller
public class MayiktJspController {
@RequestMapping("/mayiktJsp")
public String mayiktJsp() {
return "mayikt";
}
}
定义jsp页面
<%--
Created by IntelliJ IDEA.
User: mayikt
Date: 2022/7/29
Time: 16:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>mayikt</title>
</head>
<body>
springmvc整合jsp
</body>
</html>