Struts2 的入门案例配置

1. 导入所需jar包(链接:https://pan.baidu.com/s/1ZvsdZIxJmodV_dNEusGcXQ 提取码:o5i2 )里的基础包

2. 在classpath下(src下)新建 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="p1" extends="struts-default">
        <action name="hello" class="com.ljq.web.action.HelloAction" method="sayHello">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>
View Code

3. 在web.xml 中配置过滤器,在标签<display-name>结束后,添加:

  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

4. 写acton类 com.ljq.web.action.HelloAction

package com.ljq.web.action;

public class HelloAction {
    /*
     * 动作方法:1、public 2、返回String 3、无参数
     *  函数名称 、返回值  与 struts.xml 中的配置对应
     */
    public String sayHello(){
        System.out.println("hello ...");
        return "success";
    }
}

在 WebContext 或 WebRoot 下 ,写 index.jsp

<%@ page language="java"  pageEncoding="UTF-8"%>
<!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>Struts2的入门案例</title>
</head>
<body>
<%-- 在Struts2中,控制器会默认拦截扩展名为.action的请求(以.action为后缀的url)。除此之外,什么都不写也可以 --%>
    <a href="${pageContext.request.contextPath }/hello.action">struts2 的第一个实例</a>
    <a href="${pageContext.request.contextPath }/hello">struts2 的第一个实例 (不带.action)</a>
</body>
</html>

5. 部署tomcat,浏览器浏览

常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。

昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
原文地址:https://www.cnblogs.com/htj10/p/13415310.html