Struts 2中标签的用法

0.建立项目

建立项目并使用myeclipse自带的工具配置Struts 2。我的项目名为Ex3

1.创建Student类

包含姓名和年龄两个属性,自动生成其getter和setter,再自己写一个构造函数

package org.vo;

public class Student {
    private String name;
    private int age;
    public Student(String name ,int age){
        super();
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

2.实现Comparator

package org.cmp;

import java.util.Comparator;

import org.vo.Student;

public class Cmp implements Comparator<Student>{
    public int compare(Student stu1, Student stu2) {
        //根据年龄排序
        return  stu1.getAge()-stu2.getAge();
    }
}

3.用Action创建List

(试了很多方法发现不能在jsp中完成这一操作,所以只能用Action)

package org.action;

import java.util.ArrayList;
import java.util.List;

import org.vo.Student;

import com.opensymphony.xwork2.ActionSupport;

public class SortTagAction extends ActionSupport{

    private List students = new ArrayList();
    public String execute(){
        Student stu1=new Student("张灿",20);
        Student stu2=new Student("刘志杰",19);
        Student stu3=new Student("彭涛",21);
        Student stu4=new Student("鲁荣明",18);

        students.add(stu1);
        students.add(stu2);
        students.add(stu3);
        students.add(stu4);

        return SUCCESS;
    }
    public List getStudents() {
        return students;
    }
    public void setStudents(List students) {
        this.students = students;
    }
}

4.使用sort标签进行排序

以下是sort.jsp的代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

<html>
  <head>
    <title>sort.jsptitle>
  head>
  <body>
    <s:bean name="org.cmp.Cmp" id="cmp"/>
    <s:sort comparator="cmp" source="students" id="sort">
            <s:iterator>  
                    <s:property value="name"/>  
                    <s:property value="age"/>
                    <br>
            s:iterator> 
    s:sort>
  body>
html>

5.修改struts.xml



<struts>
    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
        <action name="sortTagAction" class="org.action.SortTagAction" >
            <result name="success">sort.jspresult>
        action>
    package>

struts>    



一个简单的sort标签就写完了,使用tomcat 8发布项目后,在浏览器输 http://localhost:8080/Ex3/sortTagAction.action,显示效果如下:
Struts 2中标签的用法_第1张图片



参考:
[1]郑阿奇.Java EE实用教程[M].北京:电子工业出版社,2015.2:67-68
[2] http://www.yiibai.com/struts_2/struts-2-sort-tag-example.html

你可能感兴趣的:(Struts,2)