SpringMVC学习笔记二

274 阅读5分钟

上篇主要搭建了入门案例并分析了使用到的相关类以及注意事项。关于SpringMVC的流程、组件还需多多熟练后在去加深理解。
SpringMVC是web层轻量级框架,接下来来了解它从前端接收数据、返回数据给前端的方式。

1.接收若干个普通参数

方式一:参数写在Controller的方法的形参中,适用于get, post方式提交。参数名必须和前台的一致。
    @RequestMapping("/demo2")
    public String getUserName(String username){
        System.out.println(username);
        return "success";
    }

方式二:接收HttpServletRequest

    @RequestMapping("/demo3")
    public String getUserName(HttpServletRequest request){
        String username = request.getParameter("username");
        System.out.println(username);
        return "success";
    }

方式三:使用@RequestParam注解
@RequestParam注解有两个属性:value和required(默认为true)

    @RequestMapping("/demo4")
    public String getUserInfo(@RequestParam("username") String name, @RequestParam("sex") String sex) {
        System.out.println(name);
        System.out.println(sex);
        return "success";
    }

2.接收实体类型数据

写程序时用的最多的就是接收实体类型数据了,掌握如何准确拿到前台传来的数据很重要。

方式一:表单属性与实体属性一一对应。
public class User {
    private String username;
    private String sex;
    private int age;
    
    //省略getter/setter/toString
}
<form id="testForm" method="post" action="test/demo5">
    用户名:<input type="text" name="username"/><br/>
    性别:<input type="text" name="sex"/><br/>
    年龄:<input type="text" name="age"/><br/>
    <input type="submit" value="提交">
</form>
    @RequestMapping("/demo5")
    public String getUserInfo(User user) {
        System.out.println(user.toString());
        return "success";
    }

输出结果为:


方式二:使用@RequestBody注解
@Requestbody用于获取请求体内容。 直接使用得到是key=value&key=value...结构的数据。适用于post请求、get请求方式不适用。@RequestBody的使用场景大多用于接收json格式数据
@RequestBody的属性有reuqired,默认为true

    @RequestMapping("/demo6")
    public String getUserInfo(@RequestBody String body) {
        System.out.println(body);
        return "success";
    }

输出结果为:


复杂点的实体Bean对象
1. Bean对象中包含另一个对象,比如user对象中包含账户信息Account

public class User {
    private String username;
    private String sex;
    private int age;
    private Account account;

    //getter/setter/toString
}
public class Account {
    private Integer id;
    private String name;
    private float money;

    //getter/setter/toString
    }
    @RequestMapping("/demo5")
    public String getUserInfo(User user) {
        System.out.println(user.toString());
        return "success";
    }
<form id="testForm" method="post" action="test/demo5">
    用户名:<input type="text" name="username"/><br/>
    性别:<input type="text" name="sex"/><br/>
    年龄:<input type="text" name="age"/><br/>
    账户ID:<input type="text" name="account.id"/><br/>
    账户余额:<input type="text" name="account.money"/><br/>
    <input type="submit" value="提交">
</form>

输出结果为:


2. Bean对象中包含List集合与Map集合

public class User {
    private String username;
    private String sex;
    private int age;
    private List<Address> receiveAddress; //收货地址
    private Map<String,Account> accountMap;

    //getter/setter/toString
}
public class Address {
    private String name;
    private String phone;
    private String adress;

    //getter/setter/toString
}
<form id="testForm" method="post" action="test/demo5">
    用户名:<input type="text" name="username"/><br/>
    性别:<input type="text" name="sex"/><br/>
    年龄:<input type="text" name="age"/><br/>
    收货人一:<input type="text" name="receiveAddress[0].name"/><br/>
    收货人一的电话:<input type="text" name="receiveAddress[0].phone"/><br/>
    收货人二:<input type="text" name="receiveAddress[1].name"/><br/>
    收货人二的电话:<input type="text" name="receiveAddress[1].phone"/><br/>
    账户一姓名:<input type="text" name="accountMap['one'].name"/><br/>
    账户一余额:<input type="text" name="accountMap['one'].money"/><br/>
    <input type="submit" value="提交">
</form>
    @RequestMapping("/demo5")
    public String getUserInfo(User user) {
        System.out.println(user.toString());
        return "success";
    }

DEBUG可以看到传进来的值


接收与响应json数据

在SpringMVC中使用@RequestBody与@ResponseBody组合即可完成接收与响应json数据。

@ResponseBody

@ResponseBody:注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML 数据,需要注意的是在使用此注解之后不会再走视图处理器,而是直接将数据写回,他的效果等同于通过response对象输出指定格式的数据。 :

    <a href="#" id="test">测试</a>
    $("#test").click(function () {
        $.getJSON("test/demo6?username=zs",function (data) {
            alert(data);
        });
    })
    @RequestMapping("/demo6")
    public  @ResponseBody String getUserInfo(String  username) {
        System.out.println(username);
        //可返回字符串、json数据等等、不走视图解析器
        return "操作成功";
    }


@RequestBody
@RequestBody解析请求的数据的时候会用HttpMessageConverter类(消息转换器),如果想用JSON来接收数据,那么就要配置httpMessageConverter类,所以也可以自己定义解析的方式。SpringMVC默认处理json的工具是jackson,若选用 jackson,便无需手动配置httpMessageConverter了。

<!--jackson地址-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.1</version>
</dependency>

若选用fastjson作为json工具则需在springmvc.xml中进行配置httpMessageConverter类为fastjson的:

<!--fastJson相关的jar包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.37</version>
        </dependency>
<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 配置Fastjson支持 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <value>WriteMapNullValue</value>
                        <value>QuoteFieldNames</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

实例:采用ajax提交form表单数据

<form id="testForm">
    用户名:<input type="text" name="username"/><br/>
    性别:<input type="text" name="sex"/><br/>
    年龄:<input type="text" name="age"/><br/>
    <input type="button" value="提交" id="submit">
</form>
    $(function () {
        $("#submit").click(function () {
            var jsonObject = $("#testForm").serializeObject();
            console.log(JSON.stringify(jsonObject));
            $.ajax({
                type: "post",
                url: "test/demo5",
                data: JSON.stringify(jsonObject),
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                success: function (data) {
                    //如果返回的是json字符串、需要在前台解析为json对象
                    var object = $.parseJSON(data);
                    alert(object.statusCode);
                }
            });
        });

        //序列化表单元素为json对象
        $.fn.serializeObject = function()
        {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    });
    @RequestMapping("/demo5")
    public  @ResponseBody String getUserInfo(@RequestBody User user) {
        System.out.println(user.toString());
        //业务逻辑处理
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("statusCode","200");
        return jsonObject.toString();
    }

如图:后台已正确接收到json数据并映射到Bean对象中、前台已收到后台发送的json数据

注意事项:

  • 使用SpringMVC的话传递到后台的一定要是严格的json数据、jquery提供的序列化表单元素的$.serialize序列化后为字符串、serializeArray序列化的为数组,需要将其化为json格式的字符串。
  • form表单的元素与Bean对象的属性要一一对应
  • ajax提交至服务器的默认编码为application/x-www-form-urlencoded,需要指定提交至服务器数据格式为json数据的话需要设定contentType: "application/json;charset=utf-8"
  • 若选用默认的jackson,就能够自动返回 JSON。凡是在接口中直接返回的对象,集合等等,都会自动转为 JSON。
  • 若前台发送的是json格式的数据过去,后台需要用一个bean对象去接收,比如前台发送{"id":52},此时后台参数类型为int id,将报错接收不到数据。