【SpringMVC入门系列】篇2:SpringMVC接收参数的几种方式

SpringMVC接收参数

springMVC接收参数主要有以下几种方式:

1.使用原始的request接收

假设我们有以下请求:

<a href="${pageContext.request.contextPath}/first?id=101&name=thinmoon">跳转</a>

我们只需要在接收first请求的方法中添加一个原始的request参数即可。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MyController {

    @RequestMapping("/first")
    public String show(HttpServletRequest request) {

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        System.out.println(name + " " + id);
        return "/first.jsp";
    }
}

2.使用@RequestParam

上述代码需要我们传入request对象并且需要我们调用request.getParameter("id")才能够获取参数,我们可以通过@RequestParam注解可以实现在请求方法参数中直接获取参数,我们可以将上述代码改为如下形式:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MyController {

    @RequestMapping("/first")
    public String show(@RequestParam(value = "id", required = false, defaultValue = "100") Integer idKey , String name) {
        System.out.println(name + " " + idKey);
        return "/first.jsp";
    }
}

代码的意思是,我们可以在方法参数中绑定url获取到的参数,并且会给我们做自动转型。其中

@RequestParam(value = "id", required = false, defaultValue = "100") Integer idKey

该参数表示的意思是:

  • value:表示为id的参数

  • required:有两个值分别是true、false。默认为true,表示url必须有该参数,false表示该参数可有可无

  • defaulValue:当url中没有该参数时的默认值

如果我们不想写@RequestParam标签,那么我们方法中的参数名必须与url中的参数名一致。

3.使用javaBean接收参数

我们还可以使用javaBean的形式进行接收代码,假如我们有以下请求:

<form action="${pageContext.request.contextPath}/form">
    用户名:<input type="text" name="username"><br>
    年龄:<input type="text" name="age"><br>
    <input type="checkbox" name="hobby" value="足球">足球<br>
    <input type="checkbox" name="hobby" value="篮球">篮球<br>
    <input type="checkbox" name="hobby" value="乒乓球">乒乓球<br>

    <hr>
    宠物名:<input type="text" name="dog.name"><br>
    宠物年龄:<input type="text" name="dog.age"><br>

    <hr>
    宠物名:<input type="text" name="dogs[0].name"><br>
    宠物年龄:<input type="text" name="dogs[0].age"><br>
    <hr>
    宠物名:<input type="text" name="dogs[1].name"><br>
    宠物年龄:<input type="text" name="dogs[1].age"><br>
    <hr>
    宠物名:<input type="text" name="dogs[2].name"><br>
    宠物年龄:<input type="text" name="dogs[2].age"><br>
    <input type="submit" value="提交">
</form>

我们对照参数名编写相应的javaBean

import java.util.Arrays;
import java.util.List;

public class User {
    String username;
    Integer age;
    String[] hobby;

    Dog dog;
    List<Dog> dogs;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

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

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public List<Dog> getDogs() {
        return dogs;
    }

    public void setDogs(List<Dog> dogs) {
        this.dogs = dogs;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", hobby=" + Arrays.toString(hobby) +
                ", dog=" + dog +
                ", dogs=" + dogs +
                '}';
    }
}

可以看到请求中有类相同name都为hobby,我们只需要设置相应的数组进行接收即可。

如果我们javaBean中有其他的bean对象我们也只需在传参时设置好参数名即可,类似于这样:

宠物名:<input type="text" name="dog.name"><br>
宠物年龄:<input type="text" name="dog.age"><br>

如果javabean中存在集合我们可以这样传参:

<hr>
宠物名:<input type="text" name="dogs[0].name"><br>
宠物年龄:<input type="text" name="dogs[0].age"><br>
<hr>
宠物名:<input type="text" name="dogs[1].name"><br>
宠物年龄:<input type="text" name="dogs[1].age"><br>
<hr>
宠物名:<input type="text" name="dogs[2].name"><br>
宠物年龄:<input type="text" name="dogs[2].age"><br>

接着我们将javabean传入请求方法即可:

@RequestMapping("/form")
public String show3(User user) {
    System.out.println(user);
    return "/first.jsp";
}

4.自定义转换器

上面提到的请求接收springmvc会帮我们实现自动转换,但是对于有格式的数据比如时间类型springmvc默认能帮我们转换的时间格式是yyyy/MM/dd(2020/02/02)这种格式。如果我们想要自定义转换格式则需要我们自己实现转换类。

首先我们需要实现一个Converter接口:

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {

        if (s != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = simpleDateFormat.parse(s);
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}

接着我们需要配置springmvc.xml,在配置中配置转换器,并且注册驱动。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="icu.thinmoon"/>

    <!--配置Converter转换器 转换工厂-->
    <bean  id="dateConvert" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!--可以配置多个转换器-->
        <property name="converters">
            <list>
                <bean class="icu.thinmoon.util.DateConverter"/>
            </list>
        </property>
    </bean>

    <!--注解驱动-->
    <mvc:annotation-driven conversion-service="dateConvert"/>


</beans>

5.POST请求中文乱码

解决post请求中文乱码,我们只需要在web.xml中配置以下代码即可。
注意:该配置最好放在最前面,因为拦截有顺序,放后面容易拦截不到!

    <!-- 解决post乱码问题 -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!-- 设置编码参是UTF8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
posted @ 2020-07-03 21:01  ThinMoon  阅读(353)  评论(0编辑  收藏  举报