前言
本章讲解Struts2的环境配置
方法
1.导入Struts2的相关jar包
2.在web.xml中配置Struts2分发过滤器
特别的:这和SpringMVC配置DispatcherServlet的Servlet很相似
<?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.ng.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>
3.配置Struts2配置文件
Struts2的配置文件名称为: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="default" namespace="/" extends="struts-default">
<action name="hello" class="cn.edu.ccut.action.TestAction">
<result name="success">test.jsp</result>
</action>
</package>
</struts>
4.编写TestAction.java
特别的:这里的java文件相当于SpringMVC的controller文件,所以包名建议为xx.xx.action
package cn.edu.ccut.action;
public class TestAction {
public String execute(){
System.out.println("Hello World");
return "success";
}
}
注意:这里的方法默认为execute(),当然也可以自主的去定义,这里暂时以他为例进行说明!
5.配置测试页面test.jsp
配置action跳转的页面如下所示:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Test</title>
</head>
<body>
Hello World
</body>
</html>
6.启动程序测试
输入以下网址进行测试:
我们发现,可以正确的跳转到指定的页面!