前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(十五)-SpringMVC註解開發(基礎篇)
本文主要內容:
(1 )SpringMVC校驗
(2)資料回顯
(3)異常處理器
(4)圖片上傳
(5)Json數據互動
(6)支援RESTful
1.SpringMVC校驗
1.1校驗理解
專案中,通常使用較多的是前端的校驗,例如頁面中js校驗。對於安全要求較高的建議在伺服器進行校驗。
伺服器校驗:
控制層controller:校驗頁面請求的參數的合法性。在服務端控制層controller校驗,不區分客戶端類型(瀏覽器、手機客戶端、遠端呼叫)
業務層service(使用較多):主要校驗關鍵業務參數,僅限於service接口中使用的參數。
持久層dao:一般是不校驗的。
1.2springmvc校驗需求
springmvc使用hibernate的校驗框架validation(和hibernate沒有任何關係)。
校驗思維:
頁面提交請求的參數,請求到controller方法中,使用validation進行校驗。如果校驗出錯,將錯誤訊息展示Dao頁面。
特定需求:
商品修改,新增校驗(校驗商品名稱長度、產生日期的非空校驗),如果校驗出錯,在商品修改頁面顯示錯誤訊息。
1.3環境準備
hibernate的校驗框架validation所需要jar套件:
1.4設定校驗器
在classpath下springmvc.xml中設定:
<!-- 校验器 --><bean><!-- Hibernate校验器--><property></property><!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties --><property></property></bean><!-- 校验错误信息配置文件 --><bean><!-- 资源文件名--><property> <list> <value>classpath:CustomValidationMessages</value> </list> </property><!-- 资源文件编码格式 --><property></property><!-- 对资源文件内容缓存时间,单位秒 --><property></property></bean>
#1.5將validator注入到處理器適配器中
在classpath下springmvc.xml中設定:
1.5.1設定方式1
1.5.2設定方式2
<!-- 自定义webBinder --><bean><property></property></bean><!-- 注解适配器 --><beanclass><property></property></beanclass>
1.6在pojo中新增校驗規則
在ItemsCustom.java中加入校驗規則:
/** * 商品信息的扩展类 * @author Joanna.Yan * */public class ItemsCustom extends Items{//添加商品信息的扩展属性}
這裡ItemsCustom直接繼承的是Items,所以我們在Items中新增:
1.7CustomValidationMessages.properties
#在classpath下新建CustomValidationMessages.properties文件,設定校驗錯誤訊息:
#1.8捕獲校驗錯誤訊息
一個BindingResult對應一個pojo。
1.9在頁面顯示校驗錯誤訊息
#1.9.1方式一
在controller中將錯誤訊息傳到頁面即可。
//商品信息修改提交//在需要校验的pojo前添加@Validated,在需要校验的pojo后边添加BindingResult bindingResult接收校验出错信息//注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。@RequestMapping("/editItemsSubmit")public String editItemsSubmit(Model model,HttpServletRequest request,Integer id, @Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{ //获取校验错误信息if(bindingResult.hasErrors()){ List<objecterror> allErrors=bindingResult.getAllErrors();for (ObjectError objectError : allErrors) { System.out.println(objectError.getDefaultMessage()); }//将错误信息传到页面model.addAttribute("allErrors", allErrors);//出错,重新到商品页面return "items/editItems"; }//调用service更新商品信息,页面需要将商品信息传到此方法 itemsService.updateItems(id, itemsCustom); //重定向到商品的查询列表// return "redirect:queryItems.action";//页面转发// return "forward:queryItems.action";return "success"; }</objecterror>
頁面顯示錯誤訊息:
<if><foreach>${error.defaultMessage }<br></foreach></if>
1.9.2方式二
修改Controller方法:
//商品信息修改提交//在需要校验的pojo前添加@Validated,在需要校验的pojo后边添加BindingResult bindingResult接收校验出错信息//注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。@RequestMapping("/editItemsSubmit")public String editItemsSubmit(Model model,HttpServletRequest request,Integer id, @Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{ //获取校验错误信息if(bindingResult.hasErrors()){ List<objecterror> allErrors=bindingResult.getAllErrors();for (ObjectError objectError : allErrors) { System.out.println(objectError.getDefaultMessage()); }//出错,重新到商品页面return "items/editItems"; }//调用service更新商品信息,页面需要将商品信息传到此方法 itemsService.updateItems(id, itemsCustom); //重定向到商品的查询列表// return "redirect:queryItems.action";//页面转发// return "forward:queryItems.action";return "success"; }</objecterror>
商品修改頁面顯示錯誤訊息:
頁頭:
在需要顯示錯誤訊息地方:
<hasbinderrors><foreach>${error.defaultMessage }<br></foreach></hasbinderrors>
1.10分組校驗
1.10.1需求量
在pojo中定義校驗規則,而pojo是被多個controller所共用,當不同的controller方法對同一個pojo進行校驗,但是每個controller方法需要不同的校驗。
解決方法:
定義多個校驗分組(其實是一個java介面),分組中定義有哪些規則。
每個controller方法使用不同的校驗分組。
1.10.2校驗分組
/** * 校验分组 * @author Joanna.Yan * */public interface ValidGroup1 {//接口中不需要定义任何方法,仅是对不同的校验规则进行分组//此分组只校验商品名称长度}
/** * 校验分组 * @author Joanna.Yan * */public interface ValidGroup2 {//接口中不需要定义任何方法,仅是对不同的校验规则进行分组}
1.10.3在校验规则中添加分组
1.10.4在controller方法中使用指定分组的校验
1.10.4校验注解
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
Hibernate Validator 附加的 constraint
@NotBlank(message =) 验证字符串非null,且长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
2.数据回显
2.1什么是数据回显
提交后,如果出现错误,将刚才提交的数据回显到刚才的提交页面。
2.2pojo数据回显方法
springmvc默认对pojo数据进行回显,springmvc自动将形参中的pojo重新放回request域中,request的key为pojo的类名(首字母小写),如下:
controller方法:
@RequestMapping("/editItemSubmit")public String editItemSubmit(Integer id,ItemsCustom itemsCustom)throws Exception{
springmvc自动将itemsCustom放回request,相当于调用下边的代码:
model.addAttribute("itemsCustom", itemsCustom);
jsp页面:
页面中的从“itemsCustom”中取数据。
如果key不是pojo的类名(首字母小写),可以使用@ModelAttribute完成数据回显。
@ModelAttribute作用如下:
(1)绑定请求参数到pojo并且暴露为模型数据传到视图页面。
此方法可实现数据回显效果。
// 商品修改提交@RequestMapping("/editItemSubmit")public String editItemSubmit(Model model,@ModelAttribute("item") ItemsCustom itemsCustom)
页面:
<tr> <td>商品名称</td> <td><input></td> </tr><tr> <td>商品价格</td> <td><input></td> </tr>
如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成数据回显。
(2)将方法返回值暴露为模型数据传到视图页面
//商品分类@ModelAttribute("itemtypes")public Map<string> getItemTypes(){ Map<string> itemTypes = new HashMap<string>(); itemTypes.put("101", "数码"); itemTypes.put("102", "母婴"); return itemTypes; }</string></string></string>
页面:
商品类型:<select><foreach><option>${itemtype.value }</option> </foreach></select>
2.3简单类型数据回显
最简单方法使用model。
//简单数据类型回显 model.addAttribute("id", id);
3.异常处理器
3.1异常处理思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、通过测试手段减少运行时异常的发生。
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
3.2自定义异常类
对不同的异常类型定义异常类,继承Exception。
package joanna.yan.ssm.exception;/** * 系统自定义异常类,针对预期的异常。需要在程序中抛出此类异常。 * @author Joanna.Yan * */public class CustomException extends Exception{//异常信息public String message;public CustomException(String message) {super();this.message = message; }public String getMessage() {return message; }public void setMessage(String message) {this.message = message; } }
3.3全局异常处理器
思路:
系统遇到异常,在程序中手动抛出,dao抛给service、service抛给controller、controller抛给前端控制器,前端控制器调用全局异常处理器。
全局异常处理器处理思路:
解析出异常类型
如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示
如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
springmvc提供一个HandlerExceptionResolver接口。
package joanna.yan.ssm.exception;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;public class CustomExceptionResolver implements HandlerExceptionResolver{/* * ex:系统抛出的异常 */@Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse repsonse, Object handler, Exception ex) {//handler就是处理器适配器要执行的Handler对象(只有一个method)//1.解析出异常类型//2.如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示//3.如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)CustomException customException=null;if(ex instanceof CustomException){ customException=(CustomException)ex; }else{ customException=new CustomException("未知错误"); }//错误信息String message=customException.getMessage(); ModelAndView modelAndView=new ModelAndView();//将错误信息传到页面modelAndView.addObject("message", message);//指向错误页面modelAndView.setViewName("error");return modelAndView; } }
3.4错误页面
nbsp;HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"><title>错误提示</title><meta><meta><meta> <meta><meta><!--<link rel="stylesheet" type="text/css" href="styles.css?1.1.11">-->
3.5在springmvc.xml配置全局异常处理器
<!-- 全局异常处理器 只要实现HandlerExceptionResolver接口就是全局异常处理器--><bean></bean>
3.6异常测试
在controller、service、dao中任意一处需要手动抛出异常。
如果是程序中手动抛出的异常,在错误页面中显示自定义的异常信息,如果不是手动抛出异常说明是一个运行时异常,在错误页面只显示“未知错误”。
在商品修改的controller方法中抛出异常。
在service接口中抛出异常:
如果与业功能相关的异常,建议在service中抛出异常。
与业务功能没有关系的异常(比如形参校验),建议在controller中抛出。
上边的功能,建议在service中抛出异常。
4.图片上传
4.1配置虚拟目录
在Tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
<context></context>
访问http://localhost:8080/pic即可访问F:\develop\upload\temp下的图片。
注意:在图片虚拟目录中,一定要将图片目录分级创建(提高I/O性能),一般我们采用按日期(年、月、日)进行分级创建。
4.2配置解析器
springmvc中对多部件类型解析。
在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。
在springmvc.xml中配置multipart类型解析器。
<!-- 文件上传 --><bean><!-- 设置上传文件的最大尺寸为5MB --><property><value>5242880</value></property></bean>
4.3加入上传图片的jar
上边的解析器内部使用下边的jar进行图片上传。
4.4上传图片
controller:
@RequestMapping("/editItemsSubmit")public String editItemsSubmit( Model model, HttpServletRequest request, Integer id, @ModelAttribute("items") @Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom, BindingResult bindingResult, MultipartFile items_pic//接收商品图片) throws Exception{ //获取校验错误信息if(bindingResult.hasErrors()){ List<objecterror> allErrors=bindingResult.getAllErrors();for (ObjectError objectError : allErrors) { System.out.println(objectError.getDefaultMessage()); }//将错误信息传到页面model.addAttribute("allErrors", allErrors);//可以直接使用model将提交的pojo回显到页面model.addAttribute("items", itemsCustom);//简单数据类型回显model.addAttribute("id", id);//出错,重新到商品页面return "items/editItems"; } //上传图片String originalFilename=items_pic.getOriginalFilename();if(items_pic!=null&&originalFilename!=null&&originalFilename.length()>0){//存储图片的物理路径String pic_path="F:\\develop\\upload\\temp\\";//新的图片名称String newFileName=UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));//新图片File newFile=new File(pic_path+newFileName);//将内存中的数据写入磁盘 items_pic.transferTo(newFile);//将新图片名称写到itemsCustom中 itemsCustom.setPic(newFileName); } //调用service更新商品信息,页面需要将商品信息传到此方法 itemsService.updateItems(id, itemsCustom); //重定向到商品的查询列表// return "redirect:queryItems.action";//页面转发// return "forward:queryItems.action";return "success"; }</objecterror>
页面:
form添加enctype="multipart/form-data",file的name与controller形参一致:
5.Json数据交互
5.1为什么要进行json数据交互
json数据格式在接口调用中、html页面中较常用,json格式比较简单,解析还比较方便。
比如:webserivce接口,传输json数据。
5.2springmvc进行json交互
(1)请求json、输出json,要求请求的是json串,所以在前端页面中需要将请求的内容转成json,不太方便。
(2)请求key/value、输出json。次方法比较常用。
5.3环境准备
5.3.1加载json转换的jar包
springmvc中使用jackson的包进行json转换(@requestBody和@responseBody使用下边的包进行json转换),如下:
5.3.2配置json转换器
在classpath/springmvc.xml,注解适配器中加入messageConverters
!--注解适配器 --><bean><property><list><bean></bean></list></property></bean>
注意:如果使用
5.4json交互测试
这里分输入json串输出json串和输入key/value输出json两种情况进行测试。
新建jsonTest.jsp
nbsp;HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"><title>json交互测试</title><meta><meta><meta> <meta><meta><!--<link rel="stylesheet" type="text/css" href="styles.css?1.1.11">--><script></script> <script> //请求json,输出的是json function requestJson(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath }/requestJson.action', contentType:'application/json;charset=utf-8', //数据格式是json串,商品信息 data:'{"name":"手机","price":999}', success:function(data){//返回json结果 alert(data); } }); } //请求key/value,输出的是json function responseJson(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath }/responseJson.action', //请求是key/value这里不需要指定contentType,因为默认就是key/value类型 //contentType:'application/json;charset=utf-8', //数据格式是json串,商品信息 data:'name=手机&price=999', success:function(data){//返回json结果 alert(data); } }); } </script> <input> <input>
新建Controller:
package joanna.yan.ssm.controller;import joanna.yan.ssm.po.ItemsCustom;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @Controllerpublic class JsonTest {//请求json串(商品信息),输出的竖json(商品信息)//@RequestBody将请求的商品信息的json串转成itemsCustom对象//@ResponseBody将itemsCustom转成json输出@RequestMapping("/requestJson")public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){ return itemsCustom; } //请求key/value,输出的竖json@RequestMapping("/responseJson")public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){ return itemsCustom; } }
(1)测试输入json串输出是json串
(2)测试输入key/value输出是json串
6.RESTful支持
6.1什么是RESTful
RESTful架构,是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以得到越来越多网站的采用。
RESTful(即Representational State Transfer的缩写)其实是一个开发理念,是对http的很好的诠释。
(1)对url进行规范,写RESTful格式的url
非REST的url:http://...../queryItems.action?id=001&type=T01
REST的url风格:http://..../items/001
特点:url简洁,将参数通过url传到服务端
(2)对http的方法规范
不管是删除、添加、更新...使用url是一致的,如果进行删除,需要设置http的方法为delete,同理添加...
后台controller方法:判断http方法,如果是delete执行删除,如果是post执行添加。
(3)对http的contentType规范
请求时指定contentType,要json数据,设置成json格式的type...
目前完全实现RESTful的系统很少,一般只实现(1)、(3),对于(2)我们一个方法经常会同时存在增删改查,实现起来太费劲了。
下面举例实现(1)、(2)。
6.2REST的例子
6.2.1需求
查询商品信息,返回json数据。
6.2.2controller
定义方法,进行url映射使用REST风格的url,将查询商品信息的id传入controller。
输出json使用@ResponseBody将java对象输出json。
//查询商品信息,输出json///itemsView/{id}里面的{id}表示占位符,通过@PathVariable获取占位符中的参数//如果占位符中的名称和形参名一致,在@PathVariable可以不指定名称@RequestMapping("/itemsView/{id}")public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception{ ItemsCustom itemsCustom=itemsService.findItemsById(id);return itemsCustom; }
6.2.3REST方法的前端控制器配置
在web.xml增加配置:
<!-- springmvc前端控制器,rest配置 --> <servlet> <servlet-name>springmvc_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc_rest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
6.3对静态资源的解析
配置前端控制器的url-parttern中指定/,对静态资源的解析出现问题:
在springmvc.xml中添加静态资源解析方法。
<!-- 静态资源的解析 包括:js、css、img...--> <resources></resources> <resources></resources>
以上是SpringMVC校驗的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavadevelovermentIrelyPlatForm-DeTueTososeVeralFactors.1)JVMVariationsAffectPerformanceNandBehaviorAcroSsdifferentos.2)Nativelibrariesviajnijniiniininiinniinindrododerplatefform.3)

Java代碼在不同平台上運行時會有性能差異。 1)JVM的實現和優化策略不同,如OracleJDK和OpenJDK。 2)操作系統的特性,如內存管理和線程調度,也會影響性能。 3)可以通過選擇合適的JVM、調整JVM參數和代碼優化來提升性能。

Java'splatFormentenceHaslimitations不包括PerformanceOverhead,versionCompatibilityIsissues,挑戰WithnativelibraryIntegration,Platform-SpecificFeatures,andjvminstallation/jvminstallation/jvmintenance/jeartenance.therefactorscomplicatorscomplicatethe“ writeOnce”

PlatformIndependendecealLowsProgramStormonanyPlograwsStormanyPlatFormWithOutModification,而LileCross-PlatFormDevelopmentRequiredquiresMomePlatform-specificAdjustments.platFormIndependence,EneblesuniveByjava,EnablesuniversUniversAleversalexecutionbutmayCotutionButMayComproMisePerformance.cross.cross.cross-platformd

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

javaispopularforcross-platformdesktopapplicationsduetoits“ writeonce,runany where”哲學。 1)itusesbytiesebyTecodeThatrunsonAnyJvm-備用Platform.2)librarieslikeslikeslikeswingingandjavafxhelpcreatenative-lookingenative-lookinguisis.3)

在Java中編寫平台特定代碼的原因包括訪問特定操作系統功能、與特定硬件交互和優化性能。 1)使用JNA或JNI訪問Windows註冊表;2)通過JNI與Linux特定硬件驅動程序交互;3)通過JNI使用Metal優化macOS上的遊戲性能。儘管如此,編寫平台特定代碼會影響代碼的可移植性、增加複雜性、可能帶來性能開銷和安全風險。

Java將通過雲原生應用、多平台部署和跨語言互操作進一步提昇平台獨立性。 1)雲原生應用將使用GraalVM和Quarkus提升啟動速度。 2)Java將擴展到嵌入式設備、移動設備和量子計算機。 3)通過GraalVM,Java將與Python、JavaScript等語言無縫集成,增強跨語言互操作性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具