springMVC-接收数据-参数绑定

接收数据-参数绑定

#Method Arguments概观

Same in Spring WebFlux

The table below shows supported controller method arguments. Reactive types are not supported for any arguments.

下表显示支持的控制器方法参数。 任何参数都不支持反应类型。

Controller method argument

Description

WebRequest, NativeWebRequest

通用访问请求参数,请求和会话属性,不需要直接使用Servlet API。

javax.servlet.ServletRequest, javax.servlet.ServletResponse

选择任何特定的请求或响应类型 - 例如 ServletRequest,HttpServletRequest或Spring的MultipartRequest,MultipartHttpServletRequest。

javax.servlet.http.HttpSession

强制进行会话。 结果,这样的论证永远不会为空。

注意:会话访问不是线程安全的。 如果允许多个请求同时访问会话,请考虑将RequestMappingHandlerAdapter的“synchronizeOnSession”标志设置为“true”。

javax.servlet.http.PushBuilder

用于编程式HTTP / 2资源推送的Servlet 4.0 push builder API。 请注意,根据Servlet规范,如果客户端不支持HTTP / 2功能,则注入的PushBuilder实例可以为null。

java.security.Principal

Currently authenticated user; possibly a specific Principal implementation class if known.

目前已通过身份验证 如果知道的话可能是一个特定的主体实现类

HttpMethod

The HTTP method of the request.

java.util.Locale

The current request locale, determined by the most specific LocaleResolver available, in effect, the configured LocaleResolver/LocaleContextResolver.

他当前的请求语言环境,由最具体的LocaleResolver确定,实际上是配置的LocaleResolver / LocaleContextResolver。

java.util.TimeZone + java.time.ZoneId

The time zone associated with the current request, as determined by a LocaleContextResolver.

与当前请求关联的时区,由LocaleContextResolver确定

java.io.InputStream, java.io.Reader

For access to the raw request body as exposed by the Servlet API.

用于访问由Servlet API公开的原始请求主体。

java.io.OutputStream, java.io.Writer

For access to the raw response body as exposed by the Servlet API.

用于访问由Servlet API公开的原始响应主体。

@PathVariable

For access to URI template variables. See URI patterns.

用于访问URI模板变量。 请参阅URI模式。

@MatrixVariable

For access to name-value pairs in URI path segments. See Matrix variables.

用于访问URI路径段中的名称/值对。 请参阅矩阵变量。

@RequestParam

For access to Servlet request parameters. Parameter values are converted to the declared method argument type. See @RequestParam.

Note that use of @RequestParam is optional, e.g. to set its attributes. See "Any other argument" further below in this table.
用于访问Servlet请求参数。 参数值被转换为声明的方法参数类型。 请参阅@RequestParam。

请注意,使用@RequestParam是可选的,例如, 设置其属性。 请参阅本表下面的“任何其他参数”。

主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter("name"),

它有三个常用参数:

defaultValue = "0", required = false, value = "isApp";

defaultValue 表示设置默认值,

required 铜过boolean设置是否是必须要传入的参数,

value 值表示接受的传入的参数类型。

 @RequestParam将请求的参数绑定到方法中的参数上,如下面的代码所示。其实,即使不配置该参数,注解也会默认使用该参数。如果想自定义指定参数的话,如果将@RequestParam的 required 属性设置为false(如@RequestParam(value="id",required=false))。

@RequestHeader

For access to request headers. Header values are converted to the declared method argument type. See @RequestHeader.

用于访问请求标题。 标题值被转换为声明的方法参数类型。 请参阅@RequestHeader。

@CookieValue

For access to cookies. Cookies values are converted to the declared method argument type. See @CookieValue.

用于访问cookie。 Cookies值被转换为声明的方法参数类型。 请参阅@CookieValue。

@RequestBody

For access to the HTTP request body. Body content is converted to the declared method argument type using HttpMessageConverters. See @RequestBody.

用于访问HTTP请求主体。 使用HttpMessageConverters将主体内容转换为声明的方法参数类型。 请参阅@RequestBody。

请求的body体的绑定(通过HttpMessageConverter进行类型转换);

作用: 该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

HttpEntity<B>

For access to request headers and body. The body is converted with HttpMessageConverters. See HttpEntity.

用于访问请求标头和正文。 正文使用HttpMessageConverters进行转换。 请参阅HttpEntity。

@RequestPart

For access to a part in a "multipart/form-data" request. See Multipart.

用于访问“multipart / form-data”请求中的部分。 见多部分。

java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMap

For access to the model that is used in HTML controllers and exposed to templates as part of view rendering.

用于访问HTML控制器中使用的模型,并将其作为视图渲染的一部分展示给模板。

RedirectAttributes

Specify attributes to use in case of a redirect — i.e. to be appended to the query string, and/or flash attributes to be stored temporarily until the request after redirect. See Redirect attributes and Flash attributes.

指定要重定向时使用的属性 - 即要追加到查询字符串,和/或临时存储的闪存属性,直到重定向后的请求。 请参阅重定向属性和Flash属性。

@ModelAttribute

For access to an existing attribute in the model (instantiated if not present) with data binding and validation applied. See @ModelAttribute as well as Model and DataBinder.

Note that use of @ModelAttribute is optional, e.g. to set its attributes. See "Any other argument" further below in this table.

用于访问模型中的现有属性(如果不存在,则实例化),并应用数据绑定和验证。 请参阅@ModelAttribute以及Model和DataBinder。

请注意,@ModelAttribute的使用是可选的,例如 设置其属性。 请参阅本表下面的“任何其他参数”。

Errors, BindingResult

For access to errors from validation and data binding for a command object (i.e. @ModelAttribute argument), or errors from the validation of an @RequestBody or @RequestPart arguments; an Errors, or BindingResult argument must be declared immediately after the validated method argument.

用于访问命令对象(即@ModelAttribute参数)的验证和数据绑定中的错误,或来自验证@RequestBody或@RequestPart参数的错误; 必须在验证的方法参数后立即声明Errors或BindingResult参数。

SessionStatus+class-level @SessionAttributes

For marking form processing complete which triggers cleanup of session attributes declared through a class-level @SessionAttributes annotation. See @SessionAttributes for more details.

用于标记表单处理完成,触发清理通过类级别@SessionAttributes注释声明的会话属性。 有关更多详细信息,请参阅@SessionAttributes

UriComponentsBuilder

For preparing a URL relative to the current request’s host, port, scheme, context path, and the literal part of the servlet mapping also taking into account Forwarded and X-Forwarded-* headers. See URI Links.

用于准备相对于当前请求的主机,端口,方案,上下文路径以及servlet映射的文字部分的URL,同时也考虑了转发和X-Forwarded- *标头。 请参阅URI链接。

@SessionAttribute

For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level @SessionAttributes declaration. See @SessionAttribute for more details.

用于访问任何会话属性; 与通过类级别@SessionAttributes声明存储在会话中的模型属性相反。 有关更多详细信息,请参阅@SessionAttribute。

@RequestAttribute

For access to request attributes. See @RequestAttribute for more details.

用于访问请求属性。 有关更多详细信息,请参阅@RequestAttribute。

Any other argument

这个参数可以是任意类型,也可以是一个实体类,SpringMVC会自动封装

If a method argument is not matched to any of the above, by default it is resolved as an @RequestParam if it is a simple type, as determined by BeanUtils#isSimpleProperty, or as an @ModelAttribute otherwise.

如果方法参数与上述任何一个不匹配,默认情况下,它被解析为一个@RequestParam,如果它是一个简单的类型,如BeanUtils#isSimpleProperty所确定的,或者作为@ModelAttribute来确定。

 

下面是具体使用说明,几乎都是下面这种格式:

Public String (@RequestParam int id){..}

注解形式

 

@RequestParam

@RequestParam用来接收路径后面的参数 http:www.lifeibai.com?petId = 1.

一般用来处理接收的参数和形参的参数不一致的情况

value:参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名字为item_id的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;

TTP Status 400 - Required Integer parameter 'XXXX' is not present

defaultValue:默认值,表示如果请求中没有同名参数时的默认值

@Controller

@RequestMapping("/pets")

public class EditPetForm {

 

    // ...

 

    @GetMapping

    public String setupForm(@RequestParam("petId") int Id, Model model) {

        Pet pet = this.clinic.loadPet(petId);

        model.addAttribute("pet", pet);

        return "petForm";

    }

 

    // ...

}

@RequestParam(value = "id",defaultValue = "10",required = false)

defaultValue 表示设置默认值,

required 铜过boolean设置是否是必须要传入的参数,

value 值表示接受的传入的参数类型

使用@RequestParam常用于处理简单类型的绑定。

 

value:参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名字为item_id的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;

TTP Status 400 - Required Integer parameter 'XXXX' is not present

 

defaultValue:默认值,表示如果请求中没有同名参数时的默认值

 

定义如下:

public String editItem(@RequestParam(value="item_id",required=true) String id) {

      

}

 

形参名称为id,但是这里使用value=" item_id"限定请求的参数名为item_id,所以页面传递参数的名必须为item_id。

注意:如果请求参数中没有item_id将跑出异常:

HTTP Status 500 - Required Integer parameter 'item_id' is not present

 

这里通过required=true限定item_id参数为必需传递,如果不传递则报400错误,可以使用defaultvalue设置默认值,即使required=true也可以不传item_id参数值

 

@RequestHeader

@RequestHeader用来接收指定参数的请求头信息

@GetMapping("/demo")

public void handle(

        @RequestHeader("Accept-Encoding") String encoding,

        @RequestHeader("Keep-Alive") long keepAlive) {

    //...

}

 

@CookieValue

用来接收指定名称的cookie的值

@GetMapping("/demo")

public void handle(@CookieValue("JSESSIONID") String cookie) {

    //...

}

@ModelAttribute

       ModelAttribute可以应用在方法参数上或方法上,他的作用主要是当注解在方法参数上时会将注解的参数对象添加到Model中;

当注解在请求处理方法Action上时会将该方法变成一个非请求处理的方法,但其它Action被调用时会首先调用该方法。

被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,下面访问http:localhost:8080/test_project/test.action

@RestController

@SessionAttributes("user")

public class TestController {

 

    @ModelAttribute("age2")

    public String mdoeltest1(){

        System.out.println("This is ModelAttribute1 !");

        return "33";

    }

 

    @ModelAttribute("age1")

    public String mdoeltestrrr(){

        System.out.println("This is ModelAttributee1 !");

 

        return "22";

    }

 

    @RequestMapping("/test.action")

    public String test(User user ,

                       @ModelAttribute("age1") String age1 ,

                       @ModelAttribute("age2") String age2 ,

                       HttpSession session){

        Object user2 = session.getAttribute("user");

        System.out.println(user2);

        System.out.println(user);

        System.out.println("age1:"+age1);

        System.out.println("age2:"+age2);

        return "test";

    }

}

结果:

This is ModelAttributee1 !

This is ModelAttribute1 !

User{name='李四', age=22}

User{name='李四', age=22}

age1:22

age2:33

@SessionAttributes

Value={“name”,“age”} 取出name或者value、或者把model中的name,age扔到session中

Type=User。Class   将一个实体类扔到session中

这个玩意加在 类上面,然后所有的方法的参数都可以在sesssion中找,找到了就赋值。

 @SessionAttributes需要清除时,使用SessionStatus.setComplete();来清除。

1、  将model中的值,扔到session中

@Controller

@SessionAttributes(types = User.class)

public class LoginController {

 

    @RequestMapping("/login")

    public String login(HttpServletRequest req,Model model,SessionStatus status){

        User user = new User();

        user.setName("李四");

        user.setAge(22);

        model.addAttribute("user" , user);

        return "forward:test.action";

    }

}

2、  从session取出来

 

@RestController
@SessionAttributes("user")
public class TestController {
    @RequestMapping("/test.action")
    public String  test(User user, HttpSession session){
        Object user2 = session.getAttribute("user");
        System.out.println(user2);
        System.out.println(user);
        return "test";
    }
}

@SessionAttribute(不能用 = =)springboot能用 - -

这玩意是加在方法上的参数的,将session中的数据赋值给参数

@RequestMapping("/")

public String handle(@SessionAttribute User user) {

    // ...

}

 

 

@RequestAttribute

这玩意是接收request域中的数据的

@GetMapping("/")

public String handle(@RequestAttribute Client client) {

    // ...

}

@RequestBody

作用:

@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。

List.action?id=1&name=zhangsan&age=12

 

本例子应用:

@RequestBody注解实现接收http请求的json数据,将json数据转换为java对象

// 商品修改提交json信息,响应json信息

    @RequestMapping("/editItemSubmit_RequestJson")

    public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {

       System.out.println(items);

       //itemService.saveItem(items);

       return items;

    }

@ResponseBody

作用:

该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

 

本例子应用:

@ResponseBody注解实现将controller方法返回对象转换为json响应给客户端

使用这个注解 ,sessionAttributes注解将会失效

@PathVariable(RESTful)

       简介

              @PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。

       用法

              @RequestMapping(value="/users/{userId}/topics/{topicId}")

public String test(

       @PathVariable(value="userId") int userId,

       @PathVariable(value="topicId") int topicId)

               如请求的URL为“控制器URL/users/123/topics/456”,则自动将URL中模板变量{userId}和{topicId}绑定到通过@PathVariable注解的同名参数上,即入参后userId=123、topicId=456。

Model/ModelMap/ModelAndView

 

ModelMap是Model接口的实现类,通过Model或ModelMap向页面传递数据,如下:

@RequestMapping("/itemEdit")

       public String itemEdit(Integer id, Model model) {

              Items items = itemService.getItemById(id);

              //向jsp传递数据

              model.addAttribute("item", items);

              //设置跳转的jsp页面

              return "editItem";

       }

 

       /*@RequestMapping("/itemEdit")

       public String editItem(HttpServletRequest request,

                     HttpServletResponse response, HttpSession session, Model model) {

              //从request中取参数

              String strId = request.getParameter("id");

              int id = new Integer(strId);

              //调用服务

              Items items = itemService.getItemById(id);

              //把结果传递给页面

              //ModelAndView modelAndView = new ModelAndView();

              //modelAndView.addObject("item", items);

              //设置逻辑视图

              //modelAndView.setViewName("editItem");

              //return modelAndView;

              //设置返回结果

              model.addAttribute("item", items);

              //返回逻辑视图

              return "editItem";

       }

       */

 

Any other argument原始参数

当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。从Request取参数的方法可以进一步简化。

@RequestMapping("/itemEdit")

       public String itemEdit(Integer id, Model model) {

              Items items = itemService.getItemById(id);

              //向jsp传递数据

              model.addAttribute("item", items);

              //设置跳转的jsp页面

              return "editItem";

       }

参数类型推荐使用包装数据类型,因为基础数据类型不可以为null

整形:Integer、int

字符串:String

单精度:Float、float

双精度:Double、double

布尔型:Boolean、boolean

说明:对于布尔类型的参数,请求的参数值为true或false。

处理方法:

public String editItem(Model model,Integer id,Boolean status) throws Exception

请求url:

http://localhost:8080/xxx.action?id=2&status=false

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。

·HttpServletRequest

通过request对象获取请求信息

HttpServletResponse

通过response处理响应信息

HttpSession

通过session对象得到session中存放的对象

s=false

posted @ 2018-05-14 17:33  里非白  阅读(963)  评论(0编辑  收藏  举报