SpringBoot(一)

Hello World

Web 服务器

1.WEB 服务器:

  • 对HTTP协议操作进行封装,简化web程序开发
  • 部署web项目,对外提供网上信息浏览服务

2.Tomcat

  • 一个轻量级的web 服务器,支持servlet、jsp 等少量javaEE规范
  • 也被称为web容器,servlet容器

下载目录介绍:

控制台中文乱码:

解决:

java.util.logging.ConsoleHandler.encoding = GBK

配置tomcat端口号:

springboot 内嵌了Tomcat:

请求

简单参数

原始方式了解即可:

服务端:

package com.chuangzhou.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.StringReader;

@RestController
public class RequestController {

    @RequestMapping("/simpleParame")
    public String simpleParame(HttpServletRequest request){
        String name = request.getParameter("name");
        String age = request.getParameter("age");

        int intAge = Integer.parseInt(age);
        System.out.println("name=>" + name + ",age=>" + intAge);

        return "OK";
    }
}

调用接口:

    //基于springboot 方式
    //避免了类型转换,会自动映射
    @RequestMapping("/simpleParame")
    public String simpleParame(String name, Integer age){
        System.out.println("name=>" + name + ",age=>" + age);

        return "OK";
    }

如果请求参数和方法的参数名不一致的时候服务端映射参数失败,但是请求不会报错:

此时可以借助 @RequestParam 注解完成映射

    @RequestMapping("/simpleParame")
    public String simpleParame(@RequestParam(name="name") String usernmae, Integer age){
        System.out.println("usernmae=>" + usernmae + ",age=>" + age);
        return "OK";
    }

漏传参数:

简单实体参数

实体的属性名称要和http请求传入的参数名保持一致

复杂参数传参

请求路径:
localhost:8080/complexPOJO?name=lisi&age=18&address.province=guangdong&address.city=shenzhen

    //复杂参数传参
    @RequestMapping("/complexPOJO")
    public String complexPOJO(User user){
        System.out.println("usernmae=>" + user.getName() + ",age=>" + user.getAge() + ",address:" + user.getAddress());
        return "OK";
    }

user 中内嵌address 实体:

数组集合参数

数组参数:

    //数组参数传参
    @RequestMapping("/arrParam")
    public String arrParam(String[] hobby){
        System.out.println(Arrays.toString(hobby));
        return "OK";
    }

集合参数:

接口请求与数据参数一致

    //集合参数传参
    @RequestMapping("/listParam")
    public String listParam(@RequestParam List<String> hobby){
        System.out.println(hobby);
        return "OK";
    }

日期参数

请求:

处理:

    //日期参数接收
    @RequestMapping("/dateParam")
    public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date){
        System.out.println(date);
        return "OK";
    }

如果日期的格式不对会报错

json参数

请求:

处理:

    //日期参数接收
    @RequestMapping("/jsonParam")
    public String jsonParam(@RequestBody User user){
        System.out.println(user);
        return "OK";
    }

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

路径参数

单路径参数请求:

处理:

    //路径参数接收
    @RequestMapping("/pathParam/{id}")
    public String pathParam(@PathVariable Integer id){
        System.out.println(id);
        return "OK";
    }

多路径参数:
请求:

处理:

    //路径参数接收
    @RequestMapping("/pathParam/{id}/{name}")
    public String pathParam2(@PathVariable Integer id, @PathVariable String name){
        System.out.println(id);
        System.out.println(name);
        return "OK";
    }

总结:

响应

@ResponseBody

  • 类型:方法注解,类注解
  • 位置:Controller 方法上/类上
  • 作用:将方法返回值直接响应,如果返回类型是 实体对象/集合,将会转换为JSON格式响应
  • 说明:@RestController 等价于 @ResponseBody + @Controller

响应一个实体:

    @RequestMapping("/getAddr")
    public Address getAddr(){
        Address a = new Address("湖北","武汉");
        return a;
    }
}

响应一个list:

    @RequestMapping("/getAddrList")
    public List<Address> getAddrList(){
        List<Address> l = new ArrayList<>();
        l.add(new Address("湖北","武汉"));
        l.add(new Address("湖南","长沙"));
        return l;
    }

统一响应结果,方便前端解析返回数据:

定义返回结果POJO:

package com.chuangzhou.controller.pojo;

public class Result {
    private Integer code;
    private String message;
    private Object data;


    public Result() {
    }

    public Result(Integer code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }


    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }


    public String getMessage() {
        return message;
    }


    public void setMessage(String message) {
        this.message = message;
    }


    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(0,"success",null);
    }
}

修改controller方法:

    @RequestMapping("/getAddr")
    public Result getAddr(){
        Address a = new Address("湖北","武汉");
        return Result.success(a);
    }

    @RequestMapping("/getAddrList")
    public Result getAddrList(){
        List<Address> l = new ArrayList<>();
        l.add(new Address("湖北","武汉"));
        l.add(new Address("湖南","长沙"));
        return Result.success(l);
    }

响应结果:

请求响应案例

需求:读取xml文件中的员工数据,返回统一响应结果,在页面渲染

<?xml version="1.0" encoding="UTF-8" ?>
<emps>
    <emp>
        <name>金毛狮王</name>
        <age>55</age>
        <image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/1.jpg</image>
        <!-- 1: 男, 2: 女 -->
        <gender>1</gender>
        <!-- 1: 讲师, 2: 班主任 , 3: 就业指导 -->
        <job>1</job>
    </emp>

    <emp>
        <name>白眉鹰王</name>
        <age>65</age>
        <image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/2.jpg</image>
        <gender>1</gender>
        <job>1</job>
    </emp>

    <emp>
        <name>青翼蝠王</name>
        <age>45</age>
        <image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/3.jpg</image>
        <gender>1</gender>
        <job>2</job>
    </emp>

    <emp>
        <name>紫衫龙王</name>
        <age>38</age>
        <image>https://web-framework.oss-cn-hangzhou.aliyuncs.com/web/4.jpg</image>
        <gender>2</gender>
        <job>3</job>
    </emp>
</emps>

1.引入dom4j的依赖,用于解析XML文件
2.引入XML工具类XMLParserUtils、对应的实体类Emp、xml文件emp.xml

Springboot项目的静态资源(html、css,js等前端资源)默认存放目录为:classpath:/static、classpath:/public、class:/resources

classpath 等价于 src/man/resources

后端实现接口:

    @RequestMapping("/listEmp")
    public Result listEmp(){
        String filePath = this.getClass().getClassLoader().getResource("emp.xml").getPath();
        List<Emp> emps = XmlParserUtils.parse(filePath, Emp.class);

        emps.stream().forEach(emp -> {
            String gender = emp.getGender();
            if ("1".equals(gender)){
                emp.setGender("男");
            }else if("2".equals(gender)){
                emp.setGender("女");
            }
            //         <!-- 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 Result.success(emps);
    }

前端页面:
emp.html

<!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>

最终效果,访问:http://localhost:8080/emp.html

posted @ 2023-08-04 22:11  chuangzhou  阅读(25)  评论(0编辑  收藏  举报