数据回显
1.什么事回显?
数据提交后,如果出现错误(没有错误),将刚才提交的数据回显到刚才提交的页面。
2.pojo数据回显方法:
springMVC默认对pojo进行数据回显。
@ModelAttribute(“” “”)指定pojo回显到页面在request中的key ,还可以将方法的返回值传到页面。
//itemsType表示最终将方法返回值放在request中的key,页面
@ModelAttribute("itemsType")
public Map getItemTypes(){
Map itemsType=new HashMap<>();
itemsType.put("101", "数码");
itemsType.put("102", "电脑");
return itemsType;
}
商品类型:
最简单的方法就是使用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{
/*
*系统抛出异常
*/
@Override
public 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
如果已业务无关的功能异常。建议在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配置:
org.springframework.web.multipart.commons.CommonsMultipartResolver">
5242880
controller设置
//MultipartFile pic接收商品图片。
//MultipartFile pic接收商品图片。
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(HttpServletRequest request,Integer id,
ItemsCustom itemsCustom,MultipartFile 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);
}
});
}
@Controller
public 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;
}
就是目前最流行一种互联网软件架构。结构清晰,符合标准,易于理解、扩展方便。
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{
//调用service
ItemsCustom itemsCustom=itemsService.findItemsById(id);
return itemsCustom;
}
还要配置web.xml springMVC的前端控制器。
springmvc_rest
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring/myspringmvc.xml
springmvc_rest
/*
http://localhost:8080/mybatisspringMVC/items/itemsView/4
静态资源解析:
6.拦截器:
定义:
public class HandlerInterceptor implements org.springframework.web.servlet.HandlerInterceptor{
//执行handler完成执行
//统一的异常、日志处理。
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
//进入handler方法之后,返回modelandview之前执行。
//modelAndView:将公用的模型数据在这里传到视图。也可以统一指定。
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2, ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
//进入handler方法之前执行。
//用于身份认证、身份授权。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//false表示拦截。
return false;
}
}
1.针对handlerMapping进行拦截。
2.配置类似全局的拦截器。
//进入handler方法之前执行。
//用于身份认证、身份授权。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//获取url
String url=request.getRequestURI();
//判断是否为公开地址。
if(url.indexOf("login.action")>=0){
return true;
}
//获得session
HttpSession 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;
}