標籤:ted tpm cat location ack 查詢 設定 code 使用
一、程式碼範例(需要匯入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、控制器代碼
@Controllerpublic 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、方法一
//控制器設定
@Controllerpublic 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/**"/> <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;}
springMVC中ajax請求和日期轉換(九)