JavaWeb_Web后端_请求响应

JavaWeb_Web后端_请求响应

  • 概述
  • 请求
    • 简单参数
      • 原始方式
      • SpringBoot方式
      • RequestParam注解
    • 实体参数
    • 数组集合参数
    • 日期参数
    • JSON参数
    • 路径参数
  • 响应
    • ResponseBody注解
    • 统一响应结果
      • Result.java
      • ResponseController
    • 案例
  • 来源

概述

前端控制器DispatcherServlet:

  • HttpServletRequest: 获取请求数据
  • HttpServletResponse: 设置响应数据

BS架构: Browser/Server, 浏览器/服务器架构模式. 客户端只需要浏览器, 应用程序的逻辑和数据都存储在服务端.(维护方便, 体验一般)
CS架构: Client/Server, 客户端/服务器架构模式.(开发和维护麻烦, 体验不错)

请求

简单参数

原始方式

// 原始方式
@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 + ":" + age);
    return "OK";
}

SpringBoot方式

  • 参数名与形参变量名相同, 定义形参即可接收参数
// SpringBoot方式
@RequestMapping("/simpleParam")
public String simpleParam(String name, Integer age)
{
    System.out.println(name + ":" + age);
    return "OK";
}
  • 参数名与形参变量名不相同
// SpringBoot方式-参数名与形参变量名不相同
// 没有对应的参数为null
@RequestMapping("/simpleParam")
public String simpleParam(String username, Integer age)
{
    System.out.println(username + ":" + age);
    return "OK";
}

RequestParam注解

  1. 方法形参名称与请求参数名称不匹配, 可以通过该注解完成映射
  2. 该注解的required属性默认为true, 表示请求参数必须传递
// RequestParam注解
@RequestMapping("/simpleParam")
public String simpleParam(@RequestParam(value = "name") String username, Integer age)
{
    System.out.println(username + ":" + age);
    return "OK";
}

实体参数

  • 简单实体对象: 请求参数名与形参对象属性名相同, 定义POJO接收即可.
public class User {
    private String name;
    private Integer age;
}


@RequestMapping("/simplePojo")
public String simplePojo(User user)
{
    System.out.println(user);
    return "ok";
}
  • 复杂实体对象: 请求参数名与形参对象属性名相同,按照对象层次结构关系即可接收嵌套POJO属性参数
public class Address {
    private String province;
    private String city;
}

public class User{
    private String name;
    private Integer age;
    private Address address;
}

@RequestMapping("/complexPojo")
public String complexPojo(User user)
{
    // localhost:8080/complexPojo?name=Tom&age=10&address.province=beijing&address.city=beijing

    System.out.println(user);
    return "ok";
}

数组集合参数

  • 数组参数: 请求参数名与形参数组名称相同且请求参数为多个, 定义数组类型形参即可接收参数.
@RequestMapping("/arrayParam")
public String complexPojo(String[] hobby)
{
    // localhost:8080/arrayParam?hobby=sing&hobby=jump&hobby=rap
    System.out.println(Arrays.toString(hobby));
    return "ok";
}
  • 集合参数: 请求参数名与形参集合名称相同且请求参数为多个, @RequestParam绑定参数关系
@RequestMapping("/listParam")
public String listParam(@RequestParam List<String> hobby)
{
    // localhost:8080/listParam?hobby=sing&hobby=jump&hobby=rap
    System.out.println(hobby);
    return "ok";
}

日期参数

@RequestMapping("/dateParam")
public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime)
{
    // localhost:8080/dateParam?updateTime=2022-12-12 10:00:05
    System.out.println(updateTime);
    return "ok";
}

JSON参数

JSON参数: JSON数据键名与形参对象属性名相同,定义POJO类型形参即可接收参数,需要使用@RequestBody标识.

@RequestMapping("/jsonParam")
public String dateParam(@RequestBody User user)
{
    /* Body->raw->JSON
    {
        "name":"Tom",
        "age":10,
        "address":{
            "province":"beijing",
            "city":"beijing"
        }
    }
    */
    System.out.println(user);
    return "ok";
}

路径参数

路径参数: 通过请求URL直接传递参数,使用{…}来标识该路径参数,需要使用 @PathVariable 获取路径参数.

@RequestMapping("/path/{id}/{name}")
public String pathParam(@PathVariable Integer id, @PathVariable String name)
{
    // localhost:8080/path/10/Tom
    System.out.println(id+":"+name);
    return "OK";
}

响应

ResponseBody注解

  1. 类型: 方法注解, 类注解
  2. 位置: Controller方法上/类上
  3. 作用: 将方法返回值直接响应, 如果返回值类型是实体对象/集合, 将会转换成JSON格式响应
  4. 说明: @RestController = @Controller + @ResponseBody
@RestController
public class ResponseController {

    @RequestMapping("/hello")
    public String hello()
    {
        System.out.println("Hello World!");
        return "Hello World!";
    }

    @RequestMapping("/getAddr")
    public Address getAddr()
    {
        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.java

/**
 * 统一响应结果封装类
 */
public class Result {
    private Integer code ;//1 成功 , 0 失败
    private String msg; //提示信息
    private Object data; //数据 data

    public Result() {
    }
    public Result(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

    public static Result success(Object data){
        return new Result(1, "success", data);
    }
    public static Result success(){
        return new Result(1, "success", null);
    }
    public static Result error(String msg){
        return new Result(0, msg, null);
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

ResponseController

@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("/getAddr")
    public Result getAddr()
    {
        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);
    }
}

案例

  1. 在pom.xml文件中引入dom4j的依赖, 用于解析xml文件

<dependency>
    <groupId>org.dom4jgroupId>
    <artifactId>dom4jartifactId>
    <version>2.1.3version>
dependency>
  1. 引入资料中提供的解析XML的工具类XMLParserUtils, 对应的实体类Emp, XML文件emp.xml.

XMLParserUtils.java:

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.java:

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>
  1. 引入资料中提供的静态页面文件, 放在resources下的static目录下
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工信息title>
head>

<link rel="stylesheet" href="element-ui/index.css">
<script src="./js/vue.js">script>
<script src="./element-ui/index.js">script>
<script src="./js/axios-0.18.0.js">script>

<body>
    <h1 align="center">员工信息列表展示h1>
    <div id="app">
        <el-table :data="tableData" style="width: 100%"  stripe border >
            <el-table-column prop="name" label="姓名" align="center" min-width="20%">el-table-column>
            <el-table-column prop="age" label="年龄" align="center" min-width="20%">el-table-column>
            <el-table-column label="图像" align="center"  min-width="20%">
                <template slot-scope="scope">
                    <el-image :src="scope.row.image" style="width: 80px; height: 50px;">el-image>
                template>
            el-table-column>
            <el-table-column prop="gender" label="性别" align="center"  min-width="20%">el-table-column>
            <el-table-column prop="job" label="职位" align="center"  min-width="20%">el-table-column>
        el-table>
    div>
body>

<style>
    .el-table .warning-row {
        background: oldlace;
    }
    .el-table .success-row {
        background: #f0f9eb;
    }
style>

<script>
    new Vue({
        el: "#app",
        data() {
            return {
                tableData: []
            }
        },
        mounted(){
            axios.get('/listEmp').then(res=>{
                if(res.data.code){
                    this.tableData = res.data.data;
                }
            });
        },
        methods: {
        }
    });
script>
html>
  1. 编写Controller程序, 处理请求, 响应数据.
@RestController
public class EmpController {

    @RequestMapping("/listEmp")
    public Result list()
    {
        // 1. 加载emp.xml并解析emp.xml中的数据
        String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
        List<Emp> emplist = XmlParserUtils.parse(file, Emp.class);
        // 2. 对员工信息中的gender, job字段进行处理
        emplist.stream().forEach(emp -> {
            String gender = emp.getGender();
            if("1".equals(gender)){
                emp.setGender("男");
            }else if("2".equals(gender)){
                emp.setGender("女");
            }
            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);
    }

}

来源

黑马程序员. JavaWeb开发教程

你可能感兴趣的:(JavaWeb开发,#,JavaWeb开发_Web后端,java,spring,boot,log4j,后端,spring)