A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 我是楠楠 于 2018-4-11 13:44 编辑

【郑州校区】springmvc-sublun-day02(中)

【郑州校区】springmvc-sublun-day02(上)

1 @RequestMapping
通过RequestMapping注解可以定义不同的处理器映射规则。
1.1 URL路径映射
@RequestMapping(value="/item")@RequestMapping("/item)
value的值是数组,可以将多个url映射到同一个方法
1.2 窄化请求映射
在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头,通过此方法对url进行分类管理。
如下:
@RequestMapping放在类名上边,设置请求前缀
@Controller
@RequestMapping("/item")
方法名上边设置请求映射url:
@RequestMapping放在方法名上边,如下:
@RequestMapping("/queryItem ")
访问地址为:/item/queryItem
1.3 请求方法限定
u 限定GET方法
@RequestMapping(method = RequestMethod.GET)
如果通过Post访问则报错:
HTTP Status 405 - Request method 'POST' not supported
例如:
@RequestMapping(value="/editItem",method=RequestMethod.GET)
u 限定POST方法
@RequestMapping(method = RequestMethod.POST)
如果通过Post访问则报错:
HTTP Status 405 - Request method 'GET' not supported
u GET和POST都可以
@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})
2 controller方法返回值2.1 返回ModelAndView
controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。
2.2 返回void
        在controller方法形参上可以定义request和response,使用request或response指定响应结果:
1、使用request转向页面,如下:
request.getRequestDispatcher("页面路径").forward(request, response);
2、也可以通过response页面重定向:
response.sendRedirect("url")
3、也可以通过response指定响应结果,例如响应json数据如下:
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
2.3 返回字符串2.3.1 逻辑视图名
controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
//指定逻辑视图名,经过视图解析器解析为jsp物理路径:/WEB-INF/jsp/item/editItem.jsp
return "item/editItem";
2.3.2 Redirect重定向
Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中。
//重定向到queryItem.action地址,request无法带过去
return "redirect:queryItem.action";
redirect方式相当于“response.sendRedirect()”,转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。
由于新发起一个request原来的参数在转发时就不能传递到下一个url,如果要传参数可以/item/queryItem.action后边加参数,如下:
/item/queryItem?...&..
2.3.3 forward转发
controller方法执行后继续执行另一个controller方法,如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。
//结果转发到editItem.action,request可以带过去
return "forward:editItem.action";
forward方式相当于“request.getRequestDispatcher().forward(request,response)”,转发后浏览器地址栏还是原来的地址。转发并没有执行新的request和response,而是和转发前的请求共用一个request和response。所以转发前请求的参数在转发后仍然可以读取到。
3 异常处理器
        springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。
        
3.1 异常处理思路
        系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
        系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
3.2 自定义异常类
        为了区别不同的异常通常根据异常类型自定义异常类,这里我们创建一个自定义系统异常,如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。
        public class CustomException extends Exception {
        /** serialVersionUID*/
        private static final long serialVersionUID = -5212079010855161498L;
        
        public CustomException(String message){
                super(message);
                this.message = message;
        }
        //异常信息
        private String message;
        public String getMessage() {
                return message;
        }
        public void setMessage(String message) {
                this.message = message;
        }
}
3.3 自定义异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest request,
                        HttpServletResponse response, Object handler, Exception ex) {
                ex.printStackTrace();
                CustomException customException = null;
               
                //如果抛出的是系统自定义异常则直接转换
                if(ex instanceof CustomException){
                        customException = (CustomException)ex;
                }else{
                        //如果抛出的不是系统自定义异常则重新构造一个系统错误异常。
                        customException = new CustomException("系统错误,请与系统管理 员联系!");
                }
               
                ModelAndView modelAndView = new ModelAndView();
                modelAndView.addObject("message", customException.getMessage());
                modelAndView.setViewName("error");
                return modelAndView;
        }
}
取异常堆栈:
           try {
                        
                } catch (Exception e) {
                        StringWriter s = new StringWriter();
                        PrintWriter printWriter = new PrintWriter(s);
                        e.printStackTrace(printWriter);
                        s.toString();
                }
3.4 错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
您的操作出现错误如下:<br/>
${message }
</body>
</html>
3.5 异常处理器配置
在springmvc.xml中添加:
<!-- 异常处理器 -->
        <bean id="handlerExceptionResolver" class="cn.itcast.ssm.controller.exceptionResolver.CustomExceptionResolver"/>
3.6 异常测试
修改商品信息,id输入错误提示商品信息不存在。
修改controller方法“editItem”,调用service查询商品信息,如果商品信息为空则抛出异常:
// 调用service查询商品信息
                Items item = itemService.findItemById(id);
               
                if(item == null){
                        throw new CustomException("商品信息不存在!");
                }
在service中抛出异常方法同上。
传智播客·黑马程序员郑州校区地址
河南省郑州市 高新区长椿路11号大学科技园(西区)东门8号楼三层
联系电话 0371-56061160/61/62
来校路线  地铁一号线梧桐街站A口出

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马