您的位置:首页 > 移动开发

struts2官方 中文教程 系列一:创建一个struts2 web Application

2017-05-24 14:00 579 查看
先贴了本帖地址,以免被爬 http://www.cnblogs.com/linghaoxinpian/p/6898779.html

本教程将会通过安装struts2框架来创建一个简单的应用程序。
虽然Struts 2框架简单易用,但在开始之前,必须有一定的J2EE技术的储备,包括:

Java

Filters, JSP, and Tag Libraries

JavaBeans

HTML and HTTP

Web Containers (such as Tomcat)

XML

Java Requirements

Struts 2 需要Servlet API 2.4 或是更高的版本, JSP 2.0 或是更高的版本, Java 7 或是更高的版本。

我们的第一个struts2项目

你可以在我的百度网盘上下载样例项目 https://pan.baidu.com/s/1pL7DgwF

Step 1 - 创建一个Java Web Application

这里我用的是Myeclipse,而不是Maven。取名为struts-basic



Step 2 -添加 index.jsp

在WebRoot/index.jsp下

1 <!DOCTYPE html>
2 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
3 <html>
4   <head>
5     <meta charset="UTF-8">
6     <title>Basic Struts 2 Application - Welcome</title>
7   </head>
8   <body>
9     <h1>Welcome To Struts 2!</h1>
10   </body>
11 </html>


接着运行,应该是这个样子:


到这了应该没什么难度吧

Step 3 -添加 Struts 2 的jar文件到项目中

在struts2的官网里下载jar包,







Step 5 - 添加 struts2 的过滤器

为了确保struts2能在你的web应用中运行,需要在web.xml中添加过滤器设置来启用struts2,如下:

  web.xml Servlet Filter

<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>


注意上面的 <url-pattern>/*</url-pattern> 意味着struts2的过滤器将会被应用到这个web 应用的所有URL上。

新版的myeclipse默认是没有web.xml的,自己手动新建一个就行了,修改后的web.xml应该是这个样子:



Step 6 - 创建 struts.xml

struts2 可以使用其它的XML配置文件或者是annotation(注解)来指定URL(/index.action)与处理类(Index类)、视图文件(index.jsp)之间 关联,对于我们这个基础项目,我将只使用最简单的配置方法,注意struts.xml文件必须放在src的根目录下(struts_basic/src/struts.xml),因为发布后src下的文件会被IDE转移到项目的class path的根目录下,这是struts2的规范。

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 name="struts.devMode" value="true" />

<package name="struts_basic" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
</package>

</struts>


这个最简便的配置文件告诉struts2框架,如果访问的URL是http://localhost:8081/struts_basic/index.action 或是http://localhost:8081/struts_basic/index 则转发到index.jsp视图

Step 7 - 运行程序



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: