springMVC数据绑定、类型转换

来源:互联网 发布:cp linux 命令目录 编辑:程序博客网 时间:2024/05/21 10:47

 

基于注解的springMVC处理方法的参数是比较随意的,与位置顺序、参数数量是没有关系的,只要类型对应

 

一、ServletRequest/HttpServletRequest 和ServletResponse/HttpServletResponse

  

/** * 删除User对象,支持post和get两种方式请求 * @param user * @return */@RequestMapping(value="/delUserAction", method={RequestMethod.POST,RequestMethod.GET})public String delUserAction(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("user") User user){log.info("delUserAction");log.info(user.getName());//跳转到成功success.jsp界面//return "success";//重定向到list展示界面,再次发送请求return "redirect:/function1/user/list.do";}

 

1、支持get、post两种类型的请求方式

2、用户提交的表单请求会与User类型对应,保证表单的名称和User类的属性对应

3、映射方法返回的是字符串,redirect表明是重定向到 /function1/user/list.do,会再次发送请求,页面最终跳转到/function1/user/list.do方法指定的页面。

 

@RequestMapping(value = "/commandObject", method = RequestMethod.GET)public String toCreateUser(HttpServletRequest request, UserModel user) {return "customer/create";}

 

 备注:返回的没有redirect,页面跳转到指定目录的下customer目录下create.jsp文件

<!-- ViewResolver 视图解析类 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"value="org.springframework.web.servlet.view.JstlView" /><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean>

 

页面跳转到/WEB-INF/jsp/customer/create.jsp页面

 

二、InputStream/OutputStream 和Reader/Writer

 

public void inputOrOutBody(InputStream requestBodyIn, OutputStream responseBodyOut)throws IOException {responseBodyOut.write("success".getBytes());}

 备注:输入和输出流对应的是request和response方法获取的对象。

 

 

public String requestparam4(@RequestParam(value="username",required=false) String username)
 

 

即通过@RequestParam("username")明确告诉Spring Web MVC使用username进行入参。

 

表示请求中可以没有名字为username 的参数,如果没有默认为null,此处需要注意如下几点:

    原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。

    Boolean包装类型类型:默认Boolean.FALSE,其他引用类型默认为null。

 

 

public String requestparam5(@RequestParam(value="username", required=true, defaultValue="zhang") String username)
 表示如果请求中没有名字为username 的参数,默认值为“zhang”。

 

 

 

如果请求中有多个同名的应该如何接收呢?如给用户授权时,可能授予多个权限,首先看下如下代码:

 

public String requestparam7(@RequestParam(value="role") String roleList)
 

 

如果请求参数类似于url?role=admin&role=user,则实际roleList 参数入参的数据为“admin,user”,即多个数据之间

使用“,”分割;我们应该使用如下方式来接收多个请求参数:

 

public String requestparam7(@RequestParam(value="role") String[] roleList)public String requestparam8(@RequestParam(value="list") List<String> list)
 

 

 @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。代码在PathVariableTypeController 中。

 

 

原创粉丝点击