File upload, data validation (background), interceptor

1. File Upload

  1. You need to upload the jar package --fileploat

  2. End web
    form must be submitted by post, encoding must be multipart / form-data file upload text box must be named

    <form method="post" enctype="multipart/form-data" action="stuUpload">
        姓名:<input type="text" name="name"/>
        年龄:<input type="text" name="age"/>
        上传文件:<input type="file" name="photo"/>
        <input type="submit" value="提交"/>
    </form>
  3. SpringMVC configuration file upload parser

    <!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置文件上传的大小限制,单位:字节 -->
    <property name="maxUploadSize" value="99999999"></property>
    </bean>
  4. Layer processing control codes

    package com.alibaba.wlq.controller;
    import java.io.File;
    import java.io.IOException;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.commons.io.FileUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.multipart.MultipartFile;
    import com.alibaba.wlq.bean.Student;
    @Controller
    public class StudentController {
    @RequestMapping("stuUpload")
    public String addStudent(MultipartFile photo,Student stu,HttpServletRequest request,Model model) {
        //获取文件上传的真实保存路径
        String path = request.getServletContext().getRealPath("/photo");
        File file = new File(path);
        if(!file.exists()) {
            file.mkdirs();
        }
        String filename = System.currentTimeMillis()+photo.getOriginalFilename();
        stu.setSphoto("photo/"+filename);
        File targetFile = new File(path+"/"+filename);
        try {
            FileUtils.writeByteArrayToFile(targetFile, photo.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        model.addAttribute("stu",stu);
        return "index";
    }
    }
  5. Student entity class

    package com.alibaba.wlq.bean;
    public class Student {
    private String name;
    private Integer age;
    //注意:Student实体类中图片的属性名称不能和文件上传中名臣属性的值一致,否则会出现400错误
    private String sphoto;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getSphoto() {
        return sphoto;
    }
    public void setSphoto(String sphoto) {
        this.sphoto = sphoto;
    }
    }

2. interceptor

What is the interceptor?

Spring MVC The interceptor (Interceptor) similar to the filter (Filter) Servlet is, it is mainly for intercepting a user request and processed accordingly. For example permissions may be verified by the interceptor, the log recording request information, determines whether the user login and the like.
To use Spring MVC in the interceptor, we need to define and configure the interceptor class.

  1. Creating a class that implements the interface and interface methods HandlerInterceptor rewriting

    package com.alibaba.wlq.interceptor;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    public class Interceptor 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 {
        // TODO Auto-generated method stub  
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        Object user = request.getSession().getAttribute("user");
        if(user!=null) {
            return true;
        }else {
            response.sendRedirect("toLogin");
            return false;
        }
    }
    }
  2. The class configuration to create the configuration file SpringMVC

    <!-- 配置拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
                <!--表示拦截所有user下以及user下子类的请求-->
                <mvc:mapping path="/user/**"/>
                <!---->
                <mvc:exclude-mapping path="/user/toLogin"/>
                <mvc:exclude-mapping path="/user/login"/>
                <mvc:exclude-mapping path="/user/toRegister"/>
                <mvc:exclude-mapping path="/user/register"/>
                <mvc:exclude-mapping path="/user/index"/>
                <bean class="com.alibaba.wlq.interceptor.Interceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

3. The data check (background check)

  1. Import jar package (the validate)
  2. Annotations in the respective entity class

    package com.alibaba.wlq.bean;
    
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Pattern;
    
    import org.hibernate.validator.constraints.Length;
    import org.hibernate.validator.constraints.NotEmpty;
    
    public class User {
        @NotEmpty(message="账号不能为空")
        @NotNull(message="账号不能为空")
        private String account;
        @NotEmpty(message="密码不能为空")
        @NotNull(message="密码不能为空")
        @Length(min=6,max=12,message="密码的长度在6~12之间")
        private String password;
        @Pattern(regexp="/^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/",message="手机号码格式不正确")
        private String phone;
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
        public User(String account, String password, String phone) {
            super();
            this.account = account;
            this.password = password;
            this.phone = phone;
        }
        public String getAccount() {
            return account;
        }
        public void setAccount(String account) {
            this.account = account;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public User(String account, String password) {
            super();
            this.account = account;
            this.password = password;
        }
        public User() {
            super();
        }
    }
    
  3. A control parameter receiving layer

    @RequestMapping("register")
    public String register(@Valid User user,BindingResult br,Model model) {
        if(br.hasErrors()) {
            List<FieldError> fieldList = br.getFieldErrors();
            Map<String,Object> errorMsg = new HashMap<>();
            for (FieldError f : fieldList) {
                errorMsg.put(f.getField(), f.getDefaultMessage());
            }
            model.addAttribute("errorMsg",errorMsg);
            return "register";
        }
        return "login";
    }
  4. Get an error message in a Web page

    <body>  
    <form action="register" method="post">
        账号:<input type="text" name="account"/>${errorMsg.account }<br>
        密码:<input type="text" name="password"/>${errorMsg.password }<br>
        手机号:<input type="text" name="phone"/>${errorMsg.phone}<br>
        <input type="submit" value="提交"/>
    </form>
    </body>

Guess you like

Origin www.cnblogs.com/wuliqqq/p/11461878.html