Struts.xml configuration for Struts2 project construction (4)

illustrate

1. This article introduces the struts.xml configuration of Struts2 - dynamic method call
2. This article introduces the struts.xml configuration of Struts2 - specify multiple configuration files
3. This article introduces the struts.xml configuration of Struts2 - Configure the default Action in Struts2
4. This article introduces Struts2's struts.xml configuration - Struts2 access suffix settings

Ready to work

LoginAction section

package login.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import login.entity.LoginEntity;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import util.log4j.MyLog4J;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 创建日期:2018年03月04日
 * 创建时间:10:15
 * 项目名称:DEMO
 */
public class LoginAction extends ActionSupport implements ModelDriven<LoginEntity> {
    private Logger myLog4J = MyLog4J.getLog(this.getClass());
    private LoginEntity loginEntity = new LoginEntity();

    @Override
    public String execute() throws Exception {
        String result;
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        ServletContext application = ServletActionContext.getServletContext();
        if (loginEntity != null && loginEntity.getUserName() != null && loginEntity.getUserPassword() != null) {
            if (loginEntity.getUserName().equals("erciyuan") && loginEntity.getUserPassword().equals("12345678")) {
                //登入成功后的欢迎提示
                request.setAttribute("request_hello", "登入成功,欢迎来到Struts2首页");
                result = SUCCESS;
            } else {
                //保存账号和密码
                session.setAttribute("session_username", loginEntity.getUserName());
                session.setAttribute("session_userPassword", loginEntity.getUserPassword());
                //网站访问量
                Integer integer = (Integer) application.getAttribute("application_counter");
                integer = integer == null ? 1 : ++integer;
                application.setAttribute("application_counter", integer);
                myLog4J.info(String.valueOf(integer));
                if (loginEntity != null)
                    loginEntity.setIsLogin("用户名或密码错误");
                result = LOGIN;
            }
        } else {
            result = LOGIN;
        }
        return result;
    }

    public LoginEntity getModel() {
        return loginEntity;
    }
}

1. Dynamic method invocation

three ways

  • Specify the method attribute
  • Exclamation mark (!) method (deprecated)
  • Wildcard method (recommended)

Specify the method attribute

struts.xml

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <include file="struts-default.xml"/>
    <package name="login.action.LoginAction" extends="struts-default" namespace="/">
        <action name="login" class="login.action.LoginAction" method="execute">
            <result name="success" type="dispatcher">/login/login.jsp</result>
            <result name="login" type="dispatcher">/index.jsp</result>
        </action>
    </package>
</struts>

Exclamation mark (!) method (deprecated)

struts.xml section

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <include file="struts-default.xml"/>
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
    <package name="login.action.LoginAction" extends="struts-default" namespace="/">
        <action name="login" class="login.action.LoginAction">
            <result name="success" type="dispatcher">/login/login.jsp</result>
            <result name="login" type="dispatcher">/index.jsp</result>
        </action>
    </package>
</struts>

Enter http://localhost:8080/login!execute.action after startup

Wildcard method (recommended)

struts.xml section

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <include file="struts-default.xml"/>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <package name="login.action.LoginAction" extends="struts-default" namespace="/">
        <action name="*_*_*" class="{1}.action.{2}Action" method="{3}">
            <result name="success" type="dispatcher">/login/login.jsp</result>
            <result name="login" type="dispatcher">/index.jsp</result>
        </action>
    </package>
</struts>

LoginAction section

package login.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import login.entity.LoginEntity;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import util.log4j.MyLog4J;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 创建日期:2018年03月04日
 * 创建时间:10:15
 * 项目名称:DEMO
 */
public class LoginAction extends ActionSupport implements ModelDriven<LoginEntity> {
    private Logger myLog4J = MyLog4J.getLog(this.getClass());
    private LoginEntity loginEntity = new LoginEntity();
    private HttpServletRequest request = ServletActionContext.getRequest();
    private HttpSession session = request.getSession();
    private ServletContext application = ServletActionContext.getServletContext();

    public String index() {
        if (request != null)
            request.removeAttribute("request_hello");
        if (session != null) {
            session.removeAttribute("session_username");
            session.removeAttribute("session_userPassword");
        }
        if (application != null)
            application.removeAttribute("application_counter");
        return LOGIN;
    }

    public String login() {
        String result;

        if (loginEntity != null && loginEntity.getUserName() != null && loginEntity.getUserPassword() != null) {
            if (loginEntity.getUserName().equals("erciyuan") && loginEntity.getUserPassword().equals("12345678")) {
                //登入成功后的欢迎提示
                request.setAttribute("request_hello", "登入成功,欢迎来到Struts2首页");
                result = SUCCESS;
            } else {
                //保存账号和密码
                session.setAttribute("session_username", loginEntity.getUserName());
                session.setAttribute("session_userPassword", loginEntity.getUserPassword());
                //网站访问量
                Integer integer = (Integer) application.getAttribute("application_counter");
                integer = integer == null ? 1 : ++integer;
                application.setAttribute("application_counter", integer);
                myLog4J.info(String.valueOf(integer));
                if (loginEntity != null)
                    loginEntity.setIsLogin("用户名或密码错误");
                result = LOGIN;
            }
        } else {
            result = LOGIN;
        }
        return result;
    }

    public LoginEntity getModel() {
        return loginEntity;
    }
}

login.jsp section

<%@ page contentType="text/html;charset=GBK" language="java" %>
<html>
<head>
    <title>登入成功界面</title>
</head>
<body>
<%--接收request参数--%>
<div>
    ${request_hello}
    <a href="<%=request.getContextPath()%>/login/docs/index.html">Struts2官方教程</a>

    <form action="login_Login_index.action">
        <%--返回首页,并且注销登入--%>
        <button type="submit">完全退出</button>
    </form>
    <a href=""></a>
</div>
</body>
</html>

index.jsp section

<%@ page contentType="text/html;charset=GBK" language="java" %>
<%
    Object str = application.getAttribute("application_counter");
    str = str != null ? "第" + str + "次访问此页面" : "";
%>
<html>
<head>
    <title>登入界面</title>
</head>
<body>
<form action="login_Login_login.action" name="login.LoginAction">
    <%--接收session参数--%>
    <input type="text" id="login_user_name" name="userName" placeholder="请输入用户名" value="${session_username}"/>
    <input type="password" id="login_user_password" name="userPassword" placeholder="请输入密码"
           value="${session_userPassword}"/>

    <div id="login_is_userName">${isLogin}</div>
    <%--接收application参数--%>
    <div id="login_counter">
        <%=str%>
    </div>
    <input type="submit" id="login" value="登入"/>
</form>
</body>
</html>

Specify multiple configuration files

struts.xml section

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <include file="struts-default.xml"/>
    <include file="login.xml"/>
</struts>

login.xml part (same directory as struts.xml)

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

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
        <package name="login.action.LoginAction" extends="struts-default" namespace="/">
                <action name="*_*_*" class="{1}.action.{2}Action" method="{3}">
                        <result name="success" type="dispatcher">/login/login.jsp</result>
                        <result name="login" type="dispatcher">/index.jsp</result>
                </action>
        </package>
</struts>

Configure the default Action in Struts2

1. When the accessed Action does not exist, the page will display an error message, and you can configure the default Action to handle the user's abnormal operation;
2. Configuration method:
Add the following content under <package> in the struts.xml file:
<default- action-ref name="default_name"></default-action-ref>
where default_name is the name attribute value of the default Action;
3. After configuring the default Action, if there is no Action to be accessed in the corresponding namespace, it will automatically jump to Default Action handling.

login.xml deployment

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

<struts>
    <package name="login.action.LoginAction" extends="struts-default" namespace="/">
        <default-action-ref name="login"/>
        <action name="login" class="login.action.LoginAction" method="index">
            <result name="login" type="dispatcher">/index.jsp</result>
        </action>
        <action name="*_*_*" class="{1}.action.{2}Action" method="{3}">
            <result name="success" type="dispatcher">/login/login.jsp</result>
            <result name="login" type="dispatcher">/index.jsp</result>
        </action>
    </package>
</struts>

Entering a non-existent action test, http://localhost:8080/cc.action , will enter the exact same result as http://localhost:8080/login.action , and log out the user, which can be used to illegally access the website

Struts2 access suffix settings

Three ways to set the suffix

  • Add in struts.xml file (recommended)
  • Add in struts.properties
  • Add a warning to the filter of web.xml
    : Do not use all three methods together in the project, otherwise web.xml has the highest priority. If you configure one less suffix, you may not get the correct jump and cause an error

add in struts.xml file

struts.xml section

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <include file="struts-default.xml"/>
    <include file="login.xml"/>
    <constant name="struts.action.extension" value="do,to"/>
</struts>

login section

<%@ page contentType="text/html;charset=GBK" language="java" %>
<html>
<head>
    <title>登入成功界面</title>
</head>
<body>
<%--接收request参数--%>
<div>
    ${request_hello}
    <a href="<%=request.getContextPath()%>/login/docs/index.html">Struts2官方教程</a>

    <form action="login_Login_index.to">
        <%--返回首页,并且注销登入--%>
        <button type="submit">完全退出</button>
    </form>
    <a href=""></a>
</div>
</body>
</html>

index.jsp section

<%@ page contentType="text/html;charset=GBK" language="java" %>
<%
    Object str = application.getAttribute("application_counter");
    str = str != null ? "第" + str + "次访问此页面" : "";
%>
<html>
<head>
    <title>登入界面</title>
</head>
<body>
<form action="login_Login_login.do" name="login.LoginAction">
    <%--接收session参数--%>
    <input type="text" id="login_user_name" name="userName" placeholder="请输入用户名" value="${session_username}"/>
    <input type="password" id="login_user_password" name="userPassword" placeholder="请输入密码"
           value="${session_userPassword}"/>

    <div id="login_is_userName">${isLogin}</div>
    <%--接收application参数--%>
    <div id="login_counter">
        <%=str%>
    </div>
    <input type="submit" id="login" value="登入"/>
</form>
</body>
</html>

Add in struts.properties

struts.action.extension=do,to,

Add in the filter of web.xml

web.xml section

<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.action.extension</param-name>
            <param-value>do</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>











I am a programmer. If you think it's well organized, please pay attention to your personal WeChat public account (scan it):

Guess you like

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