一.annotation-driven
ArrayList底層是一個初始值爲10的Object類型的數組
配置了<mvc:default-servlet-handler/>需要注意的問題:
配置了<mvc:default-servlet-handler/>後,會導致@RequestMapping的映射不能用,因此需要配合
<mvc:annotation-driven/>一起使用。
<mvc:annotation-driven/>
實際的開發中都要將<mvc:annotation-driven/>配上。
二.InitBinder
在數據綁定之前預處理一下
@InitBinder
public void InitBinder(WebDataBinder dataBinder){
dataBinder.setDisallowedFields("email");//不被允許的字段
}
三.數據驗證
springMVC數據校檢:
1.格式轉化:
日期:
需在屬性上配置@DateTimeFormat,例如:
@DateTimeFormat(pattern = “yyyy-mm-dd”)
private Date birth;
此時前臺輸入日期格式爲yyyy-mm-dd,如2017-08-07.
數字:
@NumberFormat(pattern="#,###.#")
private double salary;
springMVC.xml配置:(注意引入類爲FormattingConversionServiceFactoryBean)
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>
<bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<ref bean="employeeConverts"></ref>
</list>
</property>
</bean>
2.錯誤反饋:
@Valid註解用於校驗,所屬包爲:javax.validation.Valid。
首先需要在實體類的相應字段上添加用於充當校驗條件的註解,如:
@NotEmpty
private String lastName;
@Email
private String email;
其次在controller層的方法的要校驗的參數上添加@Valid註解,並且需要傳入BindingResult對象,用於獲取校驗失敗情況下的反饋信息,如下代碼:
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String save(@Valid Employee employee, BindingResult bindingResult,Map<String,Object> map){
if(bindingResult.getErrorCount()>0){
List<FieldError> list = bindingResult.getFieldErrors();
for(FieldError fieldError : list){
System.out.println(fieldError.getField()+"\t"+fieldError.getCode()+"\t"+fieldError.getDefaultMessage());
}
//throw new RuntimeException("1022,錄入信息出錯")
map.put("departments",departmentDao.getDepartments());
map.put("genders",getGendersUtils());
return "input";
}
System.out.println("--------save"+employee.toString());
employeeDao.save(employee);
return "redirect:/emps";
}
錯誤驗證:引入springMVC的表單:
<%@ taglib uri=“http://www.springframework.org/tags/form” prefix=“form” %>
使用<form:errors path=“XXX字段”></form:errors>進行錯誤提示
lastName:<form:input path="lastName"/> <form:errors path="lastName"></form:errors>
email:<form:input path="email"/> <form:errors path="email"></form:errors><br><--將錯誤的信息顯示到頁面-->
進行國際化信息的配置可自定義錯誤提示:
<--國際化信息配置-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>
JSR303
四.Json
1.HttpMessageConverter
用於將請求數據轉換成java對象, 或者將java對象轉換成響應的數據.
2.如何處理JSON:
>.導入jackson的jar包
jackson-annotations-2.1.5.jar
jackson-core-2.1.5.jar
jackson-databind-2.1.5.jar
>.在想要返回json數據的處理方法上,標註@ResponseBody註解即可.
代碼如下:
@ResponseBody//@ResponseBody:是將內容或對象作爲Http響應正文返回
@RequestMapping(value="/testJson",method=RequestMethod.POST)
public Collection<Employee> qryAllEmployee(){
return employeeDao.getAll();
}
3.@RequestBody
//@RequestBody是將Http請求正文插入方法中,修飾目標方法的入參
@RequestMapping(value="/testRequestBody",method=RequestMethod.POST)
public String testRequestBody(@RequestBody String content){
System.out.println("-----testRequestBody:"+content);
return "ok";//跳轉到ok.jsp頁面
}
如果在頭上加上註解 @ResponseBody,則返回的是字符串ok
4.ResponseEntity
ResponseEntity<byte[]>作爲目標方法的返回值
代碼如下:
//ResponseEntity
@RequestMapping(value="/testDownload",method=RequestMethod.GET)
public ResponseEntity<byte[]> testDownload()throws IOException{
byte[] body = null;
FileInputStream input = new FileInputStream(new File("D:\\CRT\\a.txt"));
body = new byte[input.available()];
input.read(body);
input.close();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment,filename=a.txt");
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(body,headers,statusCode);
return result;
}
五.國際化
國際化概述
SessionlocaleResolver&LocaleChangeInterceptor工作原理:
本地化解析器和本地化攔截器:
代碼如下:
主入口:
test18n3:<br>
中文:<a href="${pageContext.request.contextPath}/test18n3?locale=zh_CH">中文</a><br>
english:<a href="${pageContext.request.contextPath}/test18n3?locale=en_US">english</a><br>
控制層:
@RequestMapping(value="/test18n3",method=RequestMethod.GET)
public String test18n3(){
System.out.println("--------test18n3:");
return "ok";
}
ok頁面:顯示信息
<fmt:message key="i18n.username"></fmt:message><br>
<fmt:message key="i18n.password"></fmt:message>
配置文件:
<!--國際化信息配置-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>
文件上傳:
注意上傳文件的表單配置需要加上 enctype=“multipart/form-data”
主入口:
testUpload:
<form action="${pageContext.request.contextPath}/testUpload" method="post" enctype="multipart/form-data">
file1:<input type="file" name="file" value=""><br>
file2:<input type="file" name="file" value=""><br>
file3:<input type="file" name="file" value=""><br>
<input type="submit" value="testUpload_commit">
</form>
控制層:
@RequestMapping(value="/testUpload",method=RequestMethod.POST)
public String testUpload(@RequestParam("file") MultipartFile[] file) throws IllegalStateException,IOException {
for(MultipartFile multipartFile : file){
if(!multipartFile.isEmpty()){
multipartFile.transferTo(new File("D:\\CRT\\"+multipartFile.getOriginalFilename()));
}
}
return "ok";
}
代碼如下:
<!-- 配置文件上傳MultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="1048576"/> <!-- 1M -->
</bean>