Struts2入门--环境搭建(IDEA版)

一、搭建 struts2 项目步骤前端

  • 新建Java项目--输入项目名称/项目路径

  

  • 目录结构以下:将lib文件夹复制到web-inf下(不然发布不到Tomcat)

  

  • 配置web.xml(filter-class中需与导入的Struts2的jar包中的一致,此处删除了.ng

  • 配置Struts.xml(IDEA建立Struts2项目会自动生成)

  

  •  修改index.jsp

  

  • 运行成功

  

二、添加页面java

  • 编写 Action 类--HelloAction(在src下建立cn.ht.action.HelloAction类)
package cn.ht.action; /** * @Classname HelloAction * @Description TODO * @Date 2019-8-12 16:12 * @Created by Administrator * Struts2的第一个案例 */
public class HelloAction { // 在Struts2中,全部的业务方法都是public // 返回值都为string类型,全部业务方法都没有参数 // 方法名能够自定义,默认为execute
    public String execute(){ System.out.println("hello struts2"); return "success"; } }

注:在 servlet 中,默认执行 service 方法。在 struts2 中,默认执行 execute 方法。
在 servlet 中,service 方法参数时 HttpServletRequest 和 HttpServletResponse,无返回
值。在 struts2 中,方法都是 public 的,而且返回值都是 String 类型,并且方法都是没
有参数的。web

  • 配置 action 类--在 struts.xml
<?xml version="1.0" encoding="UTF-8"?>

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

<struts>
    <package name="default" namespace="/" extends="struts-default">
        <!--配置action 配置url和处理类的方法进行映射 -->
        <action name="hello" class="cn.ht.action.HelloAction">
            <result>/hello.jsp</result>
        </action>
    </package>


</struts>
  • 配置 struts2 的核心控制器 web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd" version="4.0">
    <!--配置Struts2的前端控制器-->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
View Code
  • 访问:http://localhost:8080/StrutsTest_war_exploded/hello.action

  结果:apache

  

相关文章
相关标签/搜索