第一個struts2實例——HelloWorld


內容提要:本文以一個“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。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM