spring-boot小记

251 阅读3分钟

员工管理系统-狂神说

D:\MasterLearning\JavaWeb\employee_management

记录

(1)视图解析器的配置

视图解析有两种方式,forward和redirect,这二者寻找视图解析器的方式是不同的,我们可以通过重写WebMvcConfiguer来完成自定义.

package com.luo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

/**
 * @author LunarYouI
 * @create 2021-03-22 16:01
 */

//如果你想自定义一些定制的功能,只要写这个组件,然后将它交给springboot,springboot就会自动装配
//扩展SpringMVC   dispatchservlet

@Configuration  //使当前这个类变成配置类
//一但表注了@EnableWebMvc,那么MVC将被全面接管
public class MyMvcConfig implements WebMvcConfigurer {
    //public interface ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器

    /*第二步:将自己写的视图解析器注册到Bean里面,它就会自动帮我们装配上*/
    @Bean
    public ViewResolver MyViewResolver() {
        return new MyViewResolver();
    }

    /*第一步:自定义了一个自己的视图解析器MyViewResolver*/
    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

(2)前端传递数据、传参

注意跨域请求问题。

什么是跨域请求?跨域请求主要体现在跨域两个字上,当发起请求的客户端和接收请求的服务端他们的【协议、域名、端口号】有任意一项不一致的情况都属于跨域请求,拿刚刚访问的地址举例,VUE页面运行在9000端口上,后台接口运行在8080端口上,端口号没有对上所以该请求为跨域请求。

配置过滤器

@Component
public class CorsFilter implements Filter {

    @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    // 将response响应转换为基于HTTP协议的响应对象
    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    // 在允许请求的地址列表中添加VUE的地址
    resp.addHeader("Access-Control-Allow-Origin", "http://localhost:9000");
    // 这个方法是必须调用的,不做解释
    filterChain.doFilter(servletRequest, resp);
}

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }
    @Override
    public void destroy() { }

}

传参-路径占位参数

后端接口

@RestController
public class IndexController {
    // 路径中包含user和blogId两个占位参数
    @GetMapping("/{user}/p/{blogId}.html")
    public Map<String, Object> index(@PathVariable String user, @PathVariable Long blogId) {
        // 将接收的参数返回给前端
        HashMap<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("blogId", blogId);

        return result;
    }
}

前端请求

request1() {
    this.axios.get("http://localhost:8080/hanzhe/p/11223344.html", this.config).then(res => {
        console.log("res", res);
    });
}

传参-路径传参

什么是路径传参?发起一个请求 http://localhost:8080/index?a=1&b=2 ,在路径 ? 后面的都属于路径传参,路径传参就是将参数以明文方式拼接在请求地址后面;

后端接口

@RestController
public class IndexController {
    @GetMapping("/index")
    public Map<String, Object> index(String user, String name) {
        // 将接收的参数返回给前端
        HashMap<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("name", name);

        return result;
    }
}

前端路径

// 正常拼接
request1() {
    this.axios.get("http://localhost:8080/index?user=zhang&name=hanzhe").then(res => {
        console.log("res", res);
    });
},
// 使用config中的params属性进行路径传参
request2() {
    let config = {
        params: {
            user: "zhang",
            name: "hanzhe"
        }
    }
    this.axios.get("http://localhost:8080/index", config).then(res => {
        console.log("res", res);
    });
}

传参-表单类型参数

后台接口的编写

@RestController
public class IndexController {
    @PostMapping("/index")
    public Map<String, Object> index(String username, String password) {
        // 将接收的参数返回给前端
        HashMap<String, Object> result = new HashMap<>();
        result.put("username", username);
        result.put("password", password);

        return result;
    }
}

VUE代码

request1() {
    // 构建表单对象,向表单中追加参数
    let data = new FormData();
    data.append("username", "123");
    data.append("password", "456");
    // 发起请求
    this.axios.post("http://localhost:8080/index", data).then(res => {
        console.log("res", res);
    });
},

传参-请求体参数

和表单数据类似

后台接口的编写

@RestController
public class IndexController {
    @PostMapping("/index")
    public Map<String, Object> index(@RequestBody UserEntity entity) {
        // 将接收的参数返回给前端
        HashMap<String, Object> result = new HashMap<>();
        result.put("username", entity.getUsername());
        result.put("password", entity.getPassword());

        return result;
    }
}

VUE代码

axios如果发起的为POST类型请求,默认会将参数放在请求体中,这里直接写即可

request1() {
    // 创建date对象存储参数
    let data = {
        username: "哈哈哈哈",
        password: "嘿嘿嘿嘿"
    }
    // 发起请求
    this.axios.post("http://localhost:8080/index", data).then(res => {
        console.log("res", res);
    });
},

thymeleaf传参

方式一:路径占位传参

方式二:路径传参,http://localhost:8080/index?a=1&b=2 ,在路径 ? 后面的都属于路径传参;

@{www.gh.com/}+{emp.getID()}
前端地址栏显示
http://www.gh.com?a=1&b=2

(3)日期格式问题

spring中的默认时间格式是 1999/02/08,前后端交互时要保证格式相同,不然会出现

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates//emps/list.html]")
Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "#dates.format(emp.getBirth(),'dd/MMM/yyy')" (template: "/emps/list" - line 79, col 32)

2022-04-11 16:25:21.377 ERROR 39812 --- [nio-8080-exec-9] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/gh/emps] as the response has already been committed. As a result, the response may have the wrong status code.

很明显日期问题,要将所有日期的格式改成一致的,

image-20220411162315611.png