springMVC和mybatis整合笔记03
来源:互联网 发布:中邮联合网络通信集团 编辑:程序博客网 时间:2024/06/06 20:05
数据回显
1.什么事回显?
数据提交后,如果出现错误(没有错误),将刚才提交的数据回显到刚才提交的页面。
2.pojo数据回显方法:
springMVC默认对pojo进行数据回显。
@ModelAttribute(“” “”)指定pojo回显到页面在request中的key ,还可以将方法的返回值传到页面。
//itemsType表示最终将方法返回值放在request中的key,页面@ModelAttribute("itemsType")public Map<String, String> getItemTypes(){Map<String, String> itemsType=new HashMap<>();itemsType.put("101", "数码");itemsType.put("102", "电脑");return itemsType;}
页面得到:
商品类型:<select name="tiemstype">
<c:forEach items="${itemsType}" var="itemst">
</c:forEach> <option value="${itemst.key }">${itemst.value }</option> </select>
最简单的方法就是使用Model.model.addAttribute("", );
简单的数据回显使用Model.
2.异常处理。
系统中异常包括两类:
1.预期异常。通过捕获异常而获取异常信息。
2.运行异常。通过规范代码、测试/、减少运行时异常发生。
springMVC提供全局异常处理器进行统一处理。(系统只有一个)
1.自定义异常
/** * @描述: 系统自定义异常。 */public class CustomException extends Exception{//异常信息public String message;public CustomException(String message) {super(message);this.message = message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}全局异常处理器:
系统异常。在程序中手动抛出。dao抛给service,service抛给controller,controller抛给前端控制器,前端控制器调用全局异常处理器。
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{/* *系统抛出异常 */@Overridepublic ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {// handler就是处理器适配器要执行的handler对象。(只有method//解析出异常类型。//如果该异常类型是系统自定义的异常。直接抛出异常到页面展示。//String message=null;//if(ex instanceof CustomException){//message=((CustomException)ex).getMessage();//}else{////如果该异常类型不是系统自定义的异常,构造一个自定义异常类型(信息为“未知错误”)//message="未知错误";//}//上边代码改为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;}}页面: ${message}
springMVC.xml
<!-- 全局异常处理器 只要实现了HandlerExceptionResolver这个接口就是全局异常处理器--> <bean class="cn.lanz.sm.exception.CustomExceptionResolver"> </bean>
如果已业务有关的功能异常。建议在service抛出异常。
如果已业务无关的功能异常。建议在controller抛出异常。
3.上传图片。
1.在页面form中提交enctype="multipart/form-data"的数据时。需要springMVC对multipart类型的数据进行解析
springMVC.xml配置中multipart类型解析器。
1. 配置虚拟目录。
2.也可以修改tomcat配置文件。在conf/server.xml添加虚拟目录。
注意:将图片分级创建。提高流的性能。
上传jar包:
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
springmvc.xml配置:
<!-- 文件上传 --> <bean id="multipartResolver" class="<span style="color:#FF0000;">org.springframework.web.multipart.commons.CommonsMultipartResolver</span>"> <!-- 设置文件上传的最大尺寸5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
controller设置
//MultipartFile pic接收商品图片。//MultipartFile pic接收商品图片。@RequestMapping("/editItemsSubmit")public String editItemsSubmit(HttpServletRequest request,Integer id,ItemsCustom itemsCustom,<span style="color:#FF6666;">MultipartFile </span>item_pic)throws Exception{//原始名称 String originalFilename=item_pic.getOriginalFilename(); //上传图片 if(item_pic!=null && originalFilename!=null && originalFilename.length()>0){//存储图片物理路径String pic_path="E:\\upload\\temp\\";//新的图片名称,随机数加扩展名String newfilename=UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));//新图片//File newFile=new File("E:\\upload\\temp"+newfilename);File newFile=new File(pic_path+"//"+newfilename);//将内存中的数据写入磁盘。item_pic.transferTo(newFile);//将新的图片名称写到itemsCustom中。itemsCustom.setPic(newfilename);}
4.springMVC JSON数据交互:
1.JSON数据格式在接口调用中/HTML中常用。
2.@requestBody将JSON转换为java对象。@responseBody将java对象转为JSON字符串。
3.请求key/value、输出JSON。此方法比较常用。
4.请求json 字符串contentType=application/json。请求key/value application/x-www-form-urlencoded.
jackson包。进行JSON转换。
jackson-mapper-asl-1.8.8.jar
jackson-core-asl-1.8.8.jar
1.json输出json
//请求JSON。输出JSON function requestJson(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath}/requestJson.action', contentType:'application/json;charset=utf-8', data:'{"name":"手机","price":200}', success:function(data){ alert(data); } }); }
@Controllerpublic class JsonTest {//请求JSON/输出json//@RequestBody将请求的商品信息的json转成java对象//@ResponseBody将java对象转成json输出、@RequestMapping("/requestJson")public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){return itemsCustom;}}
2.key/value 输出json
//请求KEY/VALUE,输出JSON function responseJson(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath}/requestJson.action', //contentType:'application/json;charset=utf-8', data:'name=手机&price=200', success:function(data){ alert(data); } }); }
//请求key/value输出json//@ResponseBody将java对象转成json输出、@RequestMapping("/responseJson")public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){return itemsCustom;}
5.RESTFUL架构:
就是目前最流行一种互联网软件架构。结构清晰,符合标准,易于理解、扩展方便。
1.对url进行规范。写restful格式的url
非restful的url:http://../admin.action?id=01&type=t01
restful的url:http://..../admin/01
//查询商品信息。返回json///itemsView/{id}表示这个位置的参数传到@PathVariable指定的名中@RequestMapping("/itemsView/{id}")public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id)throws Exception{//调用serviceItemsCustom itemsCustom=itemsService.findItemsById(id);return itemsCustom;}还要配置web.xml springMVC的前端控制器。
<!-- springMVC前端控制器 --> <servlet> <servlet-name>springmvc_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation配置springmvc加载的配置文件(处理器映射,适配器) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/myspringmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc_rest</servlet-name> <span style="color:#FF6666;"><url-pattern>/*</url-pattern></span> </servlet-mapping>
http://localhost:8080/mybatisspringMVC/items/itemsView/4
静态资源解析:
<!-- 静态资源解析 js css img-->
<mvc:resources location="/js/" mapping="/js/**"/>
6.拦截器:
定义:
public class HandlerInterceptor implements org.springframework.web.servlet.<span style="color:#FF0000;">HandlerInterceptor</span>{//执行handler完成执行//统一的异常、日志处理。@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {// TODO Auto-generated method stub}//进入handler方法之后,返回modelandview之前执行。//modelAndView:将公用的模型数据在这里传到视图。也可以统一指定。@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response,Object arg2, ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stub}//进入handler方法之前执行。//用于身份认证、身份授权。@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {//false表示拦截。return false;}}
拦截器配置。
1.针对handlerMapping进行拦截。
2.配置类似全局的拦截器。
<!-- 拦截器 --> <mvc:interceptors> <!-- 多个拦截器。顺序执行 --> <mvc:interceptor> <!--/**表示所有的url--> <mvc:mapping path="/**"/> <bean class="cn.lanz.sm.interceptor.HandlerInterceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="定义的拦截器类路径cn.lanz.sm.interceptor.HandlerInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors>
//进入handler方法之前执行。//用于身份认证、身份授权。@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {//获取urlString url=request.getRequestURI();//判断是否为公开地址。if(url.indexOf("login.action")>=0){return true;}//获得sessionHttpSession session=request.getSession();//获取session信息。String username=(String) session.getAttribute("username");//不为null表示放行。if(username!=null){return true;}//认证不成功,则跳转到登录页面。request.getRequestDispatcher("/WEB-INF/JSP/LOGIN.JSP").forward(request, response);//false表示拦截。return false;}
- springMVC和mybatis整合笔记03
- springMVC和mybatis整合笔记01
- springMVC和mybatis整合笔记02
- springmvc和mybatis整合
- springmvc和mybatis整合
- mybatis和springmvc整合
- springMVC和mybatis整合
- Springmvc和mybatis整合
- Springmvc和mybatis整合
- Springmvc和mybatis整合
- SpringMVC+Spring+MyBatis整合笔记
- spring、springmvc、mybatis整合笔记
- Spring+SpringMVC+Mybatis整合笔记
- SpringMVC和MyBatis整合时
- spring整合springmvc和mybatis
- MyBatis和SpringMVC的整合
- springmvc和mybatis的整合
- Springmvc 和Mybatis整合配置文件
- RatioLayout一个屏幕适配三方库源码分析
- $.ajax()方法详解
- 贾跃亭:乐视缺钱是行业公开秘密
- 常用加密解密算法【RSA、AES、DES、MD5】介绍和使用
- django+mysql的简单开发教程
- springMVC和mybatis整合笔记03
- centos7下yum安装mysql
- asp.net实体框加entiryframework 6.0 安装
- HDU-1568-Fibonacci【求高位数字】
- 关于tcp/ip协议
- 获取服务器信息
- 获取天气信息
- 浅析存储区
- OpenJDK与JDK的区别