一、代码示例(需要导入jquery文件和json的jar包)
1、前台页面
<html> <head> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script> function check(x){ var uname= x.value; var url="findOneByUname?t="+new Date().getTime(); $.post(url,{uname:uname},function(data){ alert(data); }) } </script> </head> <body> <form action="add" method="post"> name:<input name="uname" onblur="check(this)"/><br> age:<input name="age" /><br> birthday:<input name="birthday" /><br> <input type="submit" value="增加"/> </form> </body> </html>
2、控制器代码
@Controller public class UserAction { @Autowired private UserService userService; @RequestMapping(value="findOneByUname",produces="text/html;charset=UTF-8") @ResponseBody public String findOneByUname(String uname){ User user = userService.findOne(uname); System.out.println(user); return JSON.toJSONString(user); } }
3、spring核心配置文件描述(主要是为了处理乱码)
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
二、ajax请求乱码处理
1、方法一
//控制器设置
@Controller public class UserAction { @RequestMapping(value="findOneByUname",produces="text/html;charset=UTF-8") @ResponseBody public String findOneByUname(String uname){ User user = userService.findOne(uname); System.out.println(user); return JSON.toJSONString(user); } }
spring核心配置文件设置
<mvc:resources location="/js/" mapping="/js/**"/> <mvc:annotation-driven>
2、方法二
@RequestMapping("findOneByUname") @ResponseBody public String findOneByUname(String uname){ User user = userService.findOne(uname); System.out.println(user); return JSON.toJSONString(user); }
<mvc:resources location="/js/" mapping="/js/**"/> --针对post请求--
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven>
三、spring mvc中的日期转换问题
1、使用注解进行设置
public class User { private Integer uid; private String uname; private Integer age; //处理增加时为日期问题 @DateTimeFormat(pattern="yyyy-MM-dd") //处理查询请求时的日期问题 @JSONField(format="yyyy-MM-dd") private Date birthday; }