SpringMVC 获取请求参数

1.获取Request response对象

在SpringMVC的注解开发中,可以选择性的接收Request和Response对象来使用

2.获取request对象请求参数

a.通过request对象获取

通过request对象获取请求参数时,类型不一致时需要手动转换。int age = Integer.parseInt(request.getParameter("age"));

    /**
     * 获取request 和 response
     */
    @RequestMapping("/hello3.action")
    public String hello3(HttpServletRequest request,
            HttpServletResponse response,
            Model model){
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        // 获取某个请求头信息
        String al = request.getHeader("Accept-Language");
        System.out.println(al);
        System.out.println(username + "~~" + age);
        model.addAttribute("msg","hello springmvc~");
        return "hello";
    }

访问:http://localhost/SpringMVC2/hello3.action?username=cjj&age=18

b.直接接收请求参数

可以在Controller方法中直接接收请求参数相同否认方法形参,可以直接得到请求参数的值。

WebRoot目录下创建一个from表单

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello4.action" method="POST">
        <table>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="text" name="password"/></td>
            </tr>
            <tr>
                <td>年龄</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
from.jsp
    /**
     * 快速获得请求参数
     */
    @RequestMapping("/hello4.action")
    public String hello4(String username, String password, int age, Model model){
        System.out.println(username+"--"+password+"--"+age);
        model.addAttribute("msg", "hello springmvc ~~");
        return "hello";
    }

访问:http://localhost/SpringMVC2/from.jsp

点击提交,跳转到:http://localhost/SpringMVC2/hello4.action

控制台输出:

c.自动封装请求参数信息到bean

SpringMVC框架可以自动将请求参数封装到bean中,要求bean中必须提供属性的setXxx方法,且bean的属性名和请求参数的名字必须一致,才可以自动设置。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello5.action" method="POST">
        <table>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="text" name="password"/></td>
            </tr>
            <tr>
                <td>年龄</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
form.jsp
package cn.tedu.springmvc.beans;

public class User {
    private String username;
    private String password;
    private int age;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
User.java
    /**
     * 封装请求参数到bean
     */
    @RequestMapping("/hello5.action")
    public String hello5(User user, Model model){
        System.out.println(user);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

访问:http://localhost/SpringMVC2/from.jsp

页面跳转:http://localhost/SpringMVC2/hello5.action

控制台输出:

d.处理复杂类型

如果自动封装的bean中存在复杂类型,只要该复杂类型的属性同样具有setXxx方法,

则可以在请求参数中包含[bean中复杂类型].[属性]的方法为该复杂类型的参数复制,

从而实现自动封装bean的过程中处理其中复杂类型。

package cn.tedu.springmvc.beans;

public class User {
    private String username;
    private String password;
    private int age;
    private Dog dog;
    
    public Dog getDog() {
        return dog;
    }
    
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password
                + ", age=" + age + ", dog=" + dog + "]";
    }
}
User.java
package cn.tedu.springmvc.beans;

public class Dog {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog [name=" + name + ", age=" + age + "]";
    }
}
Dog.java
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello5.action" method="POST">
        <table>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="dog.name"/></td>
            </tr>
            <tr>
                <td>年龄</td>
                <td><input type="text" name="dog.age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
from.jsp
    /**
     * 封装请求参数到bean
     */
    @RequestMapping("/hello5.action")
    public String hello5(User user, Model model){
        System.out.println(user);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

e.请求参数中的名称和属性名不同的处理@RequParam

可以通过@RequestParam来修饰Controller方法中用来接收请求参数的形参,

有如下属性可以配置:

value来指定将哪个请求参数复制给当前形参

将required声明为true,则请求参数中必须有该属性,如果没有客户端将收到400

 

defaultValue可以设定当前形参的默认值

public String hello5(User user, @RequestParam(value="hobby",required=true)String[] hobbys, Model model){

f.请求参数中存在多个同名值

如果请求参数中存在多个同名值

 

此时直接获取,会得到一个用逗号分隔的字符串

    /**
     * 接收同名的多值请求参数
     */
    @RequestMapping("/hello6")
    public String hello6(String like,Model model){
        System.out.println(like);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

访问

控制台输出:

也可以修改Controller方法的形参为数据类型,则直接接收到一个数组

    /**
     * 接收同名的多值请求参数
     */
    @RequestMapping("/hello6")
    public String hello6(String[] like,Model model){
        System.out.println(Arrays.toString(like));
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

 访问

控制台输出

g.请求参数中的中文乱码修改

SpringMVC提供了过滤器用来解决全站乱码

  <!-- 配置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>
  </filter>
  <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

这种方式只能解决POST提交的乱码,对GET方式提交的乱码无效!

此时只能手动进行编解码,解决GET方式请求参数乱码

也可以直接修改Tomcat中链接器的配置来使tomcat默认采用指定编码处理请求参数

但是这种方式不建议大家使用,因为生产环境下不一定允许修改此项。

h.日期数据的处理

在SpringMVC中解析页面提交的参数时,日期默认格式是yyyy/MM/dd,并不符合中国人平常的使用习惯,

此时可以配置适配器自己来指定格式

  /**
     * 日期格式处理
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping("/hello8.action")
    public String hello8(Date birthday,Model model) throws UnsupportedEncodingException{
        System.out.println(birthday);
        model.addAttribute("msg", "hello springMvc4,hello World4~");
        return "hello";
    }
    
    public void InitBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello8.action" method="POST">
        <table>
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>年龄</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                  <td>狗名</td>
                  <td><input type="text" name="dog.name"/></td>
              </tr>
              <tr>
                  <td>狗龄</td>
                  <td><input type="text" name="dog.age"/></td>
              </tr>
            <tr>
                  <td>出生日期</td>
                  <td><input type="text" name="birthday"/></td>
              </tr>
            <tr>
                <td>爱好</td>
                  <td>
                      <input type="checkbox" name="like" value="zq"/>足球
                      <input type="checkbox" name="like" value="lq"/>篮球
                      <input type="checkbox" name="like" value="pq"/>排球
                      <input type="checkbox" name="like" value="qq"/>铅球
                  </td>            
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
form.jsp

访问

控制台输出:

i.SpringMVC文件上传

(1)准备上传表单

文件上传表单必须满足如下三个条件

a)表单必须是POST提交的

b)表单必须是enctype=“multipart/form-data”

c)文件上传必须有name属性

(2)在配置文件中配置文件上传工具

 

 (3)在Controller中实现文件上传

    /**
     * 文件上传
     * @throws IOException 
     */
    @RequestMapping("/hello9.action")
    public String hello9(MultipartFile fx, Model model) throws IOException{
        System.out.println(fx.getOriginalFilename());
        FileUtils.writeByteArrayToFile(new File("E://"+fx.getOriginalFilename()), fx.getBytes());
        
        model.addAttribute("msg", "hello springmvc ~~");
        return "hello";
    }

j.RESTul风格的请求参数处理

(1)RESTul风格的请求

普通get请求:

RESTFul风格的请求:

 

(2)SpringMVC对RESTFul风格的请求的我处理

    /**
     * RESTFul支持
     */
    @RequestMapping("/hello10/{username}/{age}.action")
    public String hello10(@PathVariable String username, @PathVariable int age, Model model){
        System.out.println(username+"~"+age);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

 访问

 

控制台输出

猜你喜欢

转载自www.cnblogs.com/chuijingjing/p/9838592.html