要求:Struts需要Servlet2.4及以上版本,需要JSP2.0及以上版本,需要java7以上版本
我们的第一个申请
1.创建一个名为basic_struts的动态web项目
2.在WenContent文件夹下新建index.jsp
在index.jsp下有以下内容:
此时,我们启动Tomcat,在浏览器地址栏里输入 http://localhost:8080/basic_struts/index.jsp 并回车
我们应该能看到以下内容:
3.添加运行Struts2所必需的jar文件
以上jar文件在每一个基本的Struts应用中都不可或缺
以下依次介绍它们的作用:
1 | commoms-fileupload-1.3.3.jar | 文件上传组件 |
2 | commons-lang3-3.6.jar | 为java.lang 提供扩展 |
3 | freemarker-2.3.26-incubating.jar | 模板引擎,一个基于模板生成文本输出的基本工具 |
4 | javassist-3.2..0-GA.jar | 用于操作字节码文件 |
5 | log4j-api 以及log4j-core | 日志输出组件 |
6 | ognl-3.1.15.jar | 支持ognl表达式(一种功能强大的表达式语言) |
7 | struts2-core-2.5.18.jar | struts2核心包 |
4.在src文件夹下创建日志记录log4j2.xml
如果你想要了解程序运行的幕后情况,那么日志文件必不可少.这里使用log4j2.
以下是log4j2.xml文件的所有内容
<Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </Console> </Appenders> <Loggers> <Logger name="com.opensymphony.xwork2" level="debug"/> <Logger name="org.apache.struts2" level="debug"/> <Root level="warn"> <AppenderRef ref="STDOUT"/> </Root> </Loggers> </Configuration> |
5.在WEB-INF下的web.xml添加过滤器
内容如下
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>basic_struts</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> |
这里将过滤器交给struts2,另外/*表示过滤此WEB应用下的所有URL请求
6.在src文件夹下创建struts.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <!-- <constant>节点用于设置一些struts2的常量,这些常量用于控制struts2的某些特性 就相当于告诉 struts,当它运行时,给你准备哪些功能 以下配置的意思是:打印更详细的错误信息,一般在开发模式中使用 --> <constant name="struts.devMode" value="true" /> <!-- <package>元素可以把逻辑上相关的一组Action、Result、Intercepter等元素封装起来,形成一个独立的模块. package可以继承其他的package,也可以作为父包被其他的package继承, 比如我们的“<package name="basicstruts2" extends="struts-default">”中,basicstruts2这个包就继承了struts-default这个包。 <package>元素有如下属性: name:包的名称。必须配置 extends:要继承的包,后面配置的是被继承的包的名称。可选 namespace:包的命名空间。可选 abstract:定义包为抽象的,也就是不能包含Action的定义。可选 --> <package name="basicstruts2" extends="struts-default"> <!-- action: name:对应页面中请求连接的后面半部分 class:对应要执行的类的完整路径 --> <action name="index"> <!-- 结果,跳转的页面.默认为dispatcher类型 --> <result>/index.jsp</result> </action> </package> </struts> |
7.运行项目
如果你的项目结构和上图大致类似,那么这就意味着你此时可以启动Tomcat服务器以运行项目.
服务器启动成功之后,在浏览器地址栏中输入http://localhost:8080/basic_struts/index.action 并回车.如果你看到以下页面,那么大概率你的第一个struts2应用已经运行成功了.