• 使用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()方法校验结果截图

  • 相关阅读:
    关于源码编译每次提示有错误 要make update-api
    如何在Android中添加系统服务
    git查看每个版本间的差异
    achartengine画出动态折线图
    java中基本数据类型和C语言中基本数据类型转换
    获取图片的真实宽高
    hdu-2066-一个人的旅行
    Linux内核模块编程与内核模块LICENSE -《具体解释(第3版)》预读
    Android平台Camera实时滤镜实现方法探讨(十一)--实时美颜滤镜
    ios9定位服务的app进入后台三分钟收不到经纬度,应用被挂起问题及解决方式
  • 原文地址:https://www.cnblogs.com/qikeyishu/p/9212869.html
Copyright © 2020-2023  润新知