SpringMVC(二)spring
經過上一篇 SpringMVC 的博文,咱們掌握瞭如何新建 SpringMVC 項目,瞭解了其大體工做原理,瞭解了經常使用的註解,知道了 REST 風格的架構,經過源碼初步瞭解到了數據綁定的流程。接着上次咱們繼續對 SpringMVC 進行學習。json
JodaDateTimeFormatAnnotationFormatterFactroy:支持對日期類型的屬性使用 @DateTimeFormat 註解架構
@DateTimeFormat(pattern = "yyyy/mm/dd") private Date birth; @NumberFormat(pattern = "#,###,###.#") private float salary;
jar 包mvc
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency>
若數據的校驗以及格式化出錯,咱們先將其默認的錯誤消息打印到控制檯,下面的代碼將打印出具體的哪個字段的什麼錯誤。app
@RequestMapping(value = "/emp", method = RequestMethod.POST) public String add(@Valid Employee employee, Errors result, Map<String, Object> map) { // 打印錯誤消息 if (result.getErrorCount() > 0) { System.out.println("出錯了!"); for (FieldError fieldError : result.getFieldErrors()) { System.out.println(fieldError.getField() + " --> " + fieldError.getDefaultMessage()); } } employeeDao.save(employee); return "redirect:/employeeList"; }
導入 jar 包框架
<spring.verison>4.3.8.RELEASE</spring.verison> <jackson.version>2.8.7</jackson.version> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency>
目標操做方法添加註解(目標方法返回一個對象或集合)post
@ResponseBody @RequestMapping("/testJson") public Collection<Employee> testJson() { System.out.println("Succ"); Collection<Employee> values = employeeDao.getEmployeeMap().values(); return values; }
目標頁面發送 Ajax 請求以及處理返回值學習
$(function () { $("#testJson").click(function () { var url = this.href; var args = {}; $.post(url, args, function(data) { for (var i = 0; i < data.length; i++) { var lastName = data[i].lastName; var email = data[i].email; alert(lastName + ", " + email); } }) return false; }) })
大牛們,以爲有任何問題和不足還但願指出,共同進步,謝謝!this