springMVC(6)---处理模型数据

之前一篇博客,写个怎么获取前段数据:springMVC(2)---获取前段数据,这篇文章写怎么从后端往前端传入数据。

模型数据类型

SpringMVC 提供了以下几种途径输出模型数据:

  – ModelAndView: 处理方法返回值类型为 ModelAndView时, 方法体即可通过该对象添加模型数据
  – Map及Model:入参为org.springframework.ui.Model、org.springframework.ui.ModelMap 或 Java.uti.Map 时,处理方法返回时,Map中的数据会自动添加到模型中。
  – @SessionAttributes: 将模型中的某个属性暂存到HttpSession 中,以便多个请求之间可以共享这个属性
  – @ModelAttribute: 方法入参标注该注解后, 入参的对象就会放到数据模型中。

一.ModelAndView

目标方法的返回值可以是ModelAndView类型,其中可以包含视图和模型信息

springmvc会把ModelAndView的model中数据放在request域对象中

@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
private static final String SUCCESS = "success";
/**
* 目标方法的返回值可以是ModelAndView类型
* 其中可以包含视图和模型信息
* springmvc会把ModelAndView的model中数据放在request域对象中
* @return*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName=SUCCESS;
//添加模型视图
ModelAndView modelAndView=new ModelAndView(viewName);
//添加模型数据到ModelAndView中
modelAndView.addObject("time", new Date());
return modelAndView;
}

 index.jsp

 <a href="springmvc/testModelAndView">Test ModelAndView<a>

success.jsp

<html>
<h4>Success Page</h4>
time:${requestScope.time}
</html>

二.Map 及 Model

入参为org.springframework.ui.Model、org.springframework.ui.ModelMap 或 java.uti.Map 时,处理方法返回时,Map 中的数据会自动添加到模型中

 Controller类

     @RequestMapping("/testMap")
public String testMap(Map<String, Object> map)
{
map.put("names", Arrays.asList("tom", "jerry", "mike"));
return "success";

  index.jsp

<a href="springmvc/testMap">Test Map</a>

  success.jsp

map: ${requestScope.names }

界面

三.@SessionAttributes

如果希望在多个请求之间共用某个模型属性数据,则可以在控制器类标注一个 @SessionAttributes,SpringMVC 会将模型中对应的属性暂存到 HTTPSession 中。

@SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外,还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中。

1. @SessionAttributes(types=User.class)会将隐含模型中所有类型为 User 的属性添加到会话中

2. @SessionAttributes(value={"user1", "user2"})将名为 user1 和 user2 的模型属性添加到会话中

3. @SessionAttributes(types={"User.class", "Dept.class"})将模型中所有类型为 User 及 Dept 的属性添加到会话中

4. @SessionAtributes(value={"user1", "user2"}, types={Dept.class})将名为 user1 和 user2 的模型属性添加到会话中,同时将所有类型为 Dept 的模型属性添加到会话中

  controller类

//SessionAttributes只能放在类上,不能在方法上
@SessionAttributes(value={"user"}, types={String.class})
@RequestMapping("/springmvc")
@Controller
public class SessionController
{
private static final String SUCCESS = "success";   @RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Map<String, Object> map)
{
User user = new User("Jack", "123");
map.put("user", user);
map.put("msg", "hello");
return SUCCESS;
}
}

 index.jsp

<a href="springmvc/testSessionAttributes">Test SessionAttributes</a>

 success.jsp

 request user: ${requestScope.user }

 request msg: ${requestScope.msg }

 session user: ${sessionScope.user }

 session msg: ${sessionScope.msg }

最终request和session都有相应值,由此我们可以得出:

被 @SessionAttributes 注解修饰后,模型属性不仅存在于请求域还存在于会话域。除了可以通过value属性值指定需要放到会话中的属性外,还可以根据types属性值指定哪些类型的模型属性需要放到会话中。

四.@ModelAttribute

     @ModelAttribute注解只支持一个属性value,类型是为String,代表绑定的属性名称。

     @ModelAttribute会优先于@RequestMapping执行,也会在Controller中每个方法执行前被执行,所以当一个Controller中有映射到多个Url时,需要谨慎使用

(1)先讲下基本理解,网上讲的无非就那么几种

     @ModelAttribute
public void myModel3(Model model) {
model.addAttribute("name", "SHANHY");
model.addAttribute("age", "28");
} /**
* 这个相当于 model.addAttribute("name", name);
*/
@ModelAttribute("name")
public String userModelfirst(@RequestParam("name") String name){
return name;
} /**
* 这个相当于 model.addAttribute("string", name);
* 因为你自己没有设置model的key值,所以它会默认value的类型第一个字母小写作为key值
* 如果你是User对象,那它会默认key值为"user",这个在实际开发中并不适用
* 因为太局限了,我们很难接受 key 为 string、int、user 等等这样的。
*/
@ModelAttribute
public String myModel1(@RequestParam(required = false) String name) {
return name;
}

(2)RequestMapping方法中取ModelAttribute方法中的值

    modelattr.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<body>
<!-- 这里我输入用户名:李四 密码:5678 -->
<form action="modelattr/test1">
<label>用户名:</label>
<input type="text" id="name" name="name"></input><br><br>
<label>密码:</label>
<input type="text" id="pwd" name="pwd"></input><br><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>

 ModelAttrController类

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; @Controller
@RequestMapping(value="/modelattr")
public class ModelAttrController { @ModelAttribute
public void Model1(Model model) {
model.addAttribute("name", "张三");
model.addAttribute("pwd", "1234");
} /**
* test1方法中,有两个值是通过Model1方法中放入的
* 有两个值是通过前端获取的我们看后台打印结果
*/
@RequestMapping(value="/test1")
public String test1(
@ModelAttribute("name") String str2,
@ModelAttribute("pwd") String str3,
@RequestParam("name") String name,
@RequestParam("pwd") String pwd) { System.out.println("name="+str2+",pwd="+str3);
System.out.println("name="+name+",pwd="+pwd); return null;
}
}

后台打印结果:

(3)有关更新,具体看案例

modelPerson.jsp

<html>
<body>
<!--
模拟修改操作
1. 原始数据为: 1, zhangsan, 123456,12
2. 密码不能被修改.
3. 表单回显, 模拟操作直接在表单填写对应的属性值
-->
<form action="modelattr/person" method="Post">
<input type="hidden" name="id" value="1"/>
name: <input type="text" name="name" value="zhangsan"/>
<br>
age: <input type="text" name="age" value="12"/>
<br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

ModelAttrController类

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ssm.model.Person; @Controller
@RequestMapping(value="/modelattr")
public class ModelAttrController { /**
*1: 因为password我在界面上是没有输入的,所以我通过id去数据库找到这条数据,就能获得它的password
*2:Person领域对象就id name password age 四个属性都是String形
*/
@ModelAttribute
public void getUser(@RequestParam(value="id",required=false) String id,
Map<String, Object> map){
if(id != null){
//模拟从数据库中获取对象
Person person = new Person("1", "lisi", "123456", "24");
System.out.println("从数据库中获取一个对象: " + person);
map.put("person", person);
}
} @RequestMapping(value="/person", method=RequestMethod.POST)
public String testModelAttribute(Person person){
System.out.println("修改: " + person); return null;
}
/*
* 总结几点:
* 1:map.put("person", person);中的key值,一定要和Person person中的形参一致,否则报错
* 2:如果去掉@ModelAttribute注解和getUser方法,直接testModelAttribute(Person person)会报错
* java.lang.NoSuchMethodException: com.ssm.model.Person.<init>()
* 3:最后修改的那个person其实就是从数据库中和前端界面传来的集合体,就是说如果前端有值那就覆盖数据库中对于
* 属性的值,如果前段没有值那就还是用数据库中属性的值
*/ }

 后台打印结果

(4)@ModelAttribute和@RequestMapping同时注释的有返回值的方法

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; @Controller
@RequestMapping(value="/modelattr")
public class ModelAttrController { @ModelAttribute(value="username")
@RequestMapping("/person")
public String login(@RequestParam("name") String name){ return name;
}
/**
* 这种情况比较有意思:以前return name;都是作为返回路径
* 现在它变成了value值
* model.addAttribute("username", name);
* 那它的映射还是@RequestMapping中的value值这里指:modelattr/person
* 我之前路径为:http://localhost:8080/ssm/modelattr/person
* 那么返回路径为:http://localhost:8080/ssm/WEB-INF/jsp/modelattr/person.jsp
*/ }

先看WEB-INF/jsp/modelattr/person.jsp

内容

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
</head>
<body>
<h1>Person返回成功</h1>
</body>
</html>

最后我们看界面

有关处理模型数据就讲到这了,如果哪里讲的不周全也欢迎多多指教。

想的太多,做的太少,中间的落差就是烦恼,要么去做,要么别想 少尉【13】

springMVC(6)---处理模型数据的更多相关文章

  1. SpringMvc:处理模型数据

    SpringMvc提供了以下途径输出模型数据: -ModelAndView:处理方法返回值类型为ModelAndView,方法体即可通过该对象添加模型数据 -Map或Model:入参为org.spri ...

  2. SpringMVC(十二):SpringMVC 处理输出模型数据之@ModelAttribute

    Spring MVC提供了以下几种途径输出模型数据:1)ModelAndView:处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据:2)Map及Model:处理方法入参 ...

  3. SpringMVC(九):SpringMVC 处理输出模型数据之ModelAndView

    Spring MVC提供了以下几种途径输出模型数据: 1)ModelAndView:处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据: 2)Map及Model:处理方法 ...

  4. SpringMVC(十一):SpringMVC 处理输出模型数据之SessionAttributes

    Spring MVC提供了以下几种途径输出模型数据:1)ModelAndView:处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据:2)Map及Model:处理方法入参 ...

  5. SpringMVC(十):SpringMVC 处理输出模型数据之Map及Model

    Spring MVC提供了以下几种途径输出模型数据: 1)ModelAndView:处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据: 2)Map及Model:处理方法 ...

  6. Spring MVC 处理模型数据(@ModelAttribute)

    SpringMVC中的模型数据是非常重要的,因为MVC中的控制(C)请求处理业务逻辑来生成数据模型(M),而视图(V)就是为了渲染数据模型的数据. 直白来讲,上面这句话的意思就是:当有一个查询的请求, ...

  7. springmvc学习(五)——处理模型数据

    Spring MVC 提供了以下几种途径输出模型数据: ModelAndView: 处理方法返回值类型为 ModelAndView 时, 方法体即可通过该对象添加模型数据Map 及 Model: 入参 ...

  8. SpringMVC(十五) RequestMapping map模型数据

    控制器中使用map模型数据,传送数据给视图. 控制器参考代码: package com.tiekui.springmvc.handlers; import java.util.Arrays; impo ...

  9. SpringMVC系列(六)处理模型数据

    Spring MVC 提供了以下几种途径输出模型数据:  ModelAndView: 处理方法返回值类型为 ModelAndView时, 方法体即可通过该对象添加模型数据  Map 及 Model: ...

随机推荐

  1. C# 通过反射初探ORM框架的实现原理

    背景: 以前学的Java进行开发,多用到Mybatis,Hiberante等ORM框架,最近需要上手一个C#的项目,由于不是特别难,也不想再去学习C#的ORM框架,所以就想着用反射简单的实现一下ORM ...

  2. 如何简单愉快的上手PipelineDB

    pipelineDB source:https://github.com/pipelinedb/pipelinedb 安装PipelineDB ./configure CFLAGS="-g ...

  3. Android自定义processor实现bindView功能

    一.简介 在现阶段的Android开发中,注解越来越流行起来,比如ButterKnife,Retrofit,Dragger,EventBus等等都选择使用注解来配置.按照处理时期,注解又分为两种类型, ...

  4. lua游戏开发实践指南学习笔记1

    本文是依据lua游戏开发实践指南做的一些学习笔记,仅用于继续自己学习的一些知识. Lua基础 1.  语言定义: 在lua语言中,标识符有非常大的灵活性(变量和函数名),只是用户不呢个以数字作为起始符 ...

  5. SQL或HQL预编译语句,可以防止SQL注入,可是不能处理%和_特殊字符

    近期项目在做整改,将全部DAO层的直接拼接SQL字符串的代码,转换成使用预编译语句的方式.个人通过写dao层的单元測试,有下面几点收获. dao层代码例如以下 //使用了预编译sql public L ...

  6. Implement Queue using Stacks(用栈实现队列)

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

  7. [前端] jquery验证手机号、身份证号、中文名称

    验证: 中文姓名.手机号.身份证和地址 HTML(表单): <form action=""> <div class="form-group"& ...

  8. android apk 的root 权限和USB adb 权限的差别

    USB adb 权限是指,当adb 连接手机时,手机中的守护进程adbd 的权限为root 权限,从而它的子进程也具有root 权限.通常假设adb shell 看到是: Android 4.0 以后 ...

  9. 爬虫新手学习2-爬虫进阶(urllib和urllib2 的区别、url转码、爬虫GET提交实例、批量爬取贴吧数据、fidder软件安装、有道翻译POST实例、豆瓣ajax数据获取)

    1.urllib和urllib2区别实例 urllib和urllib2都是接受URL请求相关模块,但是提供了不同的功能,两个最显著的不同如下: urllib可以接受URL,不能创建设置headers的 ...

  10. 【 全干货 】5 分钟带你看懂 Docker !

    欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 作者丨唐文广:腾讯工程师,负责无线研发部地图测试. 导语:Docker,近两年才流行起来的超轻量级虚拟机,它可以让你轻松完成持续集成.自动交付 ...