Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件。
作用:常用于进行接口测试(超链接点击进入官网下载即可)
正常Free注册登录到下面的这个界面:
输入下面网址:运行你上面写的代码 你就不用打开浏览器接受了!
http://localhost:8080/hello
这个软件会收到响应回来的数据——Hello World
案例测试:
**原始方式:**在原始的web程序中,获取请求参数,需要通过HttpServletRequest对象手动获取。
package com.example.springbootwebre4sp.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/simpleParam")
public String simpleParam(HttpServletRequest request)
{
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
int age = Integer.parseInt(ageStr);
System.out.println("name="+name);
System.out.println("age ="+age);
return "OK";
}
}
http://localhost:8080/simpleParam?name=Tom&age=18
浏览器传递了name与age的参数后,服务器接受成功 and返回OK在浏览器中。
观察上面的步骤:发现原始方式过于繁琐,我还要手动类型转换,那么在SpringBoot中,如何简化上面的代码呢?
前端传递了参数后,我只需要在Controller中建立对应的形参就可以接受到了。
package com.example.springbootwebre4sp.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/simpleParam")
public String simpleParam(String name,int age)
{
System.out.println("name="+name);
System.out.println("age ="+age);
return "OK";
}
}
@RequestParam
中的required
属性默认为true
,代表该请求参数必须传递,如果不传递将报错。如果该参数是可选的,可以将required
属性设置为false
。Java 是怎么解决的呢?建立类!参数都是成员变量!!!!
User
package com.example.springbootwebre4sp.pojo;
public class User {
private String name;
public Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
RequestController
package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/simpleParam")
public String simpleParam(String name,int age)
{
System.out.println("name="+name);
System.out.println("age ="+age);
return "OK";
}
@RequestMapping("/simplePojo")
public String simplePojo(User user){
System.out.println(user);
return "OK";
}
}
请求参数名与形参数组名称相同且请求参数为多个,定义数组类型形参即可接收参数
package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/arrayParam")
public String arrayParam(String[] hobby)
{
System.out.println(Arrays.toString(hobby));
return "OK";
}
}
package com.example.springbootwebre4sp.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/listParam")
public String listParam(@RequestParam List<String> hobby)
{
System.out.println(hobby);
return "OK";
}
}
数组集合参数
入职时间、生日等时间类型的表单——可以封装到LocalDateTime中来
但是前端传来的时间类型多种多样,如2020年12月12日10时10分10秒
、2020/12/12 10:10:10
等等。
所以我要申明日期格式
http://localhost:8080/dataParam?updateTime=2020-12-12 10:10:10
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/dataParam")
public String dataParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime)
{
System.out.println(updateTime);
return "OK";
}
}
2020-12-12T10:10:10
http://localhost:8080/jsonParam
{
"name":"ITCAST",
"age":16,
"address":{
"province":"北京",
"city":"北京"
}
}
JSON参数: JSON数据键名与形参对象属性名相同,定义POJ0类型形参即可接收参数,需要使用@RequestBody
标识
User
package com.example.springbootwebre4sp.pojo;
public class User {
private String name;
private Integer age;
private Address address;
public User() {
}
public User(String name, Integer age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
'}';
}
}
Address
package com.example.springbootwebre4sp.pojo;
public class Address {
private String province;
private String city;
public Address() {
}
public Address(String province, String city) {
this.province = province;
this.city = city;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
'}';
}
}
package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.pojo.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/jsonParam")
public String jsonParam(@RequestBody User user)
{
System.out.println(user);
return "OK";
}
}
@PathVariable
获取路径参数统一资源定位符(Uniform Resource Locator)”简称为URL。实际上,我们在使用互联网的过程中,其中有许多东西都是只会用,而不知道它到底是啥名字,看见了也不理解它是做什么的,比如今天我将和大家说的URL,实际上就是我们在互联网生活中非常常见的一个东西。URL是web页的地址,这种地址会在浏览器顶部附近的Location或者URL框内显示出来。鼠标指针移至某个超链接上方时, URL也会在屏幕的底部显示出来。
百度百科的解释:URL是统一资源定位符,对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎处理它。
Q:那我们能把@RequestMapping("/path/1")
吗?
A:不能,因为如果这样,路径就死了,识别不了/path/2
。
so!
package com.example.springbootwebre4sp.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/path/{id}")
public String pathParam(@PathVariable Integer id)
{
System.out.println(id);
return "OK";
}
}
可以结合!!!
package com.example.springbootwebre4sp.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController
{
//原始方式
@RequestMapping("/path/{id}")
public String pathParam(@PathVariable Integer id, @RequestParam String name,Integer age)
{
System.out.println(id+name+age);
return "OK";
}
}
@ResponseBody
为什么我们之前有返回的OK显示再客户端呢?是因为:
@RestController = @Controller + @ResponseBody
;package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.pojo.Address;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ResponseController {
@RequestMapping("/hello")
public String hello(){
System.out.println("Hello World~");
return "Hello World~";
}
@RequestMapping("/getAddress")
public Address getAddress(){
Address addr = new Address();
addr.setProvince("辽宁");
addr.setCity("铁岭");
return addr;
}
@RequestMapping("/listAddr")
public List<Address> listAddr(){
List<Address> list = new ArrayList<>();
Address addr = new Address();
addr.setProvince("广东") ;
addr.setCity("深圳");
Address addr2 = new Address() ;
addr2.setProvince ("陕西") ;
addr2.setCity("西安") ;
list.add (addr) ;
list.add (addr2) ;
return list;
}
}
但是!这个不具有通用性,我写一个结构, 前端就需要一个新的代码接受,太麻烦!不便管理!
Result
package com.example.springbootwebre4sp.pojo;
public class Result {
private Integer code ;//1 成功,0失败
private String msg; //提示信息
private Object data; // 数据date
public Result() {
}
public Result(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
/**
* 获取
* @return code
*/
public Integer getCode() {
return code;
}
/**
* 设置
* @param code
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* 获取
* @return msg
*/
public String getMsg() {
return msg;
}
/**
* 设置
* @param msg
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* 获取
* @return data
*/
public Object getData() {
return data;
}
/**
* 设置
* @param data
*/
public void setData(Object data) {
this.data = data;
}
public String toString() {
return "Result{code = " + code + ", msg = " + msg + ", data = " + data + "}";
}
public static Result success (Object data) {
return new Result( 1,"sucess", data) ;
}
public static Result ssucces() {
return new Result(1,"sucess",null) ;
}
public static Result error (String msg) {
return new Result( 0,msg,null) ;
}
}
package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.pojo.Address;
import com.example.springbootwebre4sp.pojo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ResponseController {
@RequestMapping("/hello")
public Result hello(){
System.out.println("Hello World~");
//return new Result(1,"success","Hello World~");
return Result.success("Hello World~");
}
@RequestMapping("/getAddress")
public Result getAddress(){
Address addr = new Address();
addr.setProvince("辽宁");
addr.setCity("铁岭");
return Result.success(addr);
}
@RequestMapping("/listAddr")
public Result listAddr(){
List<Address> list = new ArrayList<>();
Address addr = new Address();
addr.setProvince("广东") ;
addr.setCity("深圳");
Address addr2 = new Address() ;
addr2.setProvince ("陕西") ;
addr2.setCity("西安") ;
list.add (addr) ;
list.add (addr2) ;
return Result.success(list);
}
}
<dependency>
<groupId>org.dom4jgroupId>
<artifactId>dom4jartifactId>
<version>2.1.3version>
dependency>
2. 引入资料中提供的解析XML的工具类XMLParserUtils、对应的实体类Emp、XML文件emp.xml
XmlParserUtils
package com.example.springbootwebre4sp.utils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class XmlParserUtils {
public static <T> List<T> parse(String file , Class<T> targetClass) {
ArrayList<T> list = new ArrayList<T>(); //封装解析出来的数据
try {
//1.获取一个解析器对象
SAXReader saxReader = new SAXReader();
//2.利用解析器把xml文件加载到内存中,并返回一个文档对象
Document document = saxReader.read(new File(file));
//3.获取到根标签
Element rootElement = document.getRootElement();
//4.通过根标签来获取 user 标签
List<Element> elements = rootElement.elements("emp");
//5.遍历集合,得到每一个 user 标签
for (Element element : elements) {
//获取 name 属性
String name = element.element("name").getText();
//获取 age 属性
String age = element.element("age").getText();
//获取 image 属性
String image = element.element("image").getText();
//获取 gender 属性
String gender = element.element("gender").getText();
//获取 job 属性
String job = element.element("job").getText();
//组装数据
Constructor<T> constructor = targetClass.getDeclaredConstructor(String.class, Integer.class, String.class, String.class, String.class);
constructor.setAccessible(true);
T object = constructor.newInstance(name, Integer.parseInt(age), image, gender, job);
list.add(object);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
Emp
package com.example.springbootwebre4sp.pojo;
public class Emp {
private String name;
private Integer age;
private String image;
private String gender;
private String job;
public Emp() {
}
public Emp(String name, Integer age, String image, String gender, String job) {
this.name = name;
this.age = age;
this.image = image;
this.gender = gender;
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", age=" + age +
", image='" + image + '\'' +
", gender='" + gender + '\'' +
", job='" + job + '\'' +
'}';
}
}
emp.xml
<emps>
<emp>
<name>金毛狮王name>
<age>55age>
<image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/1.jpgimage>
<gender>1gender>
<job>1job>
emp>
<emp>
<name>白眉鹰王name>
<age>65age>
<image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/2.jpgimage>
<gender>1gender>
<job>1job>
emp>
<emp>
<name>青翼蝠王name>
<age>45age>
<image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/3.jpgimage>
<gender>1gender>
<job>2job>
emp>
<emp>
<name>紫衫龙王name>
<age>38age>
<image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/4.jpgimage>
<gender>2gender>
<job>3job>
emp>
emps>
添加前端界面——相关资料源码笔记等关注微信公众号:黑马程序员,回复关键词:领取资源02
EmpController
package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.pojo.Emp;
import com.example.springbootwebre4sp.pojo.Result;
import com.example.springbootwebre4sp.utils.XmlParserUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmpController {
@RequestMapping("/listEmp")
public Result list(){
//1. 加载并解析emp.xml
String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
System.out.println(file);
List<Emp> empList = XmlParserUtils.parse(file, Emp.class);
//2. 对数据进行转换处理 - gender, job
empList.stream().forEach(emp -> {
//处理 gender 1: 男, 2: 女
String gender = emp.getGender();
if("1".equals(gender)){
emp.setGender("男");
}else if("2".equals(gender)){
emp.setGender("女");
}
//处理job - 1: 讲师, 2: 班主任 , 3: 就业指导
String job = emp.getJob();
if("1".equals(job)){
emp.setJob("讲师");
}else if("2".equals(job)){
emp.setJob("班主任");
}else if("3".equals(job)){
emp.setJob("就业指导");
}
});
//3. 响应数据
return Result.success(empList);
}
}
我们发现我们上面编写的程序有点问题,我们所有的代码都写在了Controller中,这个逻辑简单,当时当代码复杂时就非常难以维护。——分层解耦来了!!!!
单一原则!!!
修改代码!下面是目录:
EmpController
package com.example.springbootwebre4sp.controller;
import com.example.springbootwebre4sp.dao.impl.EmpDaoA;
import com.example.springbootwebre4sp.pojo.Emp;
import com.example.springbootwebre4sp.pojo.Result;
import com.example.springbootwebre4sp.service.EmpService;
import com.example.springbootwebre4sp.service.impl.EmpServiceA;
import com.example.springbootwebre4sp.utils.XmlParserUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmpController {
private EmpService empService = new EmpServiceA();
@RequestMapping("/listEmp")
public Result list(){
List<Emp> empList = empService.listEmp();
//3. 响应数据
return Result.success(empList);
}
}
package com.example.springbootwebre4sp.dao.impl;
import com.example.springbootwebre4sp.dao.EmpDao;
import com.example.springbootwebre4sp.pojo.Emp;
import com.example.springbootwebre4sp.utils.XmlParserUtils;
import java.util.List;
public class EmpDaoA implements EmpDao {
@Override
public List<Emp> listEmp() {
String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
System.out.println(file);
List<Emp> empList = XmlParserUtils.parse(file, Emp.class);
return empList;
}
}
package com.example.springbootwebre4sp.dao;
import com.example.springbootwebre4sp.pojo.Emp;
import java.util.List;
public interface EmpDao {
//获取列表数据
public List<Emp> listEmp();
}
package com.example.springbootwebre4sp.service.impl;
import com.example.springbootwebre4sp.dao.EmpDao;
import com.example.springbootwebre4sp.dao.impl.EmpDaoA;
import com.example.springbootwebre4sp.pojo.Emp;
import com.example.springbootwebre4sp.service.EmpService;
import java.util.List;
public class EmpServiceA implements EmpService {
private EmpDao empDao = new EmpDaoA();
@Override
public List<Emp> listEmp() {
List<Emp> empList = empDao.listEmp();
empList.stream().forEach(emp -> {
//处理 gender 1: 男, 2: 女
String gender = emp.getGender();
if("1".equals(gender)){
emp.setGender("男");
}else if("2".equals(gender)){
emp.setGender("女");
}
//处理job - 1: 讲师, 2: 班主任 , 3: 就业指导
String job = emp.getJob();
if("1".equals(job)){
emp.setJob("讲师");
}else if("2".equals(job)){
emp.setJob("班主任");
}else if("3".equals(job)){
emp.setJob("就业指导");
}
});
return empList;
}
}
package com.example.springbootwebre4sp.service;
import com.example.springbootwebre4sp.pojo.Emp;
import java.util.List;
public interface EmpService {
//获取员工列表数据
public List<Emp> listEmp();
}
控制反转:@Component //将当前类交给IOC容器管理,成为IOC容器中的bean
依赖注入:@Autowired //运行时,IOC容器会提供该类型的bean对象,并赋值给该变量
Bean的声明
要把某个对象交给IOC容器管理,需要在对应的类上加上如下注解之一:
注解 | 说明 | 位置 |
---|---|---|
@Component | 声明bean的基础注解 | 不属于以下三类时,用此注解 |
@Controller | @Component的衍生注解 | 标注在控制器类上 |
@Service | @Component的衍生注解 | 标注在业务类上 |
@Repository | @Component的衍生注解 | 标注在数据访问类上(由于与mybatis整合,用的少) |
推荐:下面的三类分别标注Controller,Service,DAO三层的bean对象
工具类常常想要利用容器,我用Component
注意事项
Bean组件扫描
@Autowired——依赖注入
请大家关注我下面两个博客笔记,这也是黑马视频出品的,
黑马程序员 MySQL数据库入门到精通——基础篇(1)
黑马程序员 MySQL数据库入门到精通——基础篇(2)