好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java超详细讲解SpringMVC如何获取请求数据

1.获得请求参数

客户端请求参数的格式是:name=value&name=value… … 服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数:

1)基本类型参数:  

Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配。

?

1

2

3

4

5

6

7

//http://localhost:8080/project/quick9?username=zhangsan&age=12

@RequestMapping ( "/quick9" )

@ResponseBody

public void quickMethod9(String username, int age) throws IOException {

     System.out.println(username);

     System.out.println(age);

}

2)POJO类型参数:

Controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配。

?

1

2

3

4

5

6

7

8

9

10

11

//http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12

public class User {

     private String username;

     private int age;

     getter/setter…

}

@RequestMapping ( "/quick10" )

@ResponseBody

public void quickMethod10(User user) throws IOException {

     System.out.println(user);

}

3)数组类型参数  

Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配。

?

1

2

3

4

5

6

//http://localhost:8080/project/quick11?strs=111&strs=222&strs=333

@RequestMapping ( "/quick11" )

@ResponseBody

public void quickMethod11(String[] strs) throws IOException {

     System.out.println(Arrays.asList(strs));

}

4)集合类型参数  

获得集合参数时,要将集合参数包装到一个POJO中才可以。

?

1

2

3

4

5

6

7

< form action = "${pageContext.request.contextPath}/quick12" method = "post" >

  < input type = "text" name = "userList[0].username" >< br >

  < input type = "text" name = "userList[0].age" >< br >

  < input type = "text" name = "userList[1].username" >< br >

  < input type = "text" name = "userList[1].age" >< br >

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

</ form >

?

1

2

3

4

5

@RequestMapping ( "/quick12" )

@ResponseBody

public void quickMethod12(Vo vo) throws IOException {

     System.out.println(vo.getUserList());

}

      当使用 ajax提交时,可以指定 contentType为json形式,那么在方法参数位置使用@RequestBody可以 直接接收集合数据而无需使用POJO进行包装。

?

1

2

3

4

5

6

7

8

9

10

11

12

<script>

//模拟数据

var userList = new Array();

userList.push({username: "zhangsan" ,age: "20" });

userList.push({username: "lisi" ,age: "20" });

$.ajax({

type: "POST" ,

url: "/itheima_springmvc1/quick13" ,

data: JSON.stringify(userList),

contentType : 'application/json;charset=utf-8'

});

</script>

?

1

2

3

4

5

6

@RequestMapping ( "/quick13" )

@ResponseBody

public void quickMethod13( @RequestBody List<User> userList) throws

IOException {

     System.out.println(userList);

}

注意: 通过谷歌开发者工具抓包发现,没有加载到jquery文件,原因是SpringMVC的前端控制器 DispatcherServlet的url-pattern配置的是/,代表对所有的资源都进行过滤操作,我们可以通过以下两种方式指定放行静态资源: • 在spring-mvc.xml配置文件中指定放行的资源

?

1

< mvc:resources mapping = "/js/**" location = "/js/" />

• 或者使用<mvc:default-servlet-handler/>标签  

2.请求乱码问题

当post请求时,数据会出现乱码,我们可以在web.xml设置一个过滤器来进行编码的过滤。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

<!--资源过滤器-->

     < 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 >

当请求的参数名称与Controller的业务方法参数名称不一致时,就需要通过@RequestParam注解显示的绑定。

?

1

2

3

4

< form action = "${pageContext.request.contextPath}/quick14" method = "post" >

  < input type = "text" name = "name" >< br >

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

</ form >

3.参数绑注解@RequestParam???????

注解@RequestParam还有如下参数可以使用:

value: 请求参数名称
required: 此在指定的请求参数是否必须包括,默认是true,提交时如果没有此参数则报错
defaultValue: 当没有指定请求参数时,则使用指定的默认值赋值

?

1

2

3

4

5

6

@RequestMapping ( "/quick14" )

@ResponseBody

public void quickMethod14( @RequestParam (value= "name" ,required =

false ,defaultValue = "defaultname" ) String username) throws IOException {

System.out.println(username);

}

4.获得Restful风格的参数

Restful是一种软件 架构风格、 设计风格,而不是标准,只是提供了一组设计原则和约束条件。主要用于客户端和服务 器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制等。  

Restful风格的请求是使用 [url+请求方式]表示一次请求目的的,HTTP 协议里面四个表示操作方式的动词如下:

GET : 获取资源
DELETE: 删除资源
PUT: 更新资源
POST: 新建资源

例如:

/user/1 GET : 得到 id = 1 的 user
/user/1 DELETE: 删除 id = 1 的 user
/user/1 PUT: 更新 id = 1 的 user
user POST: 新增 user??????????????

上述url地址/user/1中的1就是要获得的请求参数,在SpringMVC中可以使用占位符进行参数绑定。地址/user/1可以写成 /user/{id},占位符{id}对应的就是1的值。在业务方法中我们可以使用@PathVariable注解进行占位符的匹配获取工作。

?

1

2

3

4

5

6

//http://localhost:8080/itheima_springmvc1/quick19/zhangsan

@RequestMapping ( "/quick19/{name}" )

@ResponseBody

public void quickMethod19( @PathVariable (value = "name" ,required = true ) String name){

System.out.println(name);

}

5.自定义类型转换器

虽然SpringMVC 默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成int型进行参数设置。 但是不是所有的数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自 定义转换器。

自定义类型转换器的开发步骤:

① 定义转换器类实现Converter接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

public class DateConverter implements Converter<String, Date> {

     @Override

     public Date convert(String source) {

         SimpleDateFormat format= new SimpleDateFormat( "yyyy-MM-dd" );

         Date date = null ;

         try {

             date = format.parse(source);

         } catch (ParseException e) {

             e.printStackTrace();

         }

         return date;

     }

}

② 在spring-mvc.xml配置文件中声明转换器

?

1

2

3

4

5

6

7

8

<!--配置自定义转换器-->

     < bean id = "conversionService" class = "org.springframework.context.support.ConversionServiceFactoryBean" >

         < property name = "converters" >

             < list >

                 < bean class = "converter.DateConverter" />

             </ list >

         </ property >

     </ bean >

③ 在<annotation-driven>中引用转换器

?

1

2

<!--注解驱动-->

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

6.获得请求头

@RequestHeader

使用@RequestHeader可以获得请求头信息,相当于web阶段学习的request.getHeader(name) @RequestHeader注解的属性如下:

value 请求头的名称
required 是否必须携带此请求头

?

1

2

3

4

5

6

@RequestMapping ( "/quick17" )

@ResponseBody

public void quickMethod17( @RequestHeader (value = "User-Agent" ,required = false ) String

headerValue){

     System.out.println(headerValue);

}

@CookieValue  

使用@CookieValue可以获得指定Cookie的值

@CookieValue注解的属性如下:

value 指定cookie的名称
required 是否必须携带此cookie

?

1

2

3

4

5

@RequestMapping ( "/quick18" )

@ResponseBody

public void quickMethod18( @CookieValue (value = "JSESSIONID" ,required = false ) String jsessionid){

     System.out.println(jsessionid);

}

7.文件上传

文件上传客户端三要素:

表单项type=[file] 表单的提交方式是post 表单的enctype属性是多部分表单形式,及enctype=[multipart/form-data]??????????????

?

1

2

3

4

5

6

< form action = "${pageContext.request.contextPath}/quick20" method = "post"

enctype = "multipart/form-data" >

名称:< input type = "text" name = "name" >< br >

文件:< input type = "file" name = "file" >< br >

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

</ form >

文件上传步骤

① 在pom.xml导入fileupload和io坐标

?

1

2

3

4

5

6

7

8

9

10

11

<!--文件下载-->

     < dependency >

       < groupId >commons-fileupload</ groupId >

       < artifactId >commons-fileupload</ artifactId >

       < version >1.4</ version >

     </ dependency >

     < dependency >

       < groupId >commons-io</ groupId >

       < artifactId >commons-io</ artifactId >

       < version >2.6</ version >

     </ dependency >

② 配置文件上传解析器

?

1

2

3

4

< bean id = "multipartResolver" class = "org.springframework.web.multipart测试数据mons.CommonsMultipartResolver" >

         < property name = "defaultEncoding" value = "UTF-8" />

         < property name = "maxUploadSize" value = "500000" />

     </ bean >

③ 编写文件上传代码

?

1

2

3

4

5

6

7

8

9

10

11

12

@RequestMapping ( "/quick8" )

     @ResponseBody

     public void save8(String name, MultipartFile uploadfile) {

         System.out.println( "save8 running..." );

         System.out.println(name);

         String filename = uploadfile.getOriginalFilename();

         try {

             uploadfile.transferTo( new File( "D:\\upload\\" +filename));

         } catch (IOException e) {

             e.printStackTrace();

         }

     }

8.小结

MVC实现数据请求参数配置

基本类型参数 POJO类型参数 数组类型参数 集合类型参数???????

MVC获取请求数据处理

中文乱码问题 @RequestParam 和 @PathVariable 获得Servlet相关API @RequestHeader 和 @CookieValue 文件上传

到此这篇关于Java超详细讲解SpringMVC如何获取请求数据的文章就介绍到这了,更多相关Java SpringMVC 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/qq_52360069/article/details/123804314

查看更多关于Java超详细讲解SpringMVC如何获取请求数据的详细内容...

  阅读:19次