创建工程并导包
书写Action类
public class HelloAction {
public String hello() {
System.out.println("hello world!");
return "success";
}
}
书写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="hello" namespace="/hello" extends="struts-default">
<action name="HelloAction" class="pers.zhang.Action.HelloAction" method="hello">
<result name="success">/hello.jsp</result>
</action>
</package>
</struts>
在web.xml中配置Struts2核心过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>StrutsDemo</display-name>
<!-- Struts2核心过滤器 -->
<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>
</web-app>
测试:
部署项目到服务器,访问:
http://localhost:8080/ + 项目名 + struts配置中package的namespace属性 + / + action中的name属性
后台打印:
hello world!
前台页面显示: