Struts2、Spring和Hibernate应用实例2

来源:互联网 发布:三国杀mac版本 编辑:程序博客网 时间:2024/05/16 06:32

 
有Struts 1.x经验的朋友都知道Action是Struts的核心内容,当然Struts 2.0也不例外。不过,Struts 1.x与Struts 2.0的Action模型很大的区别。 

 

 Struts 1.x

 Stuts 2.0

 

接口

 

 必须继承org.apache.struts.action.Action或者其子类

 无须继承任何类型或实现任何接口

表单数据

表单数据封装在FormBean中

表单数据包含在Action中,通过Getter和Setter获取

 

1、建立BookAction类

 

package com.sterning.books.web.actions;

 

import java.util.Collection;

import com.sterning.books.model.Books;

import com.sterning.books.services.iface.IBooksService;

import com.sterning.commons.AbstractAction;

import com.sterning.commons.Pager;

import com.sterning.commons.PagerService;

 

public class BooksAction extends AbstractAction {

   

    private IBooksService booksService;

    private PagerService pagerService;

    private Books book;

    private Pager pager;

    protected Collection availableItems;

    protected String currentPage;

    protected String pagerMethod;

    protected String totalRows;

    protected String bookId;

    protected String queryName;

    protected String queryValue;

    protected String searchName;

    protected String searchValue;

    protected String queryMap;

   

    public String list() throws Exception {

        if(queryMap ==null||queryMap.equals("")){

           

        }else{

            String[] str=queryMap.split("~");

            this.setQueryName(str[0]);

            this.setQueryValue(str[1]);

        }

       

        System.out.println("asd"+this.getQueryValue());

        int totalRow=booksService.getRows(this.getQueryName(),this.getQueryValue());

        pager=pagerService.getPager(this.getCurrentPage(), this.getPagerMethod(), totalRow);

        this.setCurrentPage(String.valueOf(pager.getCurrentPage()));

        this.setTotalRows(String.valueOf(totalRow));

        availableItems=booksService.getBooks(this.getQueryName(),this.getQueryValue(),pager.getPageSize(), pager.getStartRow());

       

        this.setQueryName(this.getQueryName());

        this.setQueryValue(this.getQueryValue());

       

        this.setSearchName(this.getQueryName());

        this.setSearchValue(this.getQueryValue());

       

        return SUCCESS;        

    }

   

    public String load() throws Exception {

        if(bookId!=null)

            book = booksService.getBook(bookId);

        else

            bookId=booksService.getMaxID();

        return SUCCESS;

    }

   

    public String save() throws Exception {

        if(this.getBook().getBookPrice().equals("")){

            this.getBook().setBookPrice("0.0");

        }

       

        String id=this.getBook().getBookId();

        Books book=booksService.getBook(id);

       

       

       

        if(book == null)

            booksService.addBook(this.getBook());

        else

            booksService.updateBook(this.getBook());

       

        this.setQueryName(this.getQueryName());

        this.setQueryValue(this.getQueryValue());

       

        if(this.getQueryName()==null||this.getQueryValue()==null||this.getQueryName().equals("")||this.getQueryValue().equals("")){

           

        }else{

            queryMap=this.getQueryName()+"~"+this.getQueryValue();

        }       

       

        return SUCCESS;

    }

   

    public String delete() throws Exception {

        booksService.deleteBook(this.getBookId());

       

        if(this.getQueryName()==null||this.getQueryValue()==null||this.getQueryName().equals("")||this.getQueryValue().equals("")){

           

        }else{

            queryMap=this.getQueryName()+"~"+this.getQueryValue();

        }

        return SUCCESS;

    }   

   

    public Books getBook() {

        return book;

    }

 

    public void setBook(Books book) {

        this.book = book;

    }

 

    public IBooksService getBooksService() {

        return booksService;

    }

 

    public void setBooksService(IBooksService booksService) {

        this.booksService = booksService;

    }

 

    public Collection getAvailableItems() {

        return availableItems;

    }

 

    public String getCurrentPage() {

        return currentPage;

    }

 

    public void setCurrentPage(String currentPage) {

        this.currentPage = currentPage;

    }

 

    public String getPagerMethod() {

        return pagerMethod;

    }

 

    public void setPagerMethod(String pagerMethod) {

        this.pagerMethod = pagerMethod;

    }

 

    public Pager getPager() {

        return pager;

    }

 

    public void setPager(Pager pager) {

        this.pager = pager;

    }

 

    public String getTotalRows() {

        return totalRows;

    }

 

    public void setTotalRows(String totalRows) {

        this.totalRows = totalRows;

    }

       

    public String getBookId() {

        return bookId;

    }

 

    public void setBookId(String bookId) {

        this.bookId = bookId;

    }

 

    public String getQueryName() {

        return queryName;

    }

 

    public void setQueryName(String queryName) {

        this.queryName = queryName;

    }

 

    public String getQueryValue() {

        return queryValue;

    }

 

    public void setQueryValue(String queryValue) {

        this.queryValue = queryValue;

    }

   

    public String getSearchName() {

        return searchName;

    }

 

    public void setSearchName(String searchName) {

        this.searchName = searchName;

    }

 

    public String getSearchValue() {

        return searchValue;

    }

 

    public void setSearchValue(String searchValue) {

        this.searchValue = searchValue;

    }

   

    public String getQueryMap() {

        return queryMap;

    }

 

    public void setQueryMap(String queryMap) {

        this.queryMap = queryMap;

    }

   

    public PagerService getPagerService() {

        return pagerService;

    }

 

 

    public void setPagerService(PagerService pagerService) {

        this.pagerService = pagerService;

    }   

}

 

com.sterning.books.web.actions.BookAction.java

 

(1)、默认情况下,当请求bookAction.action发生时(这个会在后面的Spring配置文件中见到的),Struts运行时(Runtime)根据struts.xml里的Action映射集(Mapping),实例化com.sterning.books.web.actions.BookAction类,并调用其execute方法。当然,我们可以通过以下两种方法改变这种默认调用。这个功能(Feature)有点类似Struts 1.x中的LookupDispathAction。

 

在classes/sturts.xml中新建Action,并指明其调用的方法;

 

访问Action时,在Action名后加上“!xxx”(xxx为方法名)。

 

(2)、细心的朋友应该可能会发现com.sterning.books.web.actions.BookAction.java中Action方法(execute)返回都是SUCCESS。这个属性变量我并没有定义,所以大家应该会猜到它在ActionSupport或其父类中定义。没错,SUCCESS在接口com.opensymphony.xwork2.Action中定义,另外同时定义的还有ERROR, INPUT, LOGIN, NONE。

 

此外,我在配置Action时都没有为result定义名字(name),所以它们默认都为success。值得一提的是Struts 2.0中的result不仅仅是Struts 1.x中forward的别名,它可以实现除forward外的很激动人心的功能,如将Action输出到FreeMaker模板、Velocity模板、JasperReports和使用XSL转换等。这些都过result里的type(类型)属性(Attribute)定义的。另外,您还可以自定义result类型。

 

(3)、使用Struts 2.0,表单数据的输入将变得非常方便,和普通的POJO一样在Action编写Getter和Setter,然后在JSP的UI标志的name与其对应,在提交表单到Action时,我们就可以取得其值。

 

(4)、Struts 2.0更厉害的是支持更高级的POJO访问,如this.getBook().getBookPrice()。private Books book所引用的是一个关于书的对象类,它可以做为一个属性而出现在BookActoin.java类中。这样对我们开发多层系统尤其有用。它可以使系统结构更清晰。

 

(5)、有朋友可能会这样问:“如果我要取得Servlet API中的一些对象,如request、response或session等,应该怎么做?这里的execute不像Struts 1.x的那样在参数中引入。”开发Web应用程序当然免不了跟这些对象打交道。在Strutx 2.0中可以有两种方式获得这些对象:非IoC(控制反转Inversion of Control)方式和IoC方式。

 

非IoC方式

 

要获得上述对象,关键是Struts 2.0中com.opensymphony.xwork2.ActionContext类。我们可以通过它的静态方法getContext()获取当前Action的上下文对象。另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象。

 

HttpServletRequest request = ServletActionContext.getRequest();

 

HttpServletResponse response = ServletActionContext.getResponse();

 

HttpSession session = request.getSession();

 

如果你只是想访问session的属性(Attribute),你也可以通过ActionContext.getContext().getSession()获取或添加session范围(Scoped)的对象。

 

IoC方式

 

要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。如实现SessionAware, ServletRequestAware, ServletResponseAware接口,从而得到上面的对象。

 

1、对BookAction类的Save方法进行验证

 

正如《Writing Secure Code》文中所写的名言All input is evil:“所有的输入都是罪恶的”,所以我们应该对所有的外部输入进行校验。而表单是应用程序最简单的入口,对其传进来的数据,我们必须进行校验。Struts2的校验框架十分简单方便,只在如下两步:

 

在Xxx-validation.xml文件中的<message>元素中加入key属性;

 

在相应的jsp文件中的<s:form>标志中加入validate="true"属性,就可以在用Javascript在客户端校验数据。

 

其验证文件为:BooksAction-save-validation.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">

<validators>

    <!-- Field-Validator Syntax -->

    <field name="book.bookName">

        <field-validator type="requiredstring">

            <message key="book.bookName.required"/>

        </field-validator>

    </field>

    <field name="book.bookAuthor">

        <field-validator type="requiredstring">

            <message key="book.bookAuthor.required"/>

        </field-validator>

    </field>

    <field name="book.bookPublish">

        <field-validator type="requiredstring">

            <message key="book.bookPublish.required"/>

        </field-validator>

    </field>

</validators>

 com.sterning.books.web.actions.BooksAction-save-validation.xml

1、对BookAction类的Save方法进行验证的资源文件

 

       注意配置文件的名字应该是:配置文件(类名-validation.xml)的格式。BooksAction类的验证资源文件为:BooksAction.properties

 

book=Books

book.bookName.required=/u8bf7/u8f93/u5165/u4e66/u540d

book.bookAuthor.required=/u8bf7/u8f93/u5165/u4f5c/u8005

book.bookPublish.required=/u8bf7/u8f93/u5165/u51fa/u7248/u793e

format.date={0,date,yyyy-MM-dd}

 

com.sterning.books.web.actions.BooksAction.properties

 

       资源文件的查找顺序是有一定规则的。之所以说Struts 2.0的国际化更灵活是因为它可以根据不同需要配置和获取资源(properties)文件。在Struts 2.0中有下面几种方法:

 

(1)、使用全局的资源文件。这适用于遍布于整个应用程序的国际化字符串,它们在不同的包(package)中被引用,如一些比较共用的出错提示;

 

(2)、使用包范围内的资源文件。做法是在包的根目录下新建名的package.properties和package_xx_XX.properties文件。这就适用于在包中不同类访问的资源;

 

(3)、使用Action范围的资源文件。做法为Action的包下新建文件名(除文件扩展名外)与Action类名同样的资源文件。它只能在该Action中访问。如此一来,我们就可以在不同的Action里使用相同的properties名表示不同的值。例如,在ActonOne中title为“动作一”,而同样用title在ActionTwo表示“动作二”,节省一些命名工夫;

 

(4)、使用<s:i18n>标志访问特定路径的properties文件。在使用这一方法时,请注意<s:i18n>标志的范围。在<s:i18n name="xxxxx">到</s:i18n>之间,所有的国际化字符串都会在名为xxxxx资源文件查找,如果找不到,Struts 2.0就会输出默认值(国际化字符串的名字)。

 

例如:某个ChildAction中调用了getText("user.title"),Struts 2.0的将会执行以下的操作:

 

查找ChildAction_xx_XX.properties文件或ChildAction.properties;

 

查找ChildAction实现的接口,查找与接口同名的资源文件MyInterface.properties;

 

查找ChildAction的父类ParentAction的properties文件,文件名为ParentAction.properties;

 

判断当前ChildAction是否实现接口ModelDriven。如果是,调用getModel()获得对象,查找与其同名的资源文件;

 

查找当前包下的package.properties文件;

 

查找当前包的父包,直到最顶层包;

 

在值栈(Value Stack)中,查找名为user的属性,转到user类型同名的资源文件,查找键为title的资源;

 

查找在struts.properties配置的默认的资源文件,参考例1;

 

输出user.title。

原创粉丝点击