Springmvc 前台传递参数到后台需要数据绑定

我们知道,当提交表单时,controller会把表单元素注入到command类里,但是系统注入的只能是基本类型,如int,char,String。但当我们在command类里需要复杂类型,如Integer,date,或自己定义的类时,controller就不会那么聪明了。这时,就需要我们帮助他们了。

后台controller:

@Controller
@RequestMapping(value = { "/projects/project" })
public class ProjectsController {

    @Autowired
    ProjectsService projectService;
    @Autowired
    UniskUserService userService;
    @Autowired(required = false)
    UserAndUserGroupService ugroupService;
    public static final String path = "sys/modules/project/";
    private static final Logger logger = LoggerFactory
            .getLogger(ProjectsController.class);

    /*
     * 日期绑定转化
    */
    @InitBinder
    public void initBinder(WebDataBinder binder) throws Exception {
        //Projects projects
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    setValue(sdf.parse(text));
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
        //controller

/*
* 修改子项目实现
*/
@ResponseBody
@RequestMapping(value = "editSub", method = RequestMethod.POST)
public String editSub(HttpServletRequest request,
HttpServletResponse response,
@ModelAttribute("user") UniskUser user,@ModelAttribute("projects") Projects project, ModelMap map)
throws UniskException {
projectService.update(project);
Map<String, String> result = new HashMap<String, String>();
result.put("resultCode", "0");
result.put("msg", "操作成功!");
System.out.println("edit");
return JsonUtil.toJson(result);
}

}    

前台表单:

<div class="control-group">
				<label class="control-label">项目发布时间:</label>
				<div class="controls">
					<%-- <form:input path="starttime" type="text" id="starttime" placeholder="${project.starttime }" /> --%>
					<input type="text" readonly id="starttime" name="starttime" maxlength="50" class="required times" placeholder="<fmt:formatDate value=‘${project.starttime }‘ pattern=‘yyyy-MM-dd‘/>" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">项目众筹时间:</label>
				<div class="controls">
					<%-- <form:input path="crowdtime" type="text" id="crowdtime" placeholder="${project.crowdtime }" /> --%>
					<input type="text" readonly id="crowdtime" name="crowdtime" maxlength="50" class="required times" placeholder="<fmt:formatDate value=‘${project.crowdtime }‘ pattern=‘yyyy-MM-dd‘/>" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">项目验收时间:</label>
				<div class="controls">
					<%-- <form:input path="examinetime" type="text" id="examinetime" maxlength="50" class="required times" placeholder="<fmt:formatDate value=‘${project.examinetime }‘ pattern=‘yyyy-MM-dd‘/>" />  --%>
					<input type="text" readonly id="examinetime" name="examinetime" maxlength="50" class="required times" placeholder="<fmt:formatDate value=‘${project.examinetime }‘ pattern=‘yyyy-MM-dd‘/>" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">项目结束时间:</label>
				<div class="controls">
					<%-- <form:input path="endtime" type="text" id="endtime" placeholder="${project.endtime }" />  --%>
					<input type="text" readonly id="endtime" name="endtime" maxlength="50" class="required times" placeholder="<fmt:formatDate value=‘${project.endtime }‘ pattern=‘yyyy-MM-dd‘/>" />
				</div>
			</div>

  getAsText和setAsText是要从新定义的。其中getAsText方法在get方法请求时会调用,而setAsText方法在post方法请求时会调用。

时间: 2024-12-09 16:13:22

Springmvc 前台传递参数到后台需要数据绑定的相关文章

[技术分享]20171212_后端开发_批量删除使用@requestBody注解获取前台传递参数

批量删除 难点在于前台的参数如何组织?组织完的参数后台如何接收? 我现在就把我们项目中用到的批量删除的方法整理出来,供大家参考. 先上一个通用版: var ids = new Array(); var vo = {}; vo.sequenceid = item.sequenceid; ids.push(vo); var data = JSON.stringify(ids); @RequestMapping(value="/list" method=RequestMethod.Delet

SpringMVC中,前台jsp封装参数,绑定参数,传递参数到后台controller的过程详解123

前台到后台的流程:前台jsp->后台:controller控制器层->service业务层->DAO数据访问层->数据库model模型层. 从上面流程可知,前台jsp的数据,想要参与到后台的业务逻辑运算,关键是要先把前台jsp的数据传递到后台的controller.这个关键点涉及到一个术语——“绑定参数”(或称“绑定数据”),即如何将前台jsp中的数据绑定为后台controller类里方法的参数. 在SpringMVC中,“绑定参数”这个过程,需要前台jsp和后台controlle

springmvc前台传递到controller层的中文乱码解决方法

@RequestMapping("/judge") public String judgeLogger(@RequestParam String userName, @RequestParam String password, @RequestParam String sex, RedirectAttributes redirectAttributes) { // 乱码解决方法 try { String name = new String(userName.getBytes("

SpringMVC重定向传递参数

在SpringMVC的一个controller中要把参数传到页面,只要配置视图解析器,把参数添加到Model中,在页面用el表达式就可以取到.但是,这样使用的是forward方式,浏览器的地址栏是不变的,如果这时候浏览器F5刷新,就会造成表单重复提交的情况.所以,我们可以使用重定向的方式,改变浏览器的地址栏,防止表单因为刷新重复提交. WEB-INF下web.xml文件: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD We

前台请求参数与后台方法参数一致与不一致的情况

1. 函数参数名与请求参数名保持一致 @RequestMapping("/delete")@ResponseBodypublic JsonResult delete(Long id){ 2. 函数参数名与请求参数名保持不一致 @RequestMapping(value = "/add", method = RequestMethod.POST)public AjaxResult save(@RequestBody Product product) { @Reques

springMVC通过ajax传递参数list对象或传递数组对象到后台

springMVC通过ajax传递参数list对象或传递数组对象到后台 环境: 前台传递参数到后台 前台使用ajax 后台使用springMVC 传递的参数是N多个对象 JSON对象和JSON字符串 在SpringMVC环境中,@RequestBody接收的是一个Json对象的字符串,而不是一个Json对象.然而在ajax请求往往传的都是Json对象,用 JSON.stringify(data)的方式就能将对象变成字符串.同时ajax请求的时候也要指定dataType: "json",

学习笔记26_MVC前台强类型参数

*一般在MVC中,aspx后台要往前台传递参数,使用ViewData["Key"] = obj; 前台就要 <%=(ViewData["key"] as ClassName).xxx属性%> 这个的坏处是,如果key的名字改了,前台就不能获取数据,而且在编译阶段查不出错误,所以,可以改成如下写法: ViewData.Model = obj; 对应的,在Aspx中,输入声明数据类型,做法:<%@page Language=... Inheris =

springboot websocket集群(stomp协议)连接时候传递参数

最近在公司项目中接到个需求.就是后台跟前端浏览器要保持长连接,后台主动往前台推数据. 网上查了下,websocket stomp协议处理这个很简单.尤其是跟springboot 集成. 但是由于开始是单机玩的,很顺利. 但是后面部署到生产搞集群的话,就会出问题了. 假如集群两个节点,浏览器A与节点A建立连接,A节点发的消息浏览器A节点肯定能收到.但是B节点由于没有跟浏览器A建立连接.B节点发的消息浏览器就收不到了. 网上也查了好多,但是没有一个说的很清楚的,也很多都是理论层面的. 还有很多思路都

EasyUI Tree 动态传递参数

1.问题背景 一般出现在加载的时候,传递参数给后台,进行数据筛选,然后在加载tree渲染数据.所谓动态参数,可以是你的上一级节点node,或者是根节点node. 2.涉及方法 onBeforeLoad(node,param),需要给的参数在这个方法后面赋值,比如: var rootNode = $(this).tree('getRoot',node.target); param.typeId = rootNode.id; 这样typeId 就作为动态参数,传递给了后台,后台获取typeId这个参