SpringMVC知识点总结

在这里插入图片描述

1 SpringMVC总体框架图

在这里插入图片描述

  1. DispatcherServlet前端控制器:接收request,进行response
  2. HandlerMapping处理器映射器:根据url查找Handler。(可以通过xml配置方式,注解方式)
  3. HandlerAdapter处理器适配器:根据特定规则去执行Handler,编写Handler时需要按照HandlerAdapter的要求去编写。
  4. Handler处理器(后端控制器):需要程序员去编写,常用注解开发方式。
  5. Handler处理器执行后结果是ModelAndView,具体开发时Handler返回方法值类型包括:ModelAndView、String(逻辑视图名)、void(通过在Handler形参中添加request和response,类似原始
  6. servlet开发方式,注意:可以通过指定response响应的结果类型实现json数据输出) View
  7. Resolver视图解析器:根据逻辑视图名生成真正的视图(在springmvc中使用View对象表示)
  8. View视图:jsp页面,仅是数据展示,没有业务逻辑

2 包装类型pojo参数绑定

方法一:在形参中 添加HttpServletRequest request参数,通过request接收查询条件参数。
方法二:在形参中让包装类型的pojo接收查询条件参数。

<script type="text/javascript">
        function deleteItems(){
            //提交form
            document.itemsForm.action="${pageContext.request.contextPath }/items/deleteItems.action";
            document.itemsForm.submit();
        }
        function queryItems(){
            //提交form
            document.itemsForm.action="${pageContext.request.contextPath }/items/queryItems.action";
            document.itemsForm.submit();
        }
</script>

<form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItems.action" method="post">
查询条件:
    <table width="100%" border=1>
        <tr>
            <td>
                商品名称:<input name="itemsCustom.name" />
            </td>
            <td><input type="button" value="查询" onclick="queryItems()"/>
                <input type="button" value="批量删除" onclick="deleteItems()"/>
            </td>
        </tr>
    </table>
商品列表:
</form>

商品名称:
注意:itemsCustom和包装pojo中的属性一致即可。

Controller代码,这时itemsQueryVo中的itemsCustom中的name属性就有值了。

@Controller
@RequestMapping("/items")

public class ItemsController {
 @RequestMapping("/queryItems")
    public ModelAndView queryItems(HttpServletRequest request,
                                   ItemsQueryVo itemsQueryVo) throws Exception {
        // 测试forward后request是否可以共享

        System.out.println(request.getParameter("id"));

        // 调用service查找 数据库,查询商品列表
        List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据
        modelAndView.addObject("itemsList", itemsList);

        // 指定视图
        // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
        // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
        // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
        modelAndView.setViewName("items/itemsList");

        return modelAndView;
    }
}

此外,集合类型绑定也是相同的,name属性要与后台pojo中的属性对应,即可完成传值。

3 Springmvc校验

项目中,通常使用较多是前端的校验,比如页面中js校验。对于安全要求较高点建议在服务端进行校验。

控制层conroller:校验页面请求的参数的合法性。在服务端控制层conroller校验,不区分客户端类型(浏览器、手机客户端、远程调用)
业务层service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数。
持久层dao:一般是不校验的。

springmvc使用hibernate的校验框架validation(和hibernate没有任何关系)。

校验思路:
页面提交请求的参数,请求到controller方法中,使用validation进行校验。如果校验出错,将错误信息展示到页面。

简述JSR 303校验规范:
(1)导入jar包
在这里插入图片描述
(2)

public class Student {
	//@Pattern:只修饰字符串类型的属性,验证是否符合正则表达式的规则
	@Pattern(message="请输入长度大于3",regexp="\\w{3,}")
	private String name;
	/*
	 * @NotNull:用于验证基本数据类型,无法检查长度为0的字符串
	 * @NotBlank:只作用于字符串,且会去掉前后空格(被trim()方法之后长度是否大于0)
	 * @NotEmpty:验证对象是否不为空,最小长度为1,用于Array、Collection、Map、String
	 */
	@NotNull(message="该值不能为空")
	@Min(value=1,message="恭喜你来到美好的世界")
	@Max(value=120,message="来到天堂")
	//范围@Range()
	private Integer age;
	@Email(message="请输入正确的邮箱格式")
	private String email;
	@DateTimeFormat(pattern="yyyy-MM-dd")
	@Past(message="生日必须是一个过去的日期")
	//@Future :未来的一个时间
	private Date date;

数据校验工具类

public class Validator {
	/*
	 * JSR 303校验: Java Specification Requests Java规范提案
	 * 也可以称为Bean Validation,它的核心接口是javax.validation.Validator。
	 * Hibernate Validator是它的实现。
	 */
	public static Map<String,Object> getValidator(BindingResult result){
		//BindingResult:获取错误信息
		Map<String,Object> map=null;
		//判断是否有错误
		boolean errors = result.hasErrors();
		if(errors){
			map=new HashMap<String,Object>();
			for(FieldError error:result.getFieldErrors()){
				//依次获取错误属性及该属性的错误信息
				String field=error.getField();
				String message=error.getDefaultMessage();
				map.put(field, message);
			}
			return map;
		}
		return null;
	}

3.1 在Spring配置文件中配置校验器

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <!-- hibernate校验器-->
    <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
    <!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
    <property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource"
      class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <!-- 资源文件名-->
    <property name="basenames">
        <list>
            <value>classpath:CustomValidationMessages</value>
        </list>
    </property>
    <!-- 资源文件编码格式 -->
    <property name="defaultEncoding" value="UTF-8"/>
<!--    <property name="fileEncodings" value="utf-8" />-->
    <!-- 对资源文件内容缓存时间,单位秒 -->
    <property name="cacheSeconds" value="120" />
</bean>

3.2 校验器注入到处理器适配器中

<mvc:annotation-driven validator=“validator”>
</mvc:annotation-driven>

4 数据回显

提交后,如果出现错误,将刚才提交的数据回显到刚才的提交页面。
4.1 springmvc默认对pojo数据进行回显

pojo数据传入controller方法后,springmvc自动将pojo数据放到request域,key等于pojo类型(首字母小写)
使用@ModelAttribute指定pojo回显到页面在request中的key。
4.2 @ModelAttribute还可以将方法的返回值传到页面

在商品查询列表页面,通过商品类型查询商品信息。
在controller中定义商品类型查询方法,最终将商品类型传到页面。

5 异常处理

5.1 异常处理思路

系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。

系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
在这里插入图片描述第一步:自定义异常类

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;
    }
}

第二步:实现全局异常处理器,HandlerExceptionResolver接口

处理思路:
1 解析出异常类型
2 如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示
3 如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
handler就是处理器适配器要执行Handler对象(只有method)

@Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
        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;
}

第三步:定义JSP的error页面,展示错误

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误提示</title>
</head>
<body>
${message }
</body>
</html>
第四步:在springmvc.xml配置全局异常处理器
<!-- 全局异常处理器 只要实现HandlerExceptionResolver接口就是全局异常处理器 -->
<bean class="cn.itcast.ssm.exception.CustomExceptionResolver"></bean>

第五步:异常测试

在controller、service、dao中任意一处需要手动抛出异常。
如果是程序中手动抛出的异常,在错误页面中显示自定义的异常信息,如果不是手动抛出异常说明是一个运行时异常,在错误页面只显示“未知错误”。

@RequestMapping("/editItems")
    public String editItems(Model model,
                            @RequestParam(value = "id", required = true) Integer items_id)
            throws Exception {
        // 调用service根据商品id查询商品信息
        ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
        //判断商品是否为空,根据id没有查询到商品,抛出异常,提示用户商品信息不存 在
        if(itemsCustom == null){
            throw new CustomException("修改的商品信息不存在!");
        }

        // 通过形参中的model将model数据传到页面
        // 相当于modelAndView.addObject方法
        model.addAttribute("items", itemsCustom);

        return "items/editItems";
    }

如果与业务功能相关的异常,建议在service中抛出异常。
与业务功能没有关系的异常,建议在controller中抛出。

6文件上传

6.1 在springmvc.xml中配置multipart类型解析器

   <!-- 文件上传 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

实现文件上传之CommonsMultipartResolver

Controller
public class UploadController {
	
	/*
	 * 实现单个文件上传
	 * MultipartFile是接收文件类型的对象,提供了上传文件、获取文件名称等方法
	 * String getContentType()//获取文件MIME内容类型
     * InputStream getInputStream()//读取文件内容,返回输入流
     * String getName() //获取表单中文件组件的名字
     * String getOriginalFilename() //获取上传文件的初始化/原始名
     * long getSize() //获取文件的字节大小,单位byte
     * boolean isEmpty() //是否为空
     * void transferTo(File dest) //将上传文件保存到目标目录中。
	 * 
	 */
	@RequestMapping("upload")
	public String demo(@RequestParam("name") String name,@RequestParam("file") MultipartFile file,HttpServletRequest request){
		System.out.println("文件描述:"+name);
		//获取文件控件中name属性的值
		String name1 = file.getName();
		//获取上传文件的名称
		String originalName = file.getOriginalFilename();
		System.out.println(name1);
		System.out.println(originalName);
		//1.使用输入输出流
		try {
			InputStream input = file.getInputStream();
			String path=request.getServletContext().getRealPath("/upload");
			//OutputStream out=new FileOutputStream("d:\\"+originalName);
			OutputStream out=new FileOutputStream(path+"\\"+originalName);
			byte[] bs=new byte[1024];
			int len=-1;
			while((len=input.read(bs))!= -1){
				out.write(bs, 0, len);
			}
			out.close();
			input.close();
			System.out.println("上传成功");
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return "/success.jsp";
		
	}

实现多文件上传 List

@RequestMapping("uploads")
	public String demo3(@RequestParam("name") String name,@RequestParam("file") List<MultipartFile> file,HttpServletRequest request){
		System.out.println("文件描述:"+name);
		// 判断所上传文件是否存在
		if (!file.isEmpty() && file.size() > 0) {
			//循环输出上传的文件
			for (MultipartFile files : file) {
				// 获取上传文件的原始名称
				String originalFilename = files.getOriginalFilename();
				// 设置上传文件的保存地址目录
				String dirPath = request.getServletContext().getRealPath("/upload/");
				File filePath = new File(dirPath);
				// 如果保存文件的地址不存在,就先创建目录
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				// 使用UUID重新命名上传的文件名称(上传人_uuid_原始文件名称)
				String newFilename = name+ "_"+UUID.randomUUID() + "_"+originalFilename;
				try {
					// 使用MultipartFile接口的方法完成文件上传到指定位置
					files.transferTo(new File(dirPath + newFilename));
				} catch (Exception e) {
					e.printStackTrace();
                    return "/error.jsp";
				}
			}

文件上传的注意事项:
1.表单的method为post
2.表单的enctype为 multipart/form-data
3.表单中有文件域

<body>
	
	<h1>使用流的方式实现文件上传</h1>
	<form action="upload" method="post" enctype="multipart/form-data">
		<input type="file" name="file" > <br>
		描述<input type="text" name="name" ><br>
		<input type="submit" value="提交">
	</form>
	<h1>使用file.transferTo()的方式实现文件上传</h1>
	<form action="upload1" method="post" enctype="multipart/form-data">
		<input type="file" name="file" > <br>
		描述<input type="text" name="name" ><br>
		<input type="submit" value="提交">
	</form>
	
	<h1>采用spring提供的方式实现文件上传</h1>
	<form action="upload2" method="post" enctype="multipart/form-data">
		<input type="file" name="file"> <br>
		描述<input type="text" name="name" ><br>
		<input type="submit" value="提交">
	</form>
	<!-- 实现一次性选中多个文件进行上传要在文件域的表单中加上multiple="multiple" -->
	<h1>实现多文件上传1</h1>
	<form action="uploads" method="post" enctype="multipart/form-data">
		描述:<input type="text" name="name" ><br>
		文件:<input type="file" name="file" multiple="multiple"> <br>
		<input type="submit" value="提交">
	</form>
	<h1>实现多文件上传2</h1>
	<form action="uploadss" method="post" enctype="multipart/form-data">
		描述:<input type="text" name="name" ><br>
		文件1:<input type="file" name="file" > <br>
		文件2:<input type="file" name="file1" > <br>
		文件3:<input type="file" name="file2" > <br>
		<input type="submit" value="提交">
	
	</form>
</body>

7文件下载

@Controller
public class DownLoadController {
	/*
	 * SpringMVC提供了一个ResponseEntity,标识整个http响应:状态码、头部信息以及响应体内容,可以方便地返回BodyBuilder、HttpHeaders、HTTPStatus
	 */
	@RequestMapping("/download")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,@RequestParam("filename") String filename) throws Exception{
	    // 指定要下载的文件所在路径
	    String path = request.getServletContext().getRealPath("/upload/");
	    // 创建该文件对象
	    File file = new File(path+File.separator+filename);
	    // 对文件名编码,防止中文文件乱码
	    filename = this.getFilename(request, filename);
	    // 设置响应头
	    HttpHeaders headers = new HttpHeaders();
	    // 通知浏览器以下载的方式打开文件
	    headers.setContentDispositionFormData("attachment", filename);
	    // 定义以二进制流的形式下载返回文件数据
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    // 使用SringMVC的ResponseEntity对象封装返回下载数据,Commons FileUpload组件的FileUtils读取文件
	   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
	                                           headers,HttpStatus.OK);
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值