SpringMVC框架之请求参数

#SpringMVC框架模块解析

springmvc的功能是接收浏览器请求,完成请求响应。``
因此从下面三个方面分模块解析mvc的功能。

  1. 接收请求参数
  2. 处理请求后返回值
  3. 其他功能
    接收请求参数问题:
    Controller以基本类型+String型接收参数时,Controller接收参数列表名需要和表单name属性值相同
<a href="/greetings/show2?name=Tom">get链接</a>
@RequestMapping("/show2")
public String testGet(String name){
    System.out.println(name);
    return "success";
}

Controller以pojo型接收参数时,表单name属性值 = pojo的变量名

<form action="/greetings/show3" method="post">
    <input type="text" name="name">姓名<br>
    <input type="text" name="age">年龄<br>
    <input type="submit" value="提交">
</form>
@RequestMapping("/show3")
public String testUser(User user){
    System.out.println(user);
    return "success";
}

当页面有集合参数时,可以将集合封装进pojo,然后Controller以pojo接收

public class User {
    private String name;
    private String age;
    private String password;
    private List<Account> accounts;
    private Map<String,Account> accountMap;
    }~
<form method="post" action="/greetings/show" >

    <input type="text" name="name">姓名<br>
    <input type="text" name="age">年龄<br>

    <input type="text" name="accounts[1].name">账户一姓名<br>
    <input type="text" name="accounts[1].money">账户一金额<br>
    <input type="text" name="accounts[2].name">账户二姓名<br>
    <input type="text" name="accounts[2].money">账户二金额<br>
    <input type="text" name="accountMap['three'].name">账户三姓名<br>
    <input type="text" name="accountMap['three'].money">账户三金额<br>
    <input type="text" name="accountMap['four'].name">账户四姓名<br>
    <input type="text" name="accountMap['four'].money">账户四金额<br>

    <input type="submit" value="提交">

</form>~
@RequestMapping("/show")
public String testList(User user){
    System.out.println(user);
    return "success";
}~

此外当页面数据是json串时,Controller以@RequestBody注解接收

<script type="text/javascript">
    $(function(){
        $("#testJson").click(function(){
            alert("jingru");
            $.ajax({
                 type:"post",
                 url:"${pageContext.request.contextPath}/ResponseJson/test",
                 contentType:"application/json;charset=utf-8",
                 data:'[{"name":"test","age":"23"},{"name":"Lily","age":"25"}],
                 dataType:"json",
                 success:function(data){
                     alert(data);
                 }
            });
        });
    })
   </script>

<!-- 测试异步请求 -->
<input type="button" value=" 测试 ajax请求 json和响应 json" id="testJson"/>~
@RequestMapping("/test")
public @ResponseBody List<User> test(@RequestBody List<User>userList){
    
    return userList;
}~

上例也表明集合参数也可以以json串发送,Controller加上@RequestBody接收集合参数。
@RequestBody注解表示接收json串数据,@ResponseBody注解表示以json串返回数据,返回的String不会再经过视图解析器解析,直接以流的方式返回到页面

接收参数还有一个注解:@RequestParameter

<form action="/greetings/show3" method="get">
    <input type="text" name="name">姓名<br>
    <input type="text" name="age">年龄<br>
    <input type="submit" value="提交">
</form>~
@RequestMapping("/show3")
public String testParameter(@RequestParam(value = "name") String username,
                            @RequestParam(value = "age",required = false)String age){
    System.out.println(username);
    System.out.println(age);
    return "success";
}~

接收页面的Cookie参数
使用注解@CookieValue接收Cookie

<a href="/greetings/show6">接收Cookie值</a>~
@RequestMapping("/show6")
public String testCookie(@CookieValue(value = "Total",required = false) String total){
    System.out.println(total);
    return "success";
}~

接收参数会遇见的两个问题:中文参数乱码、参数类型不对应
1.中文乱码解决:
post发送请求乱码,虽然页面字符编码为utf-8及页面编码也为utf-8,但是mvc框架接收后以默认编码格式“ISO-8859-1”编码,导致乱码。解决办法:
在web.xml配置过滤器,过滤所有资源以utf-8编码

 <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
<!--设置过滤器中属性值  -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
<!--启动过滤器    -->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

<!--拦截所有请求  -->
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
<!-- 拦截所有资源   -->
<!--    <url-pattern>\/*</url-pattern>-->
<!--拦截前端控制器servlet的请求    -->
    <servlet-name>SpringMVCDispatcherServlet</servlet-name>~

get请求中文乱码解决办法:
修改Tomcate conf文件下的server.xml

<Connector  connectionTimeout="20000"  port="8080"    protocol="HTTP/1.1"  redirectPort="8443"/> 

改为:

 <Connector  connectionTimeout="20000"  port="8080"     protocol="HTTP/1.1"  redirectPort="8443"     为 URIEncoding="true"/> 

2.参数类型不对应

<a href="/greetings/show4?date=2019-12-1">日期转换</a>~
@RequestMapping("/show4")
public String testStringToDate(String date){
    System.out.println(date);
    return "success";
}~

页面传的是String 型,但接收要求为Date型。这种情况下需要编写转换器

public class StringToDateConverter implements Converter<String,Date> {

    @Override
    public Date convert(String s) {
        SimpleDateFormat format = new SimpleDateFormat();
        Date date = null;
        try {
            date = format.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("String 转 Date 有误");
        }
        return date;
    }
}~

配置转换器

<!-- 类型转换工厂   -->
    <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!--的类型转换器集合      -->
        <property name="converters">
            <array>
<!--自定义转换类                -->
                <bean class="cn.itheima.converters.StringToDateConverter"></bean>
            </array>
        </property>

    </bean>~
    <!-- 引用自定义类型转换器,适配器会将String === Date Controller预先经过自定义转换类 -->
<mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值