您的位置:首页 > 编程语言 > Java开发

第一个struts2实例——HelloWorld

2013-02-01 14:23 375 查看
内容提要:本文以一个“Hello World”的简单例子,开始struts2之旅。

开发环境:eclipse3.5+jdk6.0+tomcat7.0+struts2

项目目录结构:





详细步骤:

1、打开 Eclipse,新建 Dynamic Web Project,打上项目名struts2,配置Target runtime选择tomcat ,然后直接点 Finish。



2、下载struts2包,我的版本是struts-2.3.8-all,解压,打开lib文件夹,里面都是jar文件,全部选中,复制。

回到 Eclipse,项目下的WebContent-->WEB-INF-->lib目录,粘贴。





3、在 WEB-INF 目录下,新建一个xml文件,文件名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>


3、在Java Resources -->src目录下新建一个Package,包名为hello,然后在包里新建一个class,文件名为tohello.java,代码如下:

package hello;

import com.opensymphony.xwork2.Action;

public class tohello
{
private String message;
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
public String execute()
{
message="go to hello.jsp ";
return Action.SUCCESS;
}
}


4、在Java Resources -->src目录下新建一个xml文件,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" extends="struts-default">
<action name="GO" class="hello.tohello">
<result> /Helloworld.jsp </result>
</action>
</package>

</struts>


5、在WebContent目录中新建jsp文件,Helloworld.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${message}<br/>
Hello world !
</body>
</html>


6、启动Tomcat Server,打开浏览器,输入http://localhost:8080/struts2/GO.action 或者 http://localhost:8080/struts2/GO,回车,则跳转到 Helloworld.jsp。

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