SpringMVC-------2.接受参数,保存数据和返回数据

1.springmvc接受参数

1.1直接把表单的参数写在Controller相应的方法的形参中

  SpringMVC-------2.接受参数,保存数据和返回数据

 SpringMVC-------2.接受参数,保存数据和返回数据

 1.2 通过HttpServletRequest接收

SpringMVC-------2.接受参数,保存数据和返回数据

 1.3通过一个bean来接收,post方式和get方式都可以。

  创建user实体类

SpringMVC-------2.接受参数,保存数据和返回数据

 SpringMVC-------2.接受参数,保存数据和返回数据

1.4用注解@RequestParam绑定请求参数到方法入参

当表单元素的name属性和方法参数名不同时,通过@RequestParam来绑定参数

SpringMVC-------2.接受参数,保存数据和返回数据

 1.5当接收的参数是时间类型的参数

 1.5.1接收单个时间参数,在controller中添加initBinder注解

@InitBinder

    public void initBinder(ServletRequestDataBinder binder){

//只要网页中传来的数据格式为yyyy-MM-dd 就会转化为Date类型

        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),

                true));

    }

1.5.2当接收对象中含有时间类型属性,使用@DateTimeFormat注解

SpringMVC-------2.接受参数,保存数据和返回数据

 2.controller进行数据保存

2.1使用ModelAndView对象保存,方法的返回值必须为ModelAndView类型,作用域为Request

SpringMVC-------2.接受参数,保存数据和返回数据

 2.2使用Model, 方法的返回值还是字符串类型,作用域为Request

SpringMVC-------2.接受参数,保存数据和返回数据

 2.3 使用Map.方法的返回值还是字符串类型,作用域为Request

SpringMVC-------2.接受参数,保存数据和返回数据

 2.4使用HttpServletRequest或者HttpSession保存

2.5使用注解@SessionAttributes(name={key1,key2})

3.springmvc的controller返回数据

controller中的方法一般返回字符串或者ModelAndView类型,这里会返回给视图解析器,然后视图解析器获得访问地址;

当只想让controller中的方法只返回数据,不进行跳转时,需要加上注解@ResponseBody,将Java对象转化为jsp可以识别的json对象

使用方式:

导包:

SpringMVC-------2.接受参数,保存数据和返回数据

 添加注解:

SpringMVC-------2.接受参数,保存数据和返回数据

 注意:这里controller也是可以直接返回String类型,但时Sting中只允许英文字符,中文字符会报错。

原因和解决方法如下:

默认加载驱动时加载的字符串解析器的默认编码为“iso8859-1”

SpringMVC-------2.接受参数,保存数据和返回数据

 SpringMVC-------2.接受参数,保存数据和返回数据

 SpringMVC-------2.接受参数,保存数据和返回数据

 需要手动设置加载驱动时字符串解析器的构造方法为有参构造函数,参数为需要设置的编码格式

SpringMVC-------2.接受参数,保存数据和返回数据

 SpringMVC-------2.接受参数,保存数据和返回数据