springMVC- request parameter binding

Binding mechanism

We all know that the parameters are based on the request form = Key value of.
Process SpringMVC binding request parameter by the parameter request to submit the form, as a control method of binding parameters.
E.g:
<a href= "account/findAccount ?accountId=10"> check account </a>
The request parameters are:
accountId=10
/**
* View Account
* @return
*/
@RequestMapping("/findAccount")
public String findAccount(Integer accountId) {
System. OUT .println ( " query the account .... " + accountId);
 return  " Success " ;
}

Supported data types

Basic types of parameters:
Including basic types and type String
POJO type parameters:
Including entity class, the entity class and associated
And a collection array type parameters:
List Structure Map and comprising a set of structures (including arrays)
SpringMVC binding request parameters are automatically implemented, however, to use, you must follow the requirements.

Requirements

If the basic type or String type:
We have required parameter name and parameter names consistent control method. (Strictly case-sensitive)
If POJO type, or its associated object:
It requires the name of the form attribute parameter names and POJO class consistent. The method of the controller and the parameter type is POJO type.
If a collection type, there are two ways:
The first:
Required parameters must be set in the type of request POJO. Request for a parameter name in the form POJO and collection of the same attribute name.
List elements of the collection to the assignment, using the subscript.
Map to assign elements of the collection, use pairs.
The second:
The request parameters received json format data. We need to achieve a comment.
note:
It also enables automatic conversion of some data types. Built-in converter all in:
org.springframework.core.convert.support next package. Have:
java.lang.Boolean -> java.lang.String : ObjectToStringConverter
java.lang.Character -> java.lang.Number : CharacterToNumberFactory
java.lang.Character -> java.lang.String : ObjectToStringConverter
java.lang.Enum -> java.lang.String: EnumToStringConverter
java.lang.Number -> java.lang.Character : NumberToCharacterConverter
java.lang.Number -> java.lang.Number : NumberToNumberConverterFactory
java.lang.Number -> java.lang.String : ObjectToStringConverter
...
In case of a special type of conversion requirements, the need to write our own self-defined type converter

1. The basic types as parameters of type String and

jsp code
 <a href= "params/testParams?username=rainbow&password=123456"> request parameter binding </a>

Controller code
    @RequestMapping("/testParams")
    public String testParams(String username,int password){
        . System OUT .println ( " the implementation of the binding parameters " );
        . System OUT .println ( " User Name: " + username);
        System.out.println("密码:" + password);
        return "success";
    }

 

 

2.POJO type as a parameter

pojo类
public class Account {
    private String accountNumber;
    private String password;
    private double money;
    ...
}
jsp code
    <form method="post" action="params/saveAccount">
        帐号:<input type="text" name="accountNumber"/><br/>
        密码:<input type="text" name="password"/><br/>
        金额:<input type="text" name="money"/><br/>
        <input type="submit" value="保存帐号"/><br/>
    </form>

Controller code
    @RequestMapping("saveAccount")
    public String saveAccount(Account account){
        System.out.println(account);
        return "success";
    }

 

 

 

3.POJO class member variable contains pojo

 

pojo类
public class User implements Serializable{
    private Account account;
    private String name;
    private int age;
    private String addr;
    ...
}
jsp code
    <form method="post" action="params/saveUser">
        姓名:<input type="text" name="name"/><br/>
        年龄:<input type="text" name="age"/><br/>
        地址:<input type="text" name="addr"/><br/>
        帐号:<input type="text" name="account.accountNumber"/><br/>
        密码:<input type="text" name="accunt.password"/><br/>
        金额:<input type="text" name="account.money"/><br/>
        <input type="submit" value="保存用户"/><br/>
    </form>

Controller code
    @RequestMapping("saveUser")
    public String saveUser(User user){
        System.out.println(user);
        return "success";
    }

4.POJO class contains a collection of type parameters 

pojo类
public class User2 {
    private String name;
    private int age;
    private String addr;
    private List<Account> accountList;
    private Map<String,Account> accountMap;
    ...
}
jsp code
<form method="post" action="params/saveUsers"> 姓名:<input type="text" name="name"/><br/> 年龄:<input type="text" name="age"/><br/> 地址:<input type="text" name="addr"/><br/> 帐号1:<input type="text" name="accountList[0].accountNumber"/><br/> 密码1:<input type="text" name="accountList[0].password"/><br/> 金额1:<input type="text" name="accountList[0].money"/><br/> 帐号2:<input type="text" name="accountList[1].accountNumber"/><br/> 密码2:<input type="text" name="accountList[1].password"/><br/> 金额2:<input type="text" name="accountList[1].money"/><br/> 帐号3:<input type="text" name="accountMap['one'].accountNumber"/><br/> 密码3:<input type="text" name="accountMap['one'].password"/><br/> 金额3:<input type="text" name="accountMap['one'].money"/><br/> <INPUT type = " Submit " value = " Save Multi-User account " /> a </form> Controller code @RequestMapping("saveUsers") public String saveUser(User2 user2){ System.out.println(user2); return "success"; }

 

 

The request parameter problem Chinese garbled

In the above user name if written in Chinese, will be garbled situation

 Chinese distortion of the case can be handled by configuring the filter

get way request

get request method:
tomacat GET and POST requests to a different approach, coding problems GET request, to change the server.xml tomcat
Configuration file, as follows:
<Connector connectionTimeout="20000" port="8080"
protocol="HTTP/1.1" redirectPort="8443"/>
改为:
<Connector connectionTimeout="20000" port="8080"
protocol="HTTP/1.1" redirectPort="8443"
useBodyEncodingForURI="true"/>
如果遇到 ajax 请求仍然乱码,请把:
useBodyEncodingForURI="true"改为 URIEncoding="UTF-8"
即可。

post方式请求

在web.xml中配置

 <!-- 配置 springMVC 编码过滤器 -->
  <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>
  </filter-mapping>
</web-app>

配置了过滤器就可以解决乱码问题

另外

在 springmvc 的配置文件中可以配置,静态资源不过滤:
<!-- location 表示路径, mapping 表示文件, **表示该目录下的文件以及子目录的文件 -->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/scripts/" mapping="/javascript/**"/>

6.自定义类型转换

比如,在java中,默认的日期格式是yyyy/MM/dd

如果我输入的是yyyy-MM-dd,就会出现错误

jsp代码
    <form method="post" action="params/saveDate">
        日期:<input type="text" name="date"/><br/>
        <input type="submit" value="保存日期"/><br/>
    </form>

控制器代码
    @RequestMapping("saveDate")
    public String saveDate(Date date){
        System.out.println(date);
        return "success";
    }

 

所以需要写一个自定义类型的转换器,这个转换器需要实现Converter接口

public interface Converter<S, T> {//S:表示接受的类型, T:表示目标类型
    /**
    * 实现类型转换的方法
    */
    @Nullable
    T convert(S source);
}

本身已经有很多这个实现了这个接口的自动类型转换,比如

 

步骤 

1.要写一个字符串类型转换成Date类型的转换器

public class StringToDateConverter implements Converter<String,Date> {
    @Override
    public Date convert(String source) {
        DateFormat format = null;
        try {
            if(StringUtils.isEmpty(source)) {
                throw new NullPointerException("请输入要转换的日期");
            }
            format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(source);
            return date;
        } catch (Exception e) {
            throw new RuntimeException("输入日期有误");
        }
    }
}

2.spring 配置文件中配置类型转换器。
spring 配置类型转换器的机制是,将自定义的转换器注册到类型转换服务中去。

ConversionServiceFactoryBean里面有一个set类型的converters,我们需要的就是将自己写的转换器注册到里面去

    <!--日期转换-->
   <bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="conversionService2">
       <property name="converters">
           <set>
               <bean class="com.cong.utils.StringToDateConverter"></bean>
           </set>
       </property>
   </bean>

3.annotation-driven 标签中引用配置的类型转换服务

 <mvc:annotation-driven conversion-service="conversionService2"></mvc:annotation-driven>
</beans>

这样就可以写自己想要的日期格式

使用 ServletAPI 对象作为方法参数 

SpringMVC 还支持使用原始 ServletAPI 对象作为控制器方法的参数。支持原始 ServletAPI 对象有:
HttpServletRequest
HttpServletResponse
HttpSession
java.security.Principal
Locale
InputStream
OutputStream
Reader
Writer
我们可以把上述对象,直接写在控制的方法参数中使用

示例

jsp代码
    <a href="params/testServlet">Servlet原生的API</a>

控制器代码
    @RequestMapping("testServlet")
    public String testServlet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("run...");
        System.out.println(request);
        HttpSession session = request.getSession();
        System.out.println(session);
        ServletContext context = session.getServletContext();
        System.out.println(context);
        return "success";
    }

执行结果

 

 

 

 

Guess you like

Origin www.cnblogs.com/ccoonngg/p/11839573.html