Struts2入门案例

1.导入Struts2的核心jar包。

2.配置web.xml文件

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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">
<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>

3.在src目录下创建一个包,在包下创建HelloWorldAction类

package cn.itcat.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport{
public String execute()throws Exception{
return SUCCESS;
}

}

4.配置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="/" extends="struts-default">
<action name="helloWorld" class="cn.itcat.action.HelloWorldAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>

5.在WebContent下创建一个请求页面和结果返回页面

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
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>首页</title>
</head>
<body>
<h1>Welcome to Struts2</h1>
<a href="${pageContext.request.contextPath}/helloWorld.action">Hello World</a>
</body>
</html>

返回页面:success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
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>SUCCESS</title>
</head>
<body>
跳转成功!
</body>
</html>

处理过程总结:

一,客户端发起一个请求

二,程序读取web.xml中核心控制器的配置信息

三,核心控制器读取struts.xml中的配置信息,并且找到处理该请求的Action。

四,参数通过拦截器传给Action,Action执行execute方法,并将结果传给核心控制器,核心控制器读取配置信息,找到结果的展示视图。

原文地址:https://www.cnblogs.com/litingshi/p/6422392.html