POJO
1.表单数据
<body>
<form action="/addOne" method="post" >
币名:<input id="name" name="name" value=""/><br>
货币总量:<input id="supply" name="supply" value=""/><br>
核心算法:<input id="hush_function" name="hush_function" value=""/><br>
区块时间:<input id="block_time" name="block_time" value=""/><br>
啥:<input type="text" id="timestamping_scheme" name="timestamping_scheme" value=""/><br>
简介:<input type="text" id="brief" name="brief" value=""/><br>
ico成本:<input id="ico_cost" name="ico_cost" value=""/><br>
<button type="submit">提交</button>
</form>
</body>
2.后台Controller
@RequestMapping(value = "addOne", method = RequestMethod.POST)
public ModelAndView addOne(Coin coin)throws Exception{
ModelAndView mav = new ModelAndView();
coinDao.addOne(coin);
mav.setViewName("redirect:trade");
return mav;
}
}
3.注意事项
-
<input>标签name要与对象属性名一致。
-
不要求每个属性都有对应的<input>
-
不用加@RequestParam
-
只能传简单类型的属性参数,若对象属性存在复杂类型(Date; pojo)参数是传不过去的。
Date
1.Converter配置(springmvc.xml)
<!-- 映射器,适配器-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--自定义参数绑定-->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!--自定义converter-->
<bean class="cn.vituaction.controller.converter.CoinDateConverter"/>
</list>
</property>
</bean>
2.自定义的converter
package cn.vituaction.controller.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CoinDateConverter implements Converter<String,Date> {
@Override
public Date convert(String source) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try{
Date date = simpleDateFormat.parse(source);
return date;
}catch (ParseException e){
e.printStackTrace();
}
return null;
}
}
这样,表单中与Date属性对应的数据,就会从String类型转为Date类型赋给对象的Date类型属性,再传入数据库(datetime).
注意事项
从Date类型从前端传入数据库成功了,但将数据库中datetime类型数据传入页面又是不一样的操作了
JSP页面
<c:forEach items="${list}" var="coin" >
<tr>
<td>${coin.name}</td><td>${coin.supply}</td><td>${coin.block_time}</td>
<td>${coin.hush_function}</td><td><a href="edit?id=${coin.id}">修改</a></td>
<td><fmt:formatDate type="date" value="${coin.release_date}"/></td>
</tr>
</c:forEach>
若不加上<fmt>则会打出类型“Tue Oct 07 12:04:36 CST 2014”这样的格式。
通过改变type或者pattern可以定义自己需要的格式
文件头记得加上
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>
但是!可能会出现类似于“: According to TLD or attribute directive in tag file, attribute value does not accept any expressions,”的报错,那么就要将fmt的taglib改为
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
似乎是因为jsp版本冲突的原因,但具体为什么,我也搞不清楚??