Struts2 hello world搭建&Struts知识概要整理

转载请注明出处:
牵手生活--头条新闻:笔记是整理思路方式,分享是一个美德,牵手是我的生活方式
牵手生活--简书:笔记是整理思路方式,分享是一个美德,牵手是我的生活方式

注:如果对idea创建Manven webapp不熟悉,可参见Spring MVC -Hello World(环境搭建)


用idea创建一个maven 的web项目Struts2HelloWorld

新建一个Maven项目-webapp
image.png

注意选择好原型:org.apache.maven.archetypes:maven-archetype-webapp

image.png

next,然后直接finish

在pom.xml中添加Struts2核心框架

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <!--选用最新的版本2.5.5不同版本之后的web.xml文件会有区别 -->
            <version>2.5.5</version>
        </dependency>
添加Strust2依赖

配置web.xml

  <!--struts2过滤器的配置-->
  <filter>
    <filter-name>struts2</filter-name>
    <!--如果Struts2 的2.3.24版本应该是这样的
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    -->
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <!--struts2过滤所有的路径-->
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
image.png

resources资源目录下添加struts.xml文件

创建struts2配置文件
自动创建的struts.xml内容

在project Structure中创建java源码目录与test测试目录

创建java目录与test源码目录

创建一个HelloWorldAction 继承ActionSupport,重写execute方法

Struts2中的Action及时就是一个Controller

image.png

配置struts.xml


<struts>
    <!-- 支持动态调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
    <!-- 设置开发模式 -->
    <constant name="struts.devMode" value="true"/>

    <package name="default" namespace="/" extends="struts-default">
        <action name="helloworld" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/result.jsp</result>
        </action>

        <action name="addAction" method="add" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/add.jsp</result>
        </action>

        <action name="updatection" method="update" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/add.jsp</result>
        </action>

    </package>
</struts>

创建一个与struts.xml配置对应的result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h1> This is result.jsp</h1><br>

    <h1> struts2 hello world</h1>

</body>
</html>

在idea中发布项目并在浏览器中访问

http://localhost:8080/helloworld.action

或(发现默认的情况都会响应)

http://localhost:8080/aa/bbb/helloworld.action
显示struts2的hello world
image.png

访问不存在的Action

http://localhost:8080/aa/bbb/helloworld000.action

访问不存在的Action

到这来我们的Struts hello world的项目已经搭建完成,下面开始介绍Struts2的一些知识。来个知识概要图

Struts2知识概要图
Struts2处理流程

Struts2 动态方法调用-指定method属性

修改HelloWorldAction代码

public class HelloWorldAction extends ActionSupport {
    @Override
    public String execute() throws Exception {
        System.out.println("执行Action");
        /*return super.execute();*/
        return SUCCESS;
    }
    //helloworld.action
    public String add(){
        return SUCCESS;
    }

    //helloworld.action
    public String update(){
        return SUCCESS;
    }

    public String save(){
        return "save";
    }

}

struts.xml中(指定method调用方式)

        <!--
         指定method方法方式
         http://localhost:8080/addAction.action
         -->
        <action name="addAction" method="add" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/add.jsp</result>
        </action>

        <action name="updatection" method="update" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/update.jsp</result>
        </action>

url

http://localhost:8080/addAction.action
image.png

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

访问方法:url+action+"!"+方法名+"action"

struts_helloworld.xml配置(指定感叹号方式)

        <!--
        !感叹号访问方式
        http://localhost:8080/helloworld!save.action
        -->
        <action name="helloworld" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/result.jsp</result>
            <result name="save">/index.jsp</result>
        </action>

url

http://localhost:8080/helloworld!save.action

通配符的访问方式

访问方法:url+action+"_"+方法名+"action"

struts_helloworld.xml配置(通配符的访问方式)

        <!--通配符的支持
          http://localhost:8080/helloworld_save.action
          可以配置多个通配符如: helloworld_*_* method="{1}{2}"
        -->

        <action name="helloworld_*" method="{1}" class="com.younghare.StrutsHelloWorld.action.HelloWorldAction">
            <result name="success">/{1}.jsp</result>
            <result name="save">/{1}.jsp</result>
        </action>

url

http://localhost:8080/helloworld_save.action

默认action -解决当找不到对应的action时,启用默认action

struts_helloworld.xml配置(默认action)

        <!--默认action-->
        <default-action-ref name="index"></default-action-ref>
        <action name="index">
            <result>/error.jsp</result>
        </action>

url

http://localhost:8080/aabbcc.action
image.png

修改struts的后缀,如把.action改为.do或或其他.html伪造界面;而且支持多个后缀同时使用

    <!--修改struts的后缀,如把.action改为.do或或其他.html伪造界面-->
    <constant name="struts.action.extension" value="html"></constant>

在web.xml中配置

struts2—constant常量的配置常用方法

image.png

Struts2通配符详解
Struts2.5动态方法调用action is not allowed
struts.xml和struts.properties详解

image.png

struts2 接收参数--使用Action属性接收

LoginAction.java

public class LoginAction extends ActionSupport {
    private String username ;
    private String password;//注意变量名要与post提交上来的明智一致,否则会包错误


    public String login() throws Exception {
        System.out.println("使用struts的action参数方式接收参数");
        System.out.println("模拟登录操作。。。 用户名:"+username+"密码:"+password);
        return SUCCESS;
    }

    public String getUsername() {

        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

login.jsp

...
<body>

    <h1>       提示:用户名输入admin,密码输入admin正确</h1>

    <form action="loginAction.action" method="post">
        用户名:<input type="text" name="username"><br>
        密码  :<input type="password" name="password"><br>
        <input type="submit" value="提交"><br>

        提示:用户名输入admin,密码输入admin正确

    </form>


</body>
...

struts_helloworld.xml配置(action属性接收方式)

        <action name="loginAction" method="login" 
                class="com.younghare.StrutsHelloWorld.action.LoginAction">
            <result>/success.jsp</result>
        </action>

url

http://localhost:8080/login.jsp
image.png

登录后情况


登录成功看日志

struts2 接收参数--使用Domain Model接收

LoginWithModelAction.java

public class LoginWithModelAction extends ActionSupport {
    private User user;

    public String login() throws Exception {
        System.out.println("使用struts的Domain Model方式接收参数");
        System.out.println("模拟登录操作。。。 用户名:"+user.getUsername()+"密码:"+user.getPassword());
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }


}

loginWithModel.jsp

...
<body>

    <h1>       使用struts的Domain Model方式接收参数</h1>

    <form action="loginWithModelAction.action" method="post">
        用户名:<input type="text" name="user.username"><br>
        密码  :<input type="password" name="user.password"><br>
        <input type="submit" value="提交"><br>

        提示:用户名输入admin,密码输入admin正确

    </form>

</body>
...

struts_helloworld.xml配置(Domain Model方式接收)

        <action name="loginWithModelAction" method="login" 
                class="com.younghare.StrutsHelloWorld.action.LoginWithModelAction">
            <result>/success.jsp</result>
        </action>

url

http://localhost:8080/loginWithModel.jsp
使用Domain Model方式接收参数
使用Domain Model方式成功登录

struts2 接收参数--使用ModelDriven接收

url

http://localhost:8080/loginWithModelDriven.jsp
使用ModelDriven方式接收参数
使用ModelDriven成功登录

LoginWithModelDrivenAction.java

public class LoginWithModelDrivenAction extends ActionSupport implements ModelDriven<User> {
    private User user = new User(); //使用ModelDriven方式接收参数必须对其实例化

    public String login() throws Exception {
        System.out.println("使用struts的ModelDriven方式接收参数");
        System.out.println("模拟登录操作。。。 用户名:"+user.getUsername()+"密码:"+user.getPassword());

        return SUCCESS;
    }

    public User getModel() {
        return user;
    }
}

loginWithModelDriven.jsp

...
<body>
    <h1>模拟Struts2 传递的参数中带有List使用ModelDriven接收参数的例子</h1><br>
    <h1>传递的参数中带有List</h1>

    <form action="loginWithModelDrivenAction.action" method="post">
        用户名:<input type="text" name="username"><br>
        密码  :<input type="password" name="password"><br>

        <input type="submit" value="提交"><br>

        提示:用户名输入admin,密码输入admin正确

    </form>
</body>
...

struts_helloworld.xml配置(ModelDriven接收)

        <action name="loginWithModelDrivenAction" method="login" 
                class="com.younghare.StrutsHelloWorld.action.LoginWithModelDrivenAction">
            <result>/success.jsp</result>
        </action>

struts2 接收参数2--使用ModelDriven接收(对象带List类型)

LoginWithListInModelDrivenAction.java

public class LoginWithListInModelDrivenAction extends ActionSupport implements ModelDriven<UserWithList> {
    private UserWithList userWithList = new UserWithList(); //使用ModelDriven方式接收参数必须对其实例化

    public String login() throws Exception {
        System.out.println("使用struts的ModelDriven方式接收参数,参数中带有List");
        System.out.println("模拟登录操作。。。 用户名:"+userWithList.getUsername()+"密码:"+userWithList.getPassword());
        System.out.println("书籍有:"+userWithList.getBookList().get(0));
        return SUCCESS;
    }


    public UserWithList getModel() {
        return userWithList;
    }
}

loginWithListInModelDriven.jsp

...
<body>
    <h1>模拟Struts2 使用ModelDriven接收参数的例子</h1><br>
    
    <h1>对象中带有List变量</h1>

    <form action="loginWithListInModelDrivenAction.action" method="post">
        用户名:<input type="text" name="username"><br>
        密码  :<input type="password" name="password"><br>
        书籍  :<br>
        java核心  :<input type="text" name="bookList[0]"><br>
        Android 解密  :<input type="text" name="bookList[1]"><br>

        <input type="submit" value="提交"><br>

        提示:用户名输入admin,密码输入admin正确

    </form>
</body>
...

struts.xml配置

        <action name="loginWithListInModelDrivenAction" method="login" 
                class="com.younghare.StrutsHelloWorld.action.LoginWithListInModelDrivenAction">
            <result>/success.jsp</result>
        </action>

url

http://localhost:8080/loginWithListInModelDriven.jsp
ModelDriven中对象含义List
image.png

Struts2的处理结果只Input

url

http://localhost:8080/loginInput.jsp

效果:
如果正确,如38则会调整到正确的登录页面,
否则会留在本页面,不过url地址会发生变化

登录界面

正确的就不截图了,把错误的截图处理


image.png
image.png

image.png

LoginInputAction.java

public class LoginInputAction extends ActionSupport implements ModelDriven<User>{
    private User user = new User();

    public String login() throws Exception {
        if(user.getUsername() ==null
                ||"".equals(user.getUsername().trim())){
            this.addFieldError("username","用户名为空");
            return INPUT;
        }

        System.out.println("使用struts的ModelDriven方式接收参数");
        System.out.println("模拟登录操作。。。 用户名:"+user.getUsername()+"密码:"+user.getPassword());
        return SUCCESS;
    }


    public User getModel() {
        return user;
    }
}

loginInput.jsp

<%--struts扩展标签--%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
...
<body>
    模拟Struts2 传递的参数中带使用ModelDriven接收参数的例子<br>
    本页主要用于处理Struts2返回值之----input
    <h1>演示效果是如果填入年龄(int型),</h1>
    <h1>如果正确,如38则会调整到正确的登录页面()</h1>
    <h1>否则会留在本页面,不过url地址会发生变化</h1>

    <form action="loginInputAction.action" method="post">
        <%--注意s标签--%>
        用户名:<input type="text" name="username"><br><s:fielderror name="username"></s:fielderror>
        密码  :<input type="password" name="password"><br>
        年龄  :<input type="text" name="age"><br>
        <input type="submit" value="提交"><br>

        提示:<br>
        1:年龄输入非法字符用自动返回到本页,用户名不能为空

    </form>
</body>
...

struts_helloworld.xml配置(Struts2 返回值input返回值)

        <!--Struts 处理结果只input-->
        <action name="loginInputAction" method="login"
                class="com.younghare.StrutsHelloWorld.action.LoginInputAction">
            <result>/success.jsp</result>
            <result name="input">/loginInput.jsp</result>
        </action>

遗留问题其他看一个错误
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

structs2和lo4j2的问题
java项目中Classpath路径到底指的是哪里
Intellij IDEA 配置最简单的maven-struts2环境的web项目

预留扩展知识:

源码下载

https://yunpan.360.cn/surl_yQbyGe6wTP3 (提取码:b082)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概述 什么是Struts2的框架Struts2是Struts1的下一代产品,是在 struts1和WebWork的...
    inke阅读 2,271评论 0 50
  • spring mvc 工作机制(原理): DispatcherServlet主要用作职责调度工作,本身主要用于控制...
    java大湿兄阅读 1,914评论 5 24
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,742评论 18 399
  • 男人喜欢赌博,把家里值钱的东西都拿去赌了。 女人还是对他不离不弃。因为他们有个两个月的女孩。 这一天,女人和男人发...
    朱黛阅读 178评论 0 0
  • 我把我的梦给了你 却遗失了自己 冬夜总归漫长 有时候不愿自己醒来 只是因为醒来就没有了你 我把我的梦给了你 却抛弃...
    伊苏灬卡尔阅读 780评论 4 2