1. 程式人生 > >Springmvc後臺校驗加檔案上傳(完整版)

Springmvc後臺校驗加檔案上傳(完整版)

後臺校驗
<!--資料驗證-->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>4.0.1.GA</version>

</dependency>

<!--jboss logging-->
<dependency>
  <groupId>org.jboss.logging</groupId>
  <artifactId>jboss-logging</artifactId>
  <version>3.3.0.Final</version>
</dependency>

<!--validation api-->
<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>1.0.0.GA</version>


</dependency>

<!--slf4j api-->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.21</version>
</dependency


2:然後建立個實體類UserInfo 在這裡使用註解方法來校驗屬性
別忘了GET.SET 
public class UserInfo {

/*必須是0到100之間*/
@Min(value = 0,message = "成績最小為{value}")
@Max(value = 100,message = "最大值為{value}")
private Integer score;

/*手機號不能為空,必須是1開頭 第二位是34567*/
@NotEmpty(message = "手機號不能我為空")
@Pattern(regexp = "^1[3,4,5,6,7,8,9]\\d{9}$",message = "手機號不正確")
private String phone;

//不能為空
    //必須是6個字元以上
    @NotEmpty(message = "使用者不能為空")
    @Size(min = 6,message = "名字至少6個字元")
    private String name;

GET.SET 省略。。。。。。

3:然後controller裡來使用和jsp.介面接應
@Controller
public class controller {
    @RequestMapping("/first")
    public ModelAndView doFist(@Valid UserInfo info, BindingResult br) {
        ModelAndView mv = new ModelAndView();
        /*成功後跳的介面*/
        mv.setViewName("/index.jsp");
    /*有一個可以偵測到驗證錯誤總數的方法*/
        int errorCount = br.getErrorCount();
        if (errorCount > 0) {
            //證明模型驗證失敗
            FieldError score = br.getFieldError("score");//5
            FieldError name = br.getFieldError("name");//5
            FieldError phone = br.getFieldError("phone");//5
            if (score != null) {
                mv.addObject("scormsg", score.getDefaultMessage());
            }
            if (name != null) {
                mv.addObject("namemsg", name.getDefaultMessage());
            }
            if (phone != null) {
                mv.addObject("phonemsg", phone.getDefaultMessage());
            }
            /*失敗後的介面*/
            mv.setViewName("/log.jsp");

        }
        return mv;
    }
    }
4:大配置裡的節點配置
<!--配置包掃描器-->
<context:component-scan base-package="cn.hayyp.jiaoyan"></context:component-scan>
<bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
<!--mvc註解驅動-->
<mvc:annotation-driven validator="myValidator"/>

最後jsp.的介面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>商品</title>
</head>
<body>
<h1>資料校驗</h1>
<form action="/first" method="post">
    成績:<input name="score" /> <span>${scormsg }</span><br/><br/>
    姓名:<input name="name"/><span>${namemsg }</span><br/><br/>
    電話:<input name="phone"/><span>${phonemsg }</span><br/><br/>
    <input type="submit" value="註冊"/>
</form>
</body>
</html>


---------------------------------------------------------------------------------------------------------------------------------


檔案上傳

第1步
<!--檔案上傳的jar包-->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>1.4</version>
</dependency>

第2步

建立一個類 FirstController 使用SpringMVC框架建立註解方法寫一個
檔案上傳的方法別忘了註解:如下
@Controller
public class FirstController {
@RequestMapping("/first")
public String doFirst(MultipartFile upload, HttpSession session){
    //獲取到使用者上傳的檔名字
    String filename = upload.getOriginalFilename();//獲取到檔案的斷名
    //將相對路徑轉換成絕對路徑                                    這個是建立在WEB-INF下面的檔名字
    String realPath = session.getServletContext().getRealPath("/shangchuanwenjian");
    //將file寫入指定的路徑
    File file=new File(realPath,filename);
    try {
        upload.transferTo(file);
        return "/index.jsp";
    } catch (IOException e) {
        e.printStackTrace();
        return "/WJSC.jsp";
    }
第3步: 大配置裡的配置檔案

 <!--配置包掃描器-->
<context:component-scan base-package="cn.hayyp.shangchuan"></context:component-scan>
        <!--配置檔案上傳的專用類-->
        <!--必須要是ID 要不好使-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<mvc:annotation-driven/>

然後把web.xml指定的配置檔名字改一下
<!--初始化引數-->
<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContextWJSC.xml</param-value>
</init-param>


這個是jsp,上傳頁面
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/8/30
  Time: 15:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>檔案上傳</h1>
<%--檔案上上傳必須用post 和 enctype="multipart/form-data"--%>
<form action="/first" method="post" enctype="multipart/form-data">
    檔案   <input type="file" name="upload"/>
    <input type="submit"/>
</form>

</body>
</html>