Struts2 HelloWorld (1)

1.Struts2的工作原理图


 

2.Struts2简单例子

struts2中压缩中文件中有简单的示例程序struts2-blank.war

1.将示例中的struts.xml文件拷贝到src目录下

2.将示例lib目录下的所有jar包拷贝到项目中

3.拷贝示例中web.xml文件替换项目中web.xml文件

4.修改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"><!--dtd文件规范了xml文件中能写什么-->
<struts>
    <!-- namespace与我们的访问路径对应,在这里namespace与“http://localhost:8080/struts2_0100/test/hello”中的“/test”对应 -->
    <package name="default" namespace="/test" extends="struts-default">

         <!--在struts1里面,每次访问的是同一个Action对象,会出现线程同步的问题。
            在struts2里面,每次访问的时候,都会重新new一个新的Action,因此就不出有线程不同的问题。
          -->
        <action name="hello"><!--当我们没有配置class的时候,它默认执行struts自己的一个类ActionSupport,查看ActionSupport源码可知:ActionSupport的execute方法返回的是"success"-->
            <result><!--result的name属性的默认值是"success"。-->
                /hello.jsp
            </result>
        </action>
    </package>
</struts>

说明: 1.package:

在java中的作用是给我们的类打个包,避免类重名的情况。在struts2里面,package的作用的一样,比如说我们有2个action,一个叫index,另外一个也叫index,那个这两个action就可以放到不同的package当中

2.namespace:

namespace决定了action的访问路径,默认为"",可以接受所有路径的action

namespace可以写为/,或者/xxx,或者/xxx/yyy,对应的action访问路径为/index.action,/xxx/index.action,或者xxx/yyy/index.action

3.action:

具体视图(jsp页面)的返回可以由用户定义的Action来决定,具体的手段是根据返回的字符串找到对应的配置项,来决定视图的内容。

具体Action的实现有3中方法: 可以是一个普通的java类,里面有public String execute方法即可或者实现Action接口,

不过最常用的是从ActionSupport继承,好处在于可以直接使用Struts封装好的方法。

在struts2里面它用到另外一个框架xwork,ActionSupport是xwork中的类,因此如果想查看ActionSupport的源码需要下载xwork。

 

5.编写hello.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>Insert title here</title>
</head>
<body>
   <h1>Hello Struts2</h1>
</body>
</html>

 

6.启动服务,使用

http://localhost:8080/struts2_0100/test/hello 或 http://localhost:8080/struts2_0100/test/hello.action 访问,其中hello.action中的action可以省略

 

 

小技巧1:我们每次修改struts.xml文件后都需要重启服务器,这样很麻烦,怎么办呢?

 <constant name="struts.devMode" value="true" />

在struts.xml里面有个配置叫做配置它的常量,配置struts的devMode(开发模式)为true。这改完之后,每次修改了struts.xml文件,就不必重启服务器了

 

小技巧2:查看struts2-core.jar的源码

properties ->  java source attachment -> external Folder 中输入:G:\struts\struts-2.3.8\src\core\src\main\java (struts-core的源码位置)

 

 

猜你喜欢

转载自weigang-gao.iteye.com/blog/2153845
今日推荐