Struts2框架之类型转换 --Struts2框架

Struts2框架实现了大多数常见的用于类型转换的转换器,开发人员不用自己编写类型转换代码,就可以实现数据类型的转换。下面一个Struts2框架类型转换的简单事例,

本例可在使用validate()方法进行输入校验 --Struts2框架基础上进行修改。

1、修改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() {
    if (book == null || book.getBookName().isEmpty()) {
      addActionError("请输入完整的数目信息!");
      return INPUT;
    } else {
      System.out.println("添加的书目信息如下:");
      System.out.println("书名:" + book.getBookName());
      System.out.println("单价:" + book.getBookPrice());
      System.out.println("出版日期:" + book.getBookPublishDate());
      System.out.println("数量:" + book.getBookCount());
      return SUCCESS;
    }

  }
}

2、修改addBook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'addBook.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  <body>
    <s:actionerror />
    <s:form action="addBook">
      <s:textfield name="book.bookName" label="书名" />
      <s:textfield name="book.bookPrice" label="单价" />
      <s:textfield name="book.bookPublishDate" label="出版日期" />
      <s:textfield name="book.bookCount" label="数量" />
      <s:submit value="提交" />
      <s:reset value="重置" />
    </s:form>
    <s:if test="book.bookName != ''">
      添加的书目信息如下:<br>
      书名:<s:property value="book.bookName" />
      <br>
      单价:<s:property value="book.bookPrice" />
      <br>
      出版日期:<s:property value="book.bookPublishDate" />
      <br>
        数量:<s:property value="book.bookCount" />
    </s:if>
  </body>
</html>

3、执行结果

控制台显示类型转换后的信息

posted @ 2018-06-24 12:27  牛新龙的IT技术博客  阅读(277)  评论(0编辑  收藏  举报