在spring的一个controller中要把参数传到页面,只要配置视图解析器,把参数添加到model中,在页面用el表达式就可以取到。但是,这样使用的是forward方式,浏览器的地址栏是不变的,如果这时候浏览器f5刷新,就会造成表单重复提交的情况。所以,我们可以使用重定向的方式,改变浏览器的地址栏,防止表单因为刷新重复提交。
jsp文件:
pageencoding="utf-8"%>
login账号:
密码:
controller:
package com.demo.controller;
import java.util.map;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
/**
* @author lpj
* @date 2016年7月10日
*/
@controller
@requestmapping("/user")
public class democontroller {
@requestmapping("/login")
public string login(@requestparam map user, model model) {
system.out.println("用户提交了一次表单");
string username;
if (user.get("name").isempty()) {
username = "tom";
} else {
username = user.get("name");
}
model.addattribute("msg", username);
// return "home";//此方式跳转,页面刷新会重复提交表单
return "redirect:/home.jsp";
}
}
由于重定向相当于2次请求,所以无法把参数加在model中传过去。在上面例子中,页面获取不到msg参数。要想获取参数,可以手动拼url,把参数带在后面。
spring 3.1 提供了一个很好用的类:redirectattributes。 使用这个类,我们可以把参数随着重定向传到页面,不需自己拼url了。
把上面方法参数中的model换成redirectattributes,参数就自动跟在url后了。
但是,这样页面不能用el获取到,还要另外处理,所以,我们还有一种方式,不拼url,用el获取参数,就像普通转发一样。
还是使用redirectattributes,但是这次不用addattribute方法,spring为我们准备了新方法,addflashattribute()。
这个方法原理是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢失。
package com.demo.controller;
import java.util.map;
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;
import org.springframework.web.servlet.mvc.support.redirectattributes;
/**
* @author lpj
* @date 2016年7月10日
*/
@controller
@requestmapping("/user")
public class democontroller {
@requestmapping("/login")
// public string login(@requestparam map user, model model) {
public string login(@requestparam map user, redirectattributes model) {
system.out.println("用户提交了一次表单");
string username;
if (user.get("name").isempty()) {
username = "tom";
} else {
username = user.get("name");
}
model.addflashattribute("msg", username);
// return "home";//此方式跳转,页面刷新会重复提交表单
return "redirect:/user/tohome";
}
@requestmapping("/tohome")
public string home(@modelattribute("msg") string msg, model model) {
system.out.println("拿到重定向得到的参数msg:" + msg);
model.addattribute("msg", msg);
return "home";
}
}
这边我们使用@modelattribute注解,获取之前addflashattribute添加的数据,之后就可以正常使用啦。
需要例子代码的可以点此下载:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。
希望与广大网友互动??
点此进行留言吧!