使用validate()方法进行输入校验 --Struts2框架

服务器端的输入校验包含两种方式:硬编码方式和配置文件方式。本文演示硬编码方式中使用validate()方法进行输入校验。

1、项目目录结构:

2、项目核心代码:

BookAction.java:

public class BookAction extends ActionSupport {
  private Book book;

  public Book getBook() {
    return book;
  }

  public void setBook(Book book) {
    this.book = book;
  }

  public String execute() {
    return SUCCESS;
  }

  public void validate() {
    if (book.getBookName().isEmpty()) {
      addFieldError("book.bookName", "书名不能为空!");
    }
    if (book.getBookPrice()<=0) {
      addFieldError("book.bookPrice", "单价不应小于等于0");
    }
    if (book.getBookPublishDate() == null||book.getBookPublishDate().after(new Date())) {
      addFieldError("book.bookPublicDate", "出版日期不能为空并且应该在今天之前!");
    }
    if (book.getBookCount() <= 0) {
      addFieldError("book.bookCount", "数量应大于0");
    }
  }
}

BookAction.java:

 

public class Book {

 

  private String bookName;
  private double bookPrice;
  private Date bookPublishDate;
  private int bookCount;


  public String getBookName() {
    return bookName;
  }
  public void setBookName(String bookName) {
    this.bookName = bookName;
  }
  public Double getBookPrice() {
    return bookPrice;
  }
  public void setBookPrice(Double bookPrice) {
    this.bookPrice = bookPrice;
  }
  public Date getBookPublishDate() {
    return bookPublishDate;
  }
  public void setBookPublishDate(Date bookPublishDate) {
    this.bookPublishDate = bookPublishDate;
  }
  public int getBookCount() {
    return bookCount;
  }
  public void setBookCount(int bookCount) {
    this.bookCount = bookCount;
  }
}

struts.xml:

 

<struts>
  <package name="default" namespace="/" extends="struts-default">
    <action name="addBook" class="com.example.action.BookAction">
      <result>/addBook.jsp</result>
      <result name="input">/addBook.jsp</result>
    </action>
  </package>
</struts>

 

 

addBook.jsp:

<s:actionerror />
<s:form action="addBook">
  <s:textfield name="book.bookName" label="书名" />
  <s:textfield name="book.bookPrice" label="单价" />
  <s:textfield name="book.bookPublicDate" label="出版日期" />
  <s:textfield name="book.bookCount" label="数量" />
  <s:submit value="提交" />
  <s:reset value="重置" />
</s:form>

3、使用validate()方法校验结果截图

posted @ 2018-06-22 12:32  牛新龙的IT技术博客  阅读(3476)  评论(2编辑  收藏  举报