<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近刚刚开始学习Struts2,学了Struts2里的一些结构原理,来总结复习一下</span>
各种配置做好后有三个文件:struts.xml,web.xml,Hello.jsp
web.xml的主要代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
struts.xml的主要代码如下:
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="hello">
<result >
/Hello.jsp
</result>
</action>
</package>
<!-- Add packages here -->
</struts>
Hello.jsp的主要代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>HelloStruts2</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
Hello Struts2 <br>
</body>
</html>
将工程部署到Tomcat上并运行后,访问:http://localhost:8080/test(项目名称)/hello.action 就可以了
那这三个文件之间是怎么运用的呢?
http://localhost:8080/test(项目名称)/hello.action 分解开就是 前面是Tomcat :localhost:8080,然后是项目:/test(项目名称),然后是namespace: /,然后是action:hello.action。
当访问 /test(项目名称)时,就会到该项目里的web.xml中去寻找,找到struts2然后看下一个,也就是namespace,我们的namespace是“/” 就到struts.xml中去看namespace,找到相符的namespace,就是这段代码
<package name="default" namespace="/" extends="struts-default">
找到后,就是action,我们要访问的action名称为hello,就找到
<action name="hello">
<result >
/Hello.jsp
</result>
</action>
然后是里面的result :Hello.jsp于是返回Hello.jsp的内容