SpringMVC框架四

一、数据格式化处理

1、简介

数据转换器作用:对象转换对象

请求数据------》数据转换器------》对象

其实数据格式化就是数据转换器的一种

数据格式化特点:

输入字符串数据类型-------》数据格式化------》对象

对象------》数据格式化----------》字符串

2、用法

只要继承Formatter接口,即可实现数据格式化处理

应用场景

如何实现

定义javabean

 1 package com.gec.bean;
 2 
 3 import java.io.Serializable;
 4 import java.util.Date;
 5 
 6 public class User implements Serializable {
 7 
 8     private String username;
 9     private Integer age;
10     private Date birth;
11 
12     public String getUsername() {
13         return username;
14     }
15 
16     public void setUsername(String username) {
17         this.username = username;
18     }
19 
20     public Integer getAge() {
21         return age;
22     }
23 
24     public void setAge(Integer age) {
25         this.age = age;
26     }
27 
28 
29     public Date getBirth() {
30         return birth;
31     }
32 
33     public void setBirth(Date birth) {
34         this.birth = birth;
35     }
36 
37     @Override
38     public String toString() {
39         return "User{" +
40                 "username='" + username + '\'' +
41                 ", age=" + age +
42                 ", birth=" + birth +
43                 '}';
44     }
45 }

实现handler

 1 package com.gec.controller;
 2 
 3 import com.gec.bean.User;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.ui.Model;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 
 8 @Controller
 9 public class UserController {
10 
11 
12     @RequestMapping("/toform")
13     public String toform(Model model)
14     {
15         User user=new User();
16 
17         user.setUsername("张三");
18         user.setAge(30);
19         //它会在表单的输入框打印:xxxx-xx-xx
20         user.setBirth(new java.util.Date());
21 
22 
23         model.addAttribute("command",user);
24 
25         return "form";
26     }
27 
28     @RequestMapping("/save")
29     public String save(User user)
30     {
31         System.out.println(user);
32         return "success";
33     }
34 }

编写jsp的标签form

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
 3 <html>
 4 <head>
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <form:form action="${pageContext.servletContext.contextPath}/save">
 9     用户名:<form:input path="username" /><br/>
10     年龄:<form:input path="age" /><br/>
11     出生年月:<form:input path="birth" /><br/>
12     <input type="submit" value="保存"/>
13 </form:form>
14 </body>
15 </html>

自定义formater的类

 1 package com.gec.formatter;
 2 
 3 import org.springframework.format.Formatter;
 4 
 5 import java.text.ParseException;
 6 import java.text.SimpleDateFormat;
 7 import java.util.Date;
 8 import java.util.Locale;
 9 
10 public class DateFormatter implements Formatter<Date> {
11 
12     //将字符串----------》解释--------》Date对象
13     @Override
14     public Date parse(String s, Locale locale) throws ParseException {
15 
16         SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
17 
18         return sf.parse(s);
19 
20     }
21 
22     //将Date对象--------->解释-------->打印输出
23     @Override
24     public String print(Date date, Locale locale) {
25 
26         SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
27         return sf.format(date);
28 
29     }
30 }

配置spring-config.xml文件,注解格式化对象

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:mvc="http://www.springframework.org/schema/mvc"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
 7        xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
10         http://www.springframework.org/schema/mvc
11         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context-4.3.xsd
14         http://www.springframework.org/schema/util
15         http://www.springframework.org/schema/util/spring-util.xsd">
16 
17     <context:component-scan base-package="com.gec.controller" />
18 
19     <!-- 装配自定义格式化转换器-->
20     <mvc:annotation-driven  conversion-service="conversionService"/>
21     <mvc:default-servlet-handler />
22 
23     <!-- 格式化 -->
24     <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
25         <property name="formatters">
26             <list>
27                 <bean class="com.gec.formatter.DateFormatter" />
28             </list>
29         </property>
30     </bean>
31 
32 
33 
34 
35     <!-- 视图解析器  -->
36     <bean id="viewResolver"
37           class="org.springframework.web.servlet.view.InternalResourceViewResolver">
38         <!-- 前缀 -->
39         <property name="prefix">
40             <value>/WEB-INF/jsp/</value>
41         </property>
42         <!-- 后缀 -->
43         <property name="suffix">
44             <value>.jsp</value>
45         </property>
46     </bean>
47 
48 
49 </beans>

3、通过注解实现数据格式化处理

 

 

 

二、数据校验实现

1、简介

什么是数据校验

一般情况下,是针对表单的数据进行校验,例如判断是否为空,emall格式是否规范

数据表单校验类型

前端校验

前端页面表单提交之前进行数据校验,采用javascript脚本语言去处理

后端校验

在后端程序代码去处理校验

2、springmvc框架如何实现后端校验

a、有两种实现

 

springmvc有自身的校验框架

 

 

依赖第三方的hibernate校验器实现

 

3、mvc框架自身的校验框架

 

如何实现

 

 

实现校验器

 

 1 package com.gec.validate;
 2 
 3 import com.gec.bean.User;
 4 import org.springframework.stereotype.Repository;
 5 import org.springframework.validation.Errors;
 6 import org.springframework.validation.ValidationUtils;
 7 import org.springframework.validation.Validator;
 8 
 9 @Repository("userValidator")
10 public class UserValidate implements Validator {
11 
12     @Override
13     public boolean supports(Class<?> aClass) {
14         return User.class.isAssignableFrom(aClass);
15     }
16 
17     @Override
18     public void validate(Object o, Errors errors) {
19 
20         ValidationUtils.rejectIfEmpty(errors, "username", null,"登录名不能为空");
21         ValidationUtils.rejectIfEmpty(errors, "password", null,"密码不能为空");
22 
23 
24     }
25 }

表单

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
 3 <html>
 4 <head>
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <%--<form>
 9     用户名:<input type="text" name="username" value="${command.username}"/><br/>
10     年龄:<input type="text" name="age" value="${command.age}"/><br/>
11 </form>--%>
12 <form:form modelAttribute="user" action="/save">
13 用户名:<form:input path="username" /><form:errors path="username" cssStyle="color: red"/><br/>
14 密码:<form:input path="password" /><form:errors path="password" cssStyle="color: red"/><br/>
15 <input type="submit" value="提交"/>
16 </form:form>
17 
18 </body>
19 </html>

后端handler

 1 //注入校验器
 2     @Autowired
 3     private UserValidate userValidate;
 4 
 5     @RequestMapping("/save")
 6     public String save(User user, Errors errors)
 7     {
 8         userValidate.validate(user,errors);
 9 
10         if(errors.hasErrors())
11         {
12             return "form";
13         }
14 
15 
16         return "success";
17     }

4、JSR303数据校验

简介

依赖注解实现数据校验

 

 

 

 

 

 

 

 

 

具体如何实现

 

导入hibernate validate库

 

 

编写java bean,添加校验注解

 

 1 package com.gec.bean;
 2 
 3 import org.hibernate.validator.constraints.Email;
 4 import org.hibernate.validator.constraints.NotEmpty;
 5 
 6 import java.io.Serializable;
 7 
 8 public class User implements Serializable {
 9 
10     @NotEmpty(message = "用户名不为空")
11     private String username;
12     @NotEmpty(message = "密码不为空")
13     private String password;
14     @Email(message = "邮箱格式不对")
15     @NotEmpty(message = "邮箱不为空")
16     private String email;
17 
18     public String getUsername() {
19         return username;
20     }
21 
22     public void setUsername(String username) {
23         this.username = username;
24     }
25 
26     public String getPassword() {
27         return password;
28     }
29 
30     public void setPassword(String password) {
31         this.password = password;
32     }
33 
34     public String getEmail() {
35         return email;
36     }
37 
38     public void setEmail(String email) {
39         this.email = email;
40     }
41 
42     @Override
43     public String toString() {
44         return "User{" +
45                 "username='" + username + '\'' +
46                 ", password='" + password + '\'' +
47                 '}';
48     }
49 }

编写表单

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
 3 <html>
 4 <head>
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <%--<form>
 9     用户名:<input type="text" name="username" value="${command.username}"/><br/>
10     年龄:<input type="text" name="age" value="${command.age}"/><br/>
11 </form>--%>
12 <form:form modelAttribute="user" action="/save2">
13 用户名:<form:input path="username" /><form:errors path="username" cssStyle="color: red"/><br/>
14 密码:<form:input path="password" /><form:errors path="password" cssStyle="color: red"/><br/>
15 email:<form:input path="email" /><form:errors path="email" cssStyle="color: red"/><br/>
16 <input type="submit" value="提交"/>
17 </form:form>
18 
19 </body>
20 </html>

编写后端控制器

1  @RequestMapping("/save2")
2     public String save2(@Valid User user, Errors errors)
3     {
4         if(errors.hasErrors())
5         {
6             return "form";
7         }
8         return "success";
9     }

三、文件上传功能

1、简介

 

实现文件上传

 

 

提交请求必须post

 

 

enctype必须配置成:multipart/form-data

 

 

springmvc它是依赖于apache Fileupload的库实现

 

2、如何在springmvc实现文件上传

 

提供MultipartFile对象实现文件上传

 

 

MultipartFile对象中的常用方法如下:

 

 

byte[] getBytes():获取文件数据

 

 

String getContentType[]:获取文件MIME类型,如image/jpeg等

 

 

InputStream getInputStream():获取文件流

 

 

String getName():获取表单中文件组件的名字

 

 

String getOriginalFilename():获取上传文件的原名

 

 

Long getSize():获取文件的字节大小,单位为byte

 

 

boolean isEmpty():是否有上传文件

 

 

void transferTo(File dest):将上传文件保存到一个目录文件中

 

3、实现文件上传的过程

 

导入apache upload file库文件

 

 

 

 编写表单

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 <form action="${pageContext.servletContext.contextPath}/upload" method="post" enctype="multipart/form-data">
 8 
 9     文件:<input type="file" name="file"/><br/>
10     <input type="submit" value="上传"/>
11 
12 </form>
13 
14 </body>
15 </html>

目标handler文件

 1 @RequestMapping("/toform")
 2     public String toForm()
 3     {
 4 
 5         return "form";
 6     }
 7 
 8     @RequestMapping("/upload")
 9     public String upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file)
10     {
11         System.out.println("获取上传文件原名="+file.getOriginalFilename());
12 
13         //上传文件的绝对路径
14         String uploadfilePath=httpServletRequest.getServletContext().getRealPath("/uploadfile");
15         System.out.println("上传文件的绝对路径="+uploadfilePath);
16         String uploadFileName=file.getOriginalFilename();
17 
18         //创建一个File对象
19         File uploadFile=new File(uploadfilePath,uploadFileName);
20 
21         if(!uploadFile.exists())
22         {
23             try {
24                 //创建文件
25                 uploadFile.createNewFile();
26                 //将上传文件内容复制到目标文件
27                 file.transferTo(uploadFile);
28             } catch (IOException e) {
29                 e.printStackTrace();
30             }
31         }
32 
33         return "success";
34     }

编辑spring-config.xml文件

 1 <bean id="multipartResolver"
 2           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 3         <!-- 上传文件大小上限,单位为字节(10MB) -->
 4         <property name="maxUploadSize">
 5             <value>10485760</value>
 6         </property>
 7         <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
 8         <property name="defaultEncoding">
 9             <value>UTF-8</value>
10         </property>
11     </bean>

四、拦截器

1、简介

 

其实就是类似Servlet组件的过滤器,针对请求实现拦截处理

 

 

 

 

2、拦截器阶段

 

拦截器分成三个阶段

 

 

preHandle

 

 

顾名思义,该方法将在请求处理之前进行调用。此方法返回值决定是否作拦截处理,如果返回值为true,则允许访问目标组件,否则拦截处理

 

 

postHandle

 

 

此方法调用时机:handler控制器调用之后,视图渲染生成之前,触发

 

 

afterCompletion

 

 

此方法调用:渲染了对应的视图之后执行。这个方法的主要作用是用于进行资源清理工作的。

 

3、如何实现拦截器

 

新建类,此类要实现HandlerInterceptor接口

 

 1 package com.gec.interceptor;
 2 
 3 import org.springframework.web.servlet.HandlerInterceptor;
 4 import org.springframework.web.servlet.ModelAndView;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 /*
10 * 定义一个拦截器
11 * */
12 public class MyHandlerInterceptor implements HandlerInterceptor {
13 
14     @Override
15     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
16 
17         System.out.println("pre handle");
18 
19         //获取请求参数
20         String username=httpServletRequest.getParameter("username");
21 
22         if(username!=null && username.equals("tom"))
23         {
24             return true;
25         }
26 
27         return false;
28     }
29 
30     @Override
31     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
32 
33         System.out.println("postHandle");
34         modelAndView.addObject("username","tom2");
35     }
36 
37     @Override
38     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
39 
40         System.out.println("afterCompletion");
41 
42 
43 
44 
45     }
46 }

注册拦截器,在spring-config.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:mvc="http://www.springframework.org/schema/mvc"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
 7        xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
10         http://www.springframework.org/schema/mvc
11         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context-4.3.xsd
14         http://www.springframework.org/schema/util
15         http://www.springframework.org/schema/util/spring-util.xsd">
16 
17     <context:component-scan base-package="com.gec.controller" />
18 
19     <!-- 装配自定义格式化转换器-->
20     <mvc:annotation-driven />
21     <mvc:default-servlet-handler />
22 
23     <bean id="multipartResolver"
24           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
25         <!-- 上传文件大小上限,单位为字节(10MB) -->
26         <property name="maxUploadSize">
27             <value>10485760</value>
28         </property>
29         <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
30         <property name="defaultEncoding">
31             <value>UTF-8</value>
32         </property>
33     </bean>
34 
35     <!--注册拦截器-->
36     <mvc:interceptors>
37         <mvc:interceptor>
38             <mvc:mapping path="/*"/>
39             <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
40             <bean class="com.gec.interceptor.MyHandlerInterceptor"/>
41         </mvc:interceptor>
42     </mvc:interceptors>
43 
44 
45 
46 
47 
48     <!-- 视图解析器  -->
49     <bean id="viewResolver"
50           class="org.springframework.web.servlet.view.InternalResourceViewResolver">
51         <!-- 前缀 -->
52         <property name="prefix">
53             <value>/WEB-INF/jsp/</value>
54         </property>
55         <!-- 后缀 -->
56         <property name="suffix">
57             <value>.jsp</value>
58         </property>
59     </bean>
60 
61 
62 </beans>

实现handler

 1 package com.gec.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.Model;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 
 7 @Controller
 8 public class HelloController {
 9 
10     @RequestMapping("/dohello")
11     public String dohello(Model model)
12     {
13         System.out.println("do hello");
14         model.addAttribute("username","tom1");
15         return "success";
16     }
17 }

 

posted @ 2020-10-21 19:05  蓝景钊  阅读(126)  评论(0)    收藏  举报