SpringBoot2学习笔记(四)Web技术

一.验证框架

SpringBoot支持JSR-303,Bean等验证框架

JSR-303

JSR-303是Java的标准验证框架,已有实现Hibernate validator.

JSR-303验证类型

空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  

长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) Validates that the annotated string is between min and max included.

日期检查
@Past       验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min            验证 Number 和 String 对象是否大等于指定的值  
@Max            验证 Number 和 String 对象是否小等于指定的值  
@DecimalMax     被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin     被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits         验证 Number 和 String 的构成是否合法  
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。

@Range(min=, max=) 检查数字是否介于minmax之间.

@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;

@Valid      递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber   信用卡验证
@Email      验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)

引自:https://www.cnblogs.com/yangzhilong/p/3724967.html

在MVC中使用JSR-303校验

可以使用@Validated注解来触发一次校验

例子:
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="/login">
        id:<input type="text" name="id"><br>
        name:<input type="text" name="name"><br>
        age:<input type="text" name="age"><br>
        Email:<input type="text" name="Email"><br>
        phone:<input type="text" name="phone"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

Persion类

public class Persion {

    @NotNull(message = "id不能为空")
    private Integer id;


    @NotBlank(message = "姓名不能为空")
    private String name;

    @Min(value = 1,message = "年龄不能小于1岁")
    private Integer age;

    @Email
    private String Email;

    @Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$",message = "手机号码格式错误")
    private String phone;

    // 省略getter setter toString
}

Controller

@Controller
public class PersionController {

    @RequestMapping("/login")
    @ResponseBody
    public String login(@Validated Persion persion){
        System.out.println(persion);
        return "success";
    }
}

结果:

测试1,输入错误信息
这里写图片描述
结果1

Field error in object 'persion' on field 'id': rejected value [12313456131]; codes [typeMismatch.persion.id,typeMismatch.id,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [persion.id,id]; arguments []; default message [id]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'id'; nested exception is java.lang.NumberFormatException: For input string: "12313456131"]
Field error in object 'persion' on field 'name': rejected value []; codes [NotBlank.persion.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [persion.name,name]; arguments []; default message [name]]; default message [姓名不能为空]
Field error in object 'persion' on field 'phone': rejected value [1]; codes [Pattern.persion.phone,Pattern.phone,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [persion.phone,phone]; arguments []; default message [phone],[Ljavax.validation.constraints.Pattern$Flag;@31780db2,org.springframework.validation.beanvalidation.SpringValidatorAdapter$ResolvableAttribute@402f9c39]; default message [手机号码格式错误]
Field error in object 'persion' on field 'age': rejected value [0]; codes [Min.persion.age,Min.age,Min.java.lang.Integer,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [persion.age,age]; arguments []; default message [age],1]; default message [年龄不能小于1岁]
Field error in object 'persion' on field 'Email': rejected value [1]; codes [Email.persion.Email,Email.Email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [persion.Email,Email]; arguments []; default message [Email],[Ljavax.validation.constraints.Pattern$Flag;@7204f41e,org.springframework.validation.beanvalidation.SpringValidatorAdapter$ResolvableAttribute@7af2bed5]; default message [不是一个合法的电子邮件地址]

测试2,输入一个正确信息
这里写图片描述
结果2

Persion{id=123, name='lgggx', age=1, Email='[email protected]', phone='18750712756'}

二.获取参数

@PathVariable

@PathVariable 用于从请求URL中获取参数并映射到方法参数
例子:

    @RequestMapping("/get/{name}/{age}/{id}")
    @ResponseBody
    public String getParam(@PathVariable("name") String name, @PathVariable("age") Integer age, @PathVariable("id") Integer id){
        System.out.println("name:" + name);
        System.out.println("age:" + age);
        System.out.println("id:" + id);
        return "success";
    }

访问:http://localhost:8080/get/zhangsan/18/1001
结果:

name:zhangsan
age:18
id:1001

三.文件上传

MultipartFile

通过MultipartFile 来处理文件上传

    @RequestMapping("/uploads")
    @ResponseBody
    public String fileUpload(String name, MultipartFile file) throws IOException {

        //如果文件不为空
        if (file != null && !file.isEmpty()){
            //获取文件名
            String fileName = file.getName();
            //获取文件大小
            long size = file.getSize();
            //返回系统原始文件名
            String originalFilename = file.getOriginalFilename();
            //返回文件类型
            String contentType = file.getContentType();
            //获取文件输入流
            InputStream inputStream = file.getInputStream();

            //拷贝到本地方式1
            //使用文件流拷贝文件
            //FileOutputStream ops = new FileOutputStream(new File("/" + originalFilename));
            //byte[] bytes = new byte[1024];
            //int len = 0;
            //
            //while((len = inputStream.read(bytes)) > 0){
            //     ops.write(bytes,0,len);
            //}
            //inputStream.close();
            //ops.close();

            //拷贝到本地方式2
            //保存上传文件到目标文件系统
            file.transferTo(new File("E:\\" + originalFilename));
        }
        return "upload success";
    }

form表单提交方式必须是post,且设置enctype=”multipart/form-data”

    <form method="post" action="/uploads" enctype="multipart/form-data">
        name:<input type="text" name="name"><br>
        file:<input type="file" name="file"><br>
        <input type="submit" value="提交"/>
    </form>

四.Json的使用

@RequestBody 与 @ResponseBody

使用@RequestBody来接收Json,使用@ResponseBody来返回Json

 @RequestMapping("/savejson")
 @ResponseBody
 public String getJson(@RequestBody User user){
     return user;
 }

五.JavaWeb三大组件(Servlet,Filter,Listener)

详情:https://blog.csdn.net/l1336037686/article/details/81050194

六.错误处理

定制错误页面

SpringBoot定制处理页面只需要将在类路径下静态资源文件夹下新建一个error文件夹,然后将相应错误状态码所对应的错误页面保存在里面即可
这里写图片描述

4xx.html:代表出现4xx错误状态的情况下就会默认跳转到4xx.html错误处理页面
5xx.html:代表出现5xx错误状态的情况下就会默认跳转到5xx.html错误处理页面
404.html:以准确的状态吗命名错误页面,则此页面只会处理相应的错误状态,对于其他的4xx错误不会进行处理,例如 404.html只会处理404错误码
错误页面匹配的优先级以命名的精确度从高到低,命名越准确,优先级越高

定制错误响应Json数据

七.国际化

使用thymeleaf作为视图处理
可以通过在类路径下编写国际化处理文件实现
这里写图片描述

en_US结尾 : 表示英文
zh_CN结尾 : 表示中文

例子:

i18n.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="#{word_1}">Hello World</p>
    <p th:text="#{word_2}">I like Java</p>
</body>
</html>

国际化处理文件

web.properties

word_1=Hello World
word_2=I like Java

web_en_US.properties

word_1=Hello World
word_2=I like Java

web_zh_CN.properties

word_1=你好 世界
word_2=我喜欢Java

视图跳转,使用配置类处理

@Configuration
public class WebMvcConf {

    @Bean
    public WebMvcConfigurer myWebMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/index").setViewName("index");
                registry.addViewController("/i18n").setViewName("i18n");
            }
        };

    }
}

配置国际化资源文件路径application.properties

# 配置国际化资源路径:路径/名字
spring.messages.basename=i18n/word

测试结果:

设置浏览器语言环境为中文
这里写图片描述
设置浏览器语言环境为英文
这里写图片描述

猜你喜欢

转载自blog.csdn.net/l1336037686/article/details/81119792
今日推荐