• 【从零开始学SpringMVC笔记】SpringMVC进阶


    @RequestMapping

    通过@RequestMapping注解可以定义不同的处理器映射规则。

    URL路径映射

    @RequestMapping(value="item")或@RequestMapping("/item")

    value的值是数组,可以将多个url映射到同一个方法
    @RequestMapping(value = { "itemList", "itemListAll" })

    添加在类上面

    在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头

    请求方法限定

    除了可以对url进行设置,还可以限定请求进来的方法

    • 限定GET方法
      @RequestMapping(method = RequestMethod.GET)

    如果通过POST访问则报错:
    HTTP Status 405 - Request method 'POST' not supported

    例如:
    @RequestMapping(value = "itemList",method = RequestMethod.POST)

    • 限定POST方法
      @RequestMapping(method = RequestMethod.POST)

    如果通过GET访问则报错:
    HTTP Status 405 - Request method 'GET' not supported

    • GET和POST都可以
      @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST})

    Controller方法返回值

    1.ModelAndView
    可以带着数据和视图路径返回,但是不建议使用
    2.String
    返回视图路径,数据由model携带,官方推荐此种方式。实现类解耦,数据和视图分离。
    3.void
    ajax请求适用,返回json格式数据,在完成异步请求时使用

    返回ModelAndView

    controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。

    返回void

    在Controller方法形参上可以定义request和response,使用request或response指定响应结果:
    1、使用request转发页面,如下:
    request.getRequestDispatcher("页面路径").forward(request, response);

    request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
    

    2、可以通过response页面重定向:
    response.sendRedirect("url")

    response.sendRedirect("/springmvc-web2/itemEdit.action");
    

    3、可以通过response指定响应结果,例如响应json数据如下:

    response.getWriter().print("{"abc":123}");
    

    返回字符串

    1、逻辑视图名
    controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
    2、Redirect重定向
    Contrller方法返回字符串可以重定向到一个url地址
    如下商品修改提交后重定向到商品编辑页面。

    // 修改商品成功后,重定向到商品编辑页面
    	// 重定向后浏览器地址栏变更为重定向的地址,
    	// 重定向相当于执行了新的request和response,所以之前的请求参数都会丢失
    	// 如果要指定请求参数,需要在重定向的url后面添加 ?itemId=1 这样的请求参数
    	return "redirect:/itemEdit.action?itemId=" + item.getId();
    

    3、forward转发
    Controller方法执行后继续执行另一个Controller方法
    如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。

    // 修改商品成功后,继续执行另一个方法
    	// 使用转发的方式实现。转发后浏览器地址栏还是原来的请求地址,
    	// 转发并没有执行新的request和response,所以之前的请求参数都存在
    	return "forward:/itemEdit.action";
    

    异常处理器

    springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

    • 异常处理思路
      系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
      系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

    自定义异常类

    为了区别不同的异常,通常根据异常类型进行区分,这里我们创建一个自定义系统异常。
    如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。

    public class MyException extends Exception {
    	// 异常信息
    	private String message;
    
    	public MyException() {
    		super();
    	}
    
    	public MyException(String message) {
    		super();
    		this.message = message;
    	}
    
    	public String getMessage() {
    		return message;
    	}
    
    	public void setMessage(String message) {
    		this.message = message;
    	}
    
    }
    

    自定义异常处理器

    public class CustomHandleException implements HandlerExceptionResolver {
    
    	@Override
    	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
    			Exception exception) {
    		// 定义异常信息
    		String msg;
    
    		// 判断异常类型
    		if (exception instanceof MyException) {
    			// 如果是自定义异常,读取异常信息
    			msg = exception.getMessage();
    		} else {
    			// 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息
    			Writer out = new StringWriter();
    			PrintWriter s = new PrintWriter(out);
    			exception.printStackTrace(s);
    			msg = out.toString();
    
    		}
    
    		// 把错误信息发给相关人员,邮件,短信等方式
    		// TODO
    
    		// 返回错误页面,给用户友好页面显示错误信息
    		ModelAndView modelAndView = new ModelAndView();
    		modelAndView.addObject("msg", msg);
    		modelAndView.setViewName("error");
    
    		return modelAndView;
    	}
    }
    

    异常处理器配置
    在springmvc.xml中添加:

    <!-- 配置全局异常处理器 -->
    <bean 
    id="customHandleException" 	class="cn.itcast.ssm.exception.CustomHandleException"/>
    

    错误页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!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>Insert title here</title>
    </head>
    <body>
    
    	<h1>系统发生异常了!</h1>
    	<br />
    	<h1>异常信息</h1>
    	<br />
    	<h2>${msg }</h2>
    
    </body>
    </html>
    

    异常测试
    修改ItemController方法“queryItemList”,抛出异常:

    /**
     * 查询商品列表
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = { "itemList", "itemListAll" })
    public ModelAndView queryItemList() throws Exception {
    	// 自定义异常
    	if (true) {
    		throw new MyException("自定义异常出现了~");
    	}
    
    	// 运行时异常
    	int a = 1 / 0;
    
    	// 查询商品数据
    	List<Item> list = this.itemService.queryItemList();
    	// 创建ModelAndView,设置逻辑视图名
    	ModelAndView mv = new ModelAndView("itemList");
    	// 把商品数据放到模型中
    	mv.addObject("itemList", list);
    
    	return mv;
    }
    

    上传图片

    配置虚拟目录

    在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:

    访问http://localhost:8080/pic即可访问D:developupload emp下的图片。

    也可以通过eclipse配置,如下图:

    复制一张图片到存放图片的文件夹,使用浏览器访问
    测试效果,如下图:

    加入jar包

    配置上传解析器

    <!-- 文件上传,id必须设置为multipartResolver -->
    <bean id="multipartResolver"
    	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<!-- 设置文件上传大小 -->
    	<property name="maxUploadSize" value="5000000" />
    </bean>
    
    

    jsp页面修改

    在商品修改页面,打开图片上传功能,如下图:

    设置表单可以进行文件上传,如下图:

    图片上传

    在更新商品方法中添加图片上传逻辑

    /**
     * 更新商品
     * 
     * @param item
     * @return
     * @throws Exception
     */
    @RequestMapping("updateItem")
    public String updateItemById(Item item, MultipartFile pictureFile) throws Exception {
    	// 图片上传
    	// 设置图片名称,不能重复,可以使用uuid
    	String picName = UUID.randomUUID().toString();
    
    	// 获取文件名
    	String oriName = pictureFile.getOriginalFilename();
    	// 获取图片后缀
    	String extName = oriName.substring(oriName.lastIndexOf("."));
    
    	// 开始上传
    	pictureFile.transferTo(new File("C:/upload/image/" + picName + extName));
    
    	// 设置图片名到商品中
    	item.setPic(picName + extName);
    	// ---------------------------------------------
    	// 更新商品
    	this.itemService.updateItemById(item);
    
    	return "forward:/itemEdit.action";
    }
    
    

    json数据交互

    @RequestBody

    作用:
    @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。

    传统的请求参数:
    itemEdit.action?id=1&name=zhangsan&age=12
    现在的请求参数:
    使用POST请求,在请求体里面加入json数据

    {
    "id": 1,
    "name": "测试商品",
    "price": 99.9,
    "detail": "测试商品描述",
    "pic": "123456.jpg"
    }
    

    @ResponseBody

    作用:
    @ResponseBody注解用于将Controller的方法返回的对象,通过springmvc提供的HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

    jar包

    如果需要springMVC支持json,必须加入json的处理jar
    我们使用Jackson这个jar,如下图:

    配置json转换器

    如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器,参考之前学习的自定义参数绑定。

    在springmvc.xml配置文件中,给处理器适配器加入json转换器:

    <!--处理器适配器 -->
    	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    		<property name="messageConverters">
    		<list>
    		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    		</list>
    		</property>
    	</bean>
    

    RESTful支持

    什么是restful?
    Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

    资源:互联网所有的事物都可以被抽象为资源
    资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
    分别对应 添加、 删除、修改、查询。
    传统方式操作资源

    http://127.0.0.1/item/queryItem.action?id=1 查询,GET
    http://127.0.0.1/item/saveItem.action 新增,POST
    http://127.0.0.1/item/updateItem.action 更新,POST
    http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST

    使用RESTful操作资源

    http://127.0.0.1/item/1 查询,GET
    http://127.0.0.1/item 新增,POST
    http://127.0.0.1/item 更新,PUT
    http://127.0.0.1/item/1 删除,DELETE

    方法

    1. 使用注解@RequestMapping("item/{id}")声明请求的url
      {xxx}叫做占位符,请求的URL可以是“item /1”或“item/2”

    2. 使用(@PathVariable() Integer id)获取url上的数据

    /**
     * 使用RESTful风格开发接口,实现根据id查询商品
     * 
     * @param id
     * @return
     */
    @RequestMapping("item/{id}")
    @ResponseBody
    public Item queryItemById(@PathVariable() Integer id) {
    	Item item = this.itemService.queryItemById(id);
    	return item;
    }
    
    

    如果@RequestMapping中表示为"item/{id}",id和形参名称一致,@PathVariable不用指定名称。如果不一致,例如"item/{ItemId}"则需要指定名称@PathVariable("itemId")。

    注意两个区别

    1. @PathVariable是获取url上数据的。@RequestParam获取请求参数的(包括post表单提交)

    2. 如果加上@ResponseBody注解,就不会走视图解析器,不会返回页面,目前返回的json数据。如果不加,就走视图解析器,返回页面

    拦截器

    定义

    Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。

    拦截器定义

    public class HandlerInterceptor1 implements HandlerInterceptor {
    	// controller执行后且视图返回后调用此方法
    	// 这里可得到执行controller时的异常信息
    	// 这里可记录操作日志
    	@Override
    	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
    			throws Exception {
    		System.out.println("HandlerInterceptor1....afterCompletion");
    	}
    
    	// controller执行后但未返回视图前调用此方法
    	// 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示
    	@Override
    	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
    			throws Exception {
    		System.out.println("HandlerInterceptor1....postHandle");
    	}
    
    	// Controller执行前调用此方法
    	// 返回true表示继续执行,返回false中止执行
    	// 这里可以加入登录校验、权限拦截等
    	@Override
    	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
    		System.out.println("HandlerInterceptor1....preHandle");
    		// 设置为true,测试使用
    		return true;
    	}
    }
    

    上面定义的拦截器再复制一份HandlerInterceptor2,注意新的拦截器修改代码:
    System.out.println("HandlerInterceptor2....preHandle");

    拦截器配置
    在springmvc.xml中配置拦截器

    <!-- 配置拦截器 -->
    <mvc:interceptors>
    	<mvc:interceptor>
    		<!-- 所有的请求都进入拦截器 -->
    		<mvc:mapping path="/**" />
    		<!-- 配置具体的拦截器 -->
    		<bean class="cn.itcast.ssm.interceptor.HandlerInterceptor1" />
    	</mvc:interceptor>
    	<mvc:interceptor>
    		<!-- 所有的请求都进入拦截器 -->
    		<mvc:mapping path="/**" />
    		<!-- 配置具体的拦截器 -->
    		<bean class="cn.itcast.ssm.interceptor.HandlerInterceptor2" />
    	</mvc:interceptor>
    </mvc:interceptors>
    
    

    正常流程测试

    控制台打印:

    HandlerInterceptor1..preHandle..
    HandlerInterceptor2..preHandle..
    
    HandlerInterceptor2..postHandle..
    HandlerInterceptor1..postHandle..
    
    HandlerInterceptor2..afterCompletion..
    HandlerInterceptor1..afterCompletion..
    

    中断流程测试
    HandlerInterceptor1的preHandler方法返回false,HandlerInterceptor2返回true,

    运行流程如下:

    HandlerInterceptor1..preHandle..
    

    从日志看出第一个拦截器的preHandler方法返回false后第一个拦截器只执行了preHandler方法,其它两个方法没有执行,第二个拦截器的所有方法不执行,且Controller也不执行了。

    HandlerInterceptor1的preHandler方法返回true,HandlerInterceptor2返回false,运行流程如下:

    HandlerInterceptor1..preHandle..
    HandlerInterceptor2..preHandle..
    HandlerInterceptor1..afterCompletion..
    

    从日志看出第二个拦截器的preHandler方法返回false后第一个拦截器的postHandler没有执行,第二个拦截器的postHandler和afterCompletion没有执行,且controller也不执行了。

    • 总结

    preHandle按拦截器定义顺序调用
    postHandler按拦截器定义逆序调用
    afterCompletion按拦截器定义逆序调用

    postHandler在拦截器链内所有拦截器返成功调用
    afterCompletion只有preHandle返回true才调用

    拦截器应用

    处理流程
    1、有一个登录页面,需要写一个Controller访问登录页面
    2、登录页面有一提交表单的动作。需要在Controller中处理。
    a) 判断用户名密码是否正确(在控制台打印)
    b) 如果正确,向session中写入用户信息(写入用户名username)
    c) 跳转到商品列表
    3、拦截器。
    a) 拦截用户请求,判断用户是否登录(登录请求不能拦截)
    b) 如果用户已经登录。放行
    c) 如果用户未登录,跳转到登录页面。

    第一步 编写登录jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!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>Insert title here</title>
    </head>
    <body>
    
    <form action="${pageContext.request.contextPath }/user/login.action">
    <label>用户名:</label>
    <br>
    <input type="text" name="username">
    <br>
    <label>密码:</label>
    <br>
    <input type="password" name="password">
    <br>
    <input type="submit">
    
    </form>
    
    </body>
    </html>
    

    第二步 用户登陆Controller

    @Controller
    @RequestMapping("user")
    public class UserController {
    
    	/**
    	 * 跳转到登录页面
    	 * 
    	 * @return
    	 */
    	@RequestMapping("toLogin")
    	public String toLogin() {
    		return "login";
    	}
    
    	/**
    	 * 用户登录
    	 * 
    	 * @param username
    	 * @param password
    	 * @param session
    	 * @return
    	 */
    	@RequestMapping("login")
    	public String login(String username, String password, HttpSession session) {
    		// 校验用户登录
    		System.out.println(username);
    		System.out.println(password);
    
    		// 把用户名放到session中
    		session.setAttribute("username", username);
    
    		return "redirect:/item/itemList.action";
    	}
    
    }
    

    第三步 编写拦截器

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
    	// 从request中获取session
    	HttpSession session = request.getSession();
    	// 从session中获取username
    	Object username = session.getAttribute("username");
    	// 判断username是否为null
    	if (username != null) {
    		// 如果不为空则放行
    		return true;
    	} else {
    		// 如果为空则跳转到登录页面
    		response.sendRedirect(request.getContextPath() + "/user/toLogin.action");
    	}
    
    	return false;
    }
    

    第四步 配置拦截器
    只能拦截商品的url,所以需要修改ItemController,让所有的请求都必须以item开头,如下图:

    在springmvc.xml配置拦截器

    <mvc:interceptor>
    	<!-- 配置商品被拦截器拦截 -->
    	<mvc:mapping path="/item/**" />
    	<!-- 配置具体的拦截器 -->
    	<bean class="cn.itcast.ssm.interceptor.LoginHandlerInterceptor" />
    </mvc:interceptor>
    
  • 相关阅读:
    【CF516D】Drazil and Morning Exercise(换根DP预处理+暴力双指针)
    【CF538G】Berserk Robot(思维)
    【CF521D】Shop(贪心)
    【洛谷4827】[国家集训队] Crash 的文明世界(斯特林数+换根DP)
    斯特林数的基础性质与斯特林反演的初步入门
    【CF566C】Logistical Questions(点分治)
    【CF980D】Perfect Groups(仔细一想是道水题)
    【洛谷2597】[ZJOI2012] 灾难(支配树)
    2020CCPC长春站题解A D F H J K
    2020CCPC长春站自我反省
  • 原文地址:https://www.cnblogs.com/zllk/p/12793200.html
Copyright © 2020-2023  润新知