欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一起学习SSM框架之SpringMVC(三)

程序员文章站 2022-04-14 12:05:36
SpringMVC静态资源1.解决方案12.解决方案23.解决方案3静态资源静态资源:HTML,js文件,css文件,图片文件静态文件没有url-pattern,所以默认是访问不到的,之所以可以访问,是因为tomcat中有一个全局的servlet:org.apache.catalina.servlets.DefaultServlet,它的url-pattern是“/”,是全局默认的servlet,所以每个项目中不能匹配到静态资源请求的时候,用这个来处理1.解决方案12.解决方案23.解决方案3...

静态资源

静态资源:HTML,js文件,css文件,图片文件
静态文件没有url-pattern,所以默认是访问不到的,之所以可以访问,是因为tomcat中有一个全局的servlet:org.apache.catalina.servlets.DefaultServlet,它的url-pattern是“/”,是全局默认的servlet,所以每个项目中不能匹配到静态资源请求的时候,用这个来处理

1.解决方案1

DispathcerServlet采用其他的url-pattern
此时,所有的访问handler的路径都要以action结尾

  <servlet>
        <servlet-name>ozl_mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <!--可选配置,不写就是懒汉式加载,写了就是饿汉式加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ozl_mvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

2.解决方案2

DispathcerServlet的url-pattern依然采用"/",但要追加配置

   <!-- 额外增加一个handler,且requestMapping:"/**"可以匹配所有的请求,
    但是优先级最低,所以如果其他所有的handler都匹配不上,请求会转向"/**",
    恰好这个handler是处理静态资源的处理方式:将请求转会到tomcat中default的Servlet

    requestMapping:"/**"    /xx/xx或者/x就是所有路径
    -->
    <mvc:default-servlet-handler/>

3.解决方案3

	 <!--
        1.mapping是访问路径,location是存放资源位置
        2.将/html/**中/**匹配到的内容,拼接到/page/
     -->
    <mvc:resources mapping="/html/**" location="/page/"/>

Json处理

SpringMVC默认的Json处理方案选择是Jackson,所以只需要导入Jackson的jar

1.导入依赖

  <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>

2.使用@ResponseBody

@ResponseBody
将handler的返回值,转换成json(jackson),并将json响应给客户端

@Controller
@RequestMapping("/json")
public class JsonController {
    @RequestMapping("/test1")
    @ResponseBody
    public User test1(){
        System.out.println("test1");
        User user = new User(1,"李四");
        return user;
    }

    @RequestMapping(value = "/test2",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String test2(){
        System.out.println("test2");
        return "利好";//结果返回 利好
    }
}

3.使用@RestController

@RestController
给该控制类的所有方法即handler都加上@ResponseBody的作用
注意:使用了@RestController可以不用写@Controller,因为@RestController里面已经有了@Controller注解

@RestController
@RequestMapping("/json")
public class JsonController {
    @RequestMapping("/test1")
//    @ResponseBody
    public User test1(){
        System.out.println("test1");
        User user = new User(1,"李四");
        return user;
    }

    @RequestMapping(value = "/test2",produces = "text/html;charset=utf-8")
//    @ResponseBody
    public String test2(){
        System.out.println("test2");
        return "利好";
    }

    @RequestMapping("/test3")
    public String test3(@RequestBody User user){
        System.out.println(user);
        return "ok";
    }
}

4.使用@RequestBody

@RequestBody 接收json参数

4.1定义handler

实体类User

public class User {
    private Integer id;
    private String name;
    private Boolean gender;
    private Date birth;
    private String[] hobby;

    public User(){

    }
    public User(Integer id, String name) {
        this.id = id;
        this.name = name;

    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender=" + gender +
                ", birth=" + birth +
                ", hobby=" + Arrays.toString(hobby) +
                '}';
    }

    public String[] getHobby() {
        return hobby;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boolean getGender() {
        return gender;
    }

    public void setGender(Boolean gender) {
        this.gender = gender;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
}

JsonController

 @RequestMapping("/test3")
    public String test3(@RequestBody User user){//@RequestBody将请求体中的json数据转换为java对象
        System.out.println(user);
        return "ok";
    }

4.2Ajax发送json

下载jquery-2.1.1.js的代码导入进去
一起学习SSM框架之SpringMVC(三)
json.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jquery-2.1.1.js"></script>
</head>
<body>
    <input type="button" value="ajax" onclick="send_json();">
    <script>
        function send_json(){
        //    ajax json
            var user={id:1,name:"战三"};
            var userJson=JSON.stringify(user);

            $.ajax({
                url:"${pageContext.request.contextPath}/json/test3",
                type:"post",
                data:userJson,
                contentType:"application/json",
                success:function (ret){
                    alert(ret);
                }
                }
            )
        }
    </script>

</body>
</html>

5.Jackson常用注解

5.1日期格式化

@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”)

User

    @JsonFormat(pattern = "YYYY-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date birth;

JsonController

    @RequestMapping("/test1")
//    @ResponseBody
    public User test1(){
        System.out.println("test1");
        User user = new User(1,"李四",new Date());
        return user;
    }

5.2属性名修改

User

 @JsonProperty("id_new")
    private Integer id;

json响应的id属性变成id_new

5.3属性忽略

User

 @JsonIgnore
    private Boolean gender;

json响应就不会有gender属性

5.4null和empty属性排除

@JsonInclude(JsonInclude.Include.NON_NULL)
null值,属性不输出
元素为空就不会json响应显示

@JsonInclude(JsonInclude.Include.NON_NULL)
    private List<String> hobby;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
empty属性不输出(空串,长度为0的集合,null值)

 @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<String> hobby;

5.5自定义序列化

User

  @JsonSerialize(using= MySerializer.class)
    private Double salary=10000.262; //用MySerializer输出

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

MySerializer

public class MySerializer extends JsonSerializer<Double> {


    public void serialize(Double aDouble, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        //将salary的值四舍五入  留两位小数
        String number= BigDecimal.valueOf(aDouble).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
        //输出四舍五入的值
        jsonGenerator.writeNumber(number);
    }
}

FastJson

SpringMVC默认的json处理方案是Jackson,但是FastJson性能更好,可以使用FastJson处理方案

1.导入依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

2.安装FastJson

mvc.xml

 <!--启动mvc注解驱动-->
    <mvc:annotation-driven>
        <!--安装FastJson,转化器-->
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <!--声明转换类型:json-->
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

3.使用常用注解

日期格式化:@JSONField(format = “yyyy/MM/dd”)
属性名修改:@JSONField(name=“xxxx”)
忽略属性名:@JSONField(serialize = false)
包含null值:@JSONField(serialzeFeatures = SerializerFeature.WriteNullStringAsEmpty)
//null的String输出为""空串
@JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)
//默认会忽略所有null值,有此注解输出null
自定义序列化: @JSONField(serializeUsing =xxxx.class)

User2


public class User2 {
    @JSONField(serialize = false)
    private Integer id;
    @JSONField(name="Name",serialzeFeatures = SerializerFeature.WriteNullStringAsEmpty)
    private String name;
    @JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)
    private String city;
    @JSONField(format = "yyyy/MM/dd")
    private Date birth;
    @JSONField(serializeUsing = MySerializer2.class)
    private Double salary;

    public User2(Integer id, String name, String city, Date birth, Double salary) {
        this.id = id;
        this.name = name;
        this.city = city;
        this.birth = birth;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User2{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", city='" + city + '\'' +
                ", birth=" + birth +
                ", salary=" + salary +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }
}

MySerializer2


public class MySerializer2 implements ObjectSerializer {
    public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type, int i) throws IOException {
        Double value=(Double) o;//salary属性值
        String text=value+"元";//salary属性值后面添加 元
        jsonSerializer.write(text);

    }
}

JsonController

  @RequestMapping("/test12")
//    @ResponseBody
    public User2 test12(){
        System.out.println("test12");
        User2 user2= new User2(1,"李k","上海",new Date(),1000.22);
        return user2;
    }

本文地址:https://blog.csdn.net/ozl520/article/details/109225107