SSH Combat OA 05: Struts2 Tags

Struts2 tag library provides theme and template support, which greatly simplifies the writing of view pages. Moreover, struts2 themes and templates provide good extensibility. Better code reuse is achieved. Struts2 allows the use of custom components in the page, which can fully meet the complex and changeable needs of the page display in the project. This article only gives the usage of commonly used struts tags. These tags are classified as: general tags, control flow tags, ajax tags, UI tags, etc.

Create a new TagsAction.java under the built Struts2 project, the code is as follows:

import com.opensymphony.xwork2.ActionSupport;

public class TagsAction extends ActionSupport {

    private String password;

    private String username;

    private String id;

    public TagsAction() {
    }

    @Override
    public String execute() throws Exception {
        this.addFieldError("fielderror.test", "用户名或密码出错!");

        return this.SUCCESS;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

The logic of this action is very simple. It overrides the code logic of the execute() method of the parent class and returns an error message and a SUCCESS view to the front end. This action has 3 properties, namely: username, password, id, and generates the corresponding getter/setter methods. In addition, the action has an empty constructor.

The struts.xml configuration file is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <!--
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    -->
    <!--
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
    -->

    <constant name="struts.devMode" value="true" />
    <constant name="struts.ui.theme" value="simple" />

    <package name="tags" extends="struts-default">
        <action name="tagsAction" class="com.shizongger.tags.TagsAction">
            <result>/tags.jsp</result>
        </action>
    </package>    
</struts>

The focus of this article is on the tags of struts, so struts.xml does the simplest configuration, only configures one action, and defines a front-end return view tags.jsp.

The initial state of tags.jsp is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Struts-Tags学习案例</title>
</head>
<body>
    <ol>
        <li>property:<s:property value="username" /></li>
    </ol>
</body>
</html>

Using struts2 tags, the introduction of struts2 taglib is the first step. Appealing jsp code is the simplest usage of property.
Enter the following link in your browser:

http://localhost:8080/StrutsTags/tagsAction.action?username=u&password=p

The server will output to the front-end browser

property: u

property usage

The common methods of property are as follows:

<li>property:<s:property value="username" /></li>
<li>property取值为字符串:<s:property value="'username'"/></li>
<li>property设置默认值:<s:property value="id" default="没有id" /></li>
<li>property设定html:<s:property value="'<hr />'" escape="false" /></li>
<hr />

The li in the first line is our commonly used OGNL expression to take out the value of username, and the value value is the OGNL expression . The usage of the second line is to output 'username' as a string instead of expecting the struts tag to parse our string. The third line has an additional default attribute value. When no id is passed in as a parameter, the content in the defalut is displayed, and when an id value is passed in, the id value is displayed. Such as the following two case output:

url:

http://localhost:8080/StrutsTags/tagsAction.action?username=u&password=p&id=1

output:

property set default value: 1

url:

http://localhost:8080/StrutsTags/tagsAction.action?username=u&password=p

property set default value: no id

The property usage in the fourth li, when escape is true, the value of value is regarded as a normal character output, and when escape is false at that time, the browser will parse it as an html tag. For example, if the appealed escape is false, then the browser will As the tag < hr /> to output, there is an extra line.

set tag usage

<li>set 设定adminName值(默认为request 和 ActionContext): <s:set var="adminName" value="username" /></li>
<li>s标签从request中取出adminName:<s:property value="#request.adminName" /></li>
<li>s标签从ActionContext中取出adminName:<s:property value="adminName" /></li>
<li>s标签从ActionContext中取出adminName:<s:property value="#adminName" /></li>
<li>set 设定var,范围为ActionContext: <s:set var="adminPassword" value="password" scope="reqeust" /></li>
<li>使用#取出adminPassword:<s:property value="#adminPassword" /></li>
<li>从session取出:<s:property value="#session.adminPassword" /></li>
<li>从request取出:<s:property value="#request.adminPassword" /></li>
<hr />

The main function of the set tag is to define variables in the jsp page. In this case, we assign the username value passed in by the parameter to the variable adminName, and then use the property method to get the value from the scope. The first li is the usage of set assignment, and the 2nd to 4th are usages of taking out the set. Need to pay attention to the usage of the scope with the specified scope. When we specify the scope of the variable, we need to specify our scope when taking it out.

Use of bean and param tags

        <li>bean 定义bean,并使用param来设定新的属性值:
            <s:bean name="com.shizongger.tags.Dog">
                <s:param name="name" value="大黄" />
                <s:property value="name" />
            </s:bean>
        </li>
        <li>bean 查看debug情况:
            <s:bean name="com.shizongger.tags.Dog" var="myDog">
                <s:param name="name" value="'Sam'" />
            </s:bean>
            取出值:<s:property value="#myDog.name" />
        </li>
        <hr />

Our javaBean Dog is used here, and the code of Dog is as follows:

public class Dog {
    private String name;

    public Dog() {
        System.out.println("Dog无参构造方法");
    }

    public Dog(String name) {
        System.out.println("Dog有参构造方法,name = " + name);

        this.name = name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("name = " + name);

        this.name = name;
    }

    @Override
    public String toString() {
        return "Dog [name=" + name + "]";
    }

}

The Dog class has only one name property, an empty constructor and a constructor with parameters, and overrides the toString method. Of course, the output statement of this class is to better see the parameter output, you can also remove the output statement.

The name of the jsp bean tag specifies the full path of the Dog class, and the param tag assigns its properties. Since I assigned the value of "rhubarb" to the dog's name attribute, you can see it with the debug tag:
write picture description here

Simultaneous page output:

The bean defines the bean and uses param to set the new property value:
bean View the debug situation: Take out the value: Sam

include tag

        <li>include mydemo1.html 包含静态英文页面
            <s:include value="/myDemo1.html"></s:include>
        </li>
        <li>include mydemo2.html 包含静态中文页面
            <s:include value="/myDemo2.html"></s:include>
        </li>
        <li>include _include1.html 包含静态英文文件,说明%用法
        <s:set var="incPage" value="%{'/myDemo1.html'}" />
        <s:include value="%{#incPage}"></s:include>
        </li>
        <hr />

The usage of the inlcude tag of struts is similar to that of the include of jsp. The two static html files for appeal are as follows:
myDemo1.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>_include1.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=GB18030">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
    <h3>This is the head</h3>
    <p>This is a Paragram.</p>
  </body>
</html>

myDemo2.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>_include1.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=GB18030">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
    <h3>This is the head</h3>
    <p>中文字符的段落.</p>
  </body>
</html>

Maybe due to the version bug, English static html can be loaded normally, but Chinese static html is not loaded normally. It is recommended to use the include statement that comes with jsp.

Usage of if elseif else tag

        <li>if elseif else的用法:
            sex参数的值是=<s:property value="#parameters.sex[0]"/><br />
            将parameters.sex[0]的值赋到age变量中去<s:set name="sex" value="#parameters.sex[0]"></s:set><br />
            用户性别=<s:if test="#sex == 1"></s:if>
                   <s:elseif test="#sex == 2"></s:elseif>
                   <s:else>未知</s:else>
        </li>
        <li>username是否为空:
            <s:if test="#parameters.username == null"></s:if>
            <s:else></s:else>
        </li>
        <hr />

What the hell are the parameters used here? It is the parameter passed by our url. There is a method getParamters(String str) in HttpServletRequest, which gets the jsp from the parameters and passes the parameters to the Servlet.
The logic of this code snippet is to first obtain the parameters.sex[0] parameter from the url, assign it to the sex variable, and then use the struts judgment tag to judge the value of sex. If sex is equal to 1, it is male, if sex is equal to 2, it is female, and the others are output unknown.
In this case the url I entered is as follows:

http://localhost:8080/StrutsTags/tagsAction.action?username=u&password=p&sex=1

The browser output is as follows:

  • Usage of if elseif else: The value of the sex parameter is = 1, and the value of
    parameters.sex[0] is assigned to the age variable.
    User gender = male
  • Is username empty: no

iterate over the collection

        <li>遍历集合:<br />
        <s:iterator value="{'hello','to','struts','tags'}">
            <s:property/>
        </s:iterator>
        </li>       
        <li>自定义变量:<br />
            <s:iterator value="{'this','is','the','self','define','struts','tags'}" var="word">
                <s:property value="#word.toUpperCase()"/>
            </s:iterator>!
        </li>
        <li>使用status:<br />
            <s:iterator value="{'this','is','the','self','define','struts','tags'}" status="status">
                <s:property/>->
                已经遍历了元素的个数:<s:property value="#status.count" /> . 
                元素的索引:<s:property value="#status.index" /> . 
                当前是偶数?:<s:property value="#status.even" /> . 
                当前是奇数? :<s:property value="#status.odd" /> .
                是否是集合第一个元素?:<s:property value="#status.first" /> . 
                是否是集合最后一个元素? :<s:property value="#status.last" />
                <br />
            </s:iterator>
        </li>
        <li>
            <s:iterator value="#{001:'root', 002:'admin', 003:'shizongger'}">
                key = <s:property value="key"/> ,value = <s:property value="value" /><br />
            </s:iterator>
        </li>
        <li>
            <s:iterator value="#{001:'Sam', 002:'Big Huang',003:'Perk'}" var="dog">
                key = <s:property value="#dog.key" /> ,value = <s:property value="#dog.value" /><br />
            </s:iterator>
        </li>
        <hr />

Collection traversal is often used in project development. The first li gives the simplest collection traversal method. The second li tag assigns each element of the collection to the variable word, and then outputs it. The status usage of the third li can display the status of the current element.
The labels under the 4th and 5th li show the usage of map. By nesting the property label in the iteration label s:iterator, you can take out the key value in turn, then take out the value, and take out the key-value of the map in turn.
The final browser output is as follows:
write picture description here
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325980930&siteId=291194637