Struts2第一个例子Hello World!

1、首先用eclipse新建一个动态web项目Struts2Demo1:

(把Default output floder由build\classes改成WebContent\WEB-INF\classes)

2、从struts2官网下载struts,解压后将如下包copy到WebContent/WEB-INF/lib下,然后bulid path

commons-fileupload文件上传包

commons-ior文件上传依赖包

commons-lang为java.lang包提供扩展

commons-logging 通用日志记录包

commons-logging-api Apache Commons包中的一个,包含了一些数据类型工具类,是java.lang.*的扩展

freemarker FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具

javassist javassist是一款字节码编辑工具,可以直接编辑和生成Java生成的字节码,以达到对.class文件进行动态修改的效果

ognl 支持ognl表达式

struts2-core struts2的核心包

xwork-core xwork核心包

将struts2安装包中的struts.xml copy到src目录下(编译时会自动将struts.xml导入到/WEB_INF/classes目录),修改struts.xml为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">
     
      <action name="hello" 
            class="cn.orlion.strctsdemo.HelloWorldAction" 
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
      </action>
   </package>
</struts>

 

3、将web.xml改为如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</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.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

4、在src目录下新建包cn.orlion.strctsdemo,新建类HelloWorldAction(继承ActionSupport)。创建一个方法execute,返回字符串"success"

package cn.orlion.strctsdemo;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport{

    public String execute() throws Exception{
        
        return "success";
    }
}

然后在WebContent目录下新建一个HelloWorld.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Hello World!</title>
</head>
<body>
    Hello World!
</body>
</html>

5、运行,访问http://localhost:8080/Struts2Demo1/hello.action。可看到Hello World!

posted @ 2015-12-01 17:12  orlion  阅读(326)  评论(0编辑  收藏  举报