Struts2项目搭建之struts.xml配置(四)

说明

1.本文介绍Struts2的struts.xml配置-动态方法调用
2.本文介绍Struts2的struts.xml配置-指定多个配置文件
3.本文介绍Struts2的struts.xml配置-Struts2中配置默认Action
4.本文介绍Struts2的struts.xml配置-Struts2 访问后缀设置

准备工作

LoginAction 部分

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.动态方法调用

三种方式

  • 指定method属性
  • 感叹号(!)方式(不推荐使用)
  • 通配符方式(推荐使用)

指定method属性

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>

感叹号(!)方式(不推荐使用)

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"/>
    <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>

启动后输入http://localhost:8080/login!execute.action

通配符方式(推荐使用)

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"/>
    <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部分

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部分

<%@ 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部分

<%@ 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>

指定多个配置文件

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>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <include file="struts-default.xml"/>
    <include file="login.xml"/>
</struts>

login.xml部分(和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>

Struts2中配置默认Action

1.当访问的Action不存在时,页面会显示错误信息,可以通过配置默认Action处理用户异常的操作;
2.配置方法:
在struts.xml文件中的<package>下添加如下内容:
<default-action-ref name="default_name"></default-action-ref>
其中default_name为默认Action的name属性值;
3.配置默认Action后,相应的namespace下不存在要访问的Action时,自动跳转到默认Action处理。

login.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="/">
        <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>

输入一个不存在的action测试,http://localhost:8080/cc.action,会进入和http://localhost:8080/login.action完全一样的结果,并且注销用户,可以用于非法访问网站

Struts2 访问后缀设置

三种方式可以设置后缀

  • 在struts.xml文件中添加(推荐)
  • 在struts.properties中添加
  • 在web.xml的过滤器中添加
    警告:请勿三种方式都一起使用到项目中,否则web.xml优先级最高,如果少配置一个后缀将会有可能得不到正确的跳转导致报错

struts.xml文件中添加

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>
    <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部分

<%@ 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部分

<%@ 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>

在struts.properties中添加

struts.action.extension=do,to,

在web.xml的过滤器中添加

web.xml部分

<?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>











本人是一枚程序猿,如果觉得整理的不错,请关注个人微信公众号(扫一扫):

猜你喜欢

转载自blog.csdn.net/huyingzuo/article/details/80117055