springMVC日记(三),文件上传,拦截器,数据校验

一、文件上传

  1.需要的jar包 commons-fileupload    1.3.1 ,common-io   2.2

  2.网页。表单必须是post提交,编码必须是multipart/form-data  文件上传文本框必须起名

<form action="upload.do" method="post" enctype="multipart/form-data">
        <input type="file" name="myfile">
        <input type="submit" value="提交">
    </form>

  3.在springmvc中配置文件上传解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 。设置文件上传大小的最大值: 2MB -->
        <property name="maxUploadSize" value="2097152"></property>
    </bean>

  4.在控制层处理代码

public String upload(MultipartFile myfile,HttpServletRequest request) {
        //1.获取文件上传保存的路径。设置目录为 upload
        String path=request.getServletContext().getRealPath("/upload");
        System.out.println(path);
        //2.创建该文件对象,如果没有路径,则创建相应的目录
        File file=new File(path);
        if(!file.exists()) {
            file.mkdirs();
        }
        //3.获取文件名
        String name=myfile.getOriginalFilename();
        //4.获取文件对象
        File targetFile=new File(path+"/"+name);
        //5.文件输出流以字节数组形式将文件输出到指定路径中
        try(BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(targetFile));) {
            bos.write(myfile.getBytes());
            //。利用FileUtils也可以
            //FileUtils.writeByteArrayToFile(targetFile, myfile.getBytes());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "list";
    }

二、拦截器。拦截的都是控制层的地址,它在handlerMapping之后controller层之前的过程中拦截

  1.创建一个类,实现接口 HandlerInterceptor

  2.重写接口中的方法

public class UserInterceptor implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        System.out.println("========");
        
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        System.out.println("是否拦截");
        Object user = request.getSession().getAttribute("user");
        if(user!=null) {
            System.out.println("通过");
            return true;
        }
        else {
            System.out.println("不通过");
            response.sendRedirect("/springMVC4/index.jsp");
            return false;
        }
    }

}

  3.把创建的类配置到springmvc文件中

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/user/*"/>
            <mvc:exclude-mapping path="/user/toLogin.do"/>
            <mvc:exclude-mapping path="/user/login.do"/>
            <mvc:exclude-mapping path="/user/toRegister.do"/>
            <mvc:exclude-mapping path="/user/register.do"/>
            <bean class="com.zhiyou100.cyf.interceptor.UserInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

三、数据校验(后台校验 hibernate validate)

  1.引入jar包springMVC日记(三),文件上传,拦截器,数据校验

   2.在相应的实体类加入注解

@NotEmpty(message="用户名不能为空")
    private String name;
    @Pattern(regexp="^[0-9A-z_\.%@]{6,12}$",message="密码为6-12位数字字母和_.%@的组合")
    private String pw;
    @Pattern(regexp="^1[3-9]\d{9}$",message="手机格式错误")
    private String tel;

其校验注解详情见https://blog.csdn.net/y550918116j/article/details/78258916

  3.在控制层接收参数时

public String reigster(@Valid User user,BindingResult br,Model model) {
        //BindingResult封装了所有错误信息
        if(br.hasErrors()) {
            List<FieldError> fieldErrors=br.getFieldErrors();//获取每个字段错误对象
            Map<String,Object> error=new HashMap<>();
            for(FieldError e:fieldErrors) {
                error.put(e.getField(),e.getDefaultMessage());//得到错误的字段名和错误信息
            }
            model.addAttribute("error", error);
            return "register";
        }
        return "login";
    }