深入了解struts2

来源:互联网 发布:网络微电影排行榜 编辑:程序博客网 时间:2024/05/02 02:51

                                                                                                                                  struts2在网站中的配置

如果你是使用Myeclipse6.5你需要导入相应的struts2的架包,及修改web.xml的相应的文件。因为myeclipse的struts版本默认支持1.3,不支持2.0.

如果你使用的是myeclipse10.0就不要相应的修改,直接新建web项目,添加struts支持(file-->myeclipse--->add  struts)


下面就让我们来详细看看配置过程吧!

      我们需要显示的效果

先做一个最简单的struts2的例子:在浏览器中请求一个action,然后返回一个字符串到jsp页面上显示出来。
 
第一步:把struts2最低配置的jar包加入的项目中。
         commons-logging-1.0.4.jar
    freemarker-2.3.8.jar
    ognl-2.6.11.jar
    struts2-core-2.0.11.jar
    xwork-2.0.4.jar
 
第二步:在web.xml中加入拦截器配置。
         <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>
 
第三步:把空的struts.xml配置文件放到项目src下面。
         <struts>
   
</struts>
 
第四部:编写自定义的action类。
package test;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
    private String str;
    public String hello() {
       this.str = "hello!!!";
       return "success";
    }
    public String getStr() {
       return str;
    }
    public void setStr(String str) {
       this.str = str;
    }
}
 
第五步:编写struts.xml配置文件。
<struts>
    <package name="test" namespace="/np" extends="struts-default">
       <action name="hello" class="test.HelloAction" method="hello">
           <result name="success">/hello.jsp</result>
       </action>
    </package>
</struts>
 
第六步:编写hello.jsp文件。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>Test</title>
</head>
<body>
    <h1><s:property value="str"/></h1>
</body>
</html>
 
第七步:启动tomcat,在浏览器中访问:
         http://localhost:8080/hello/np/hello.action
         hello 是项目名字
         np 命名空间,对应namespace里面的字符串。
         hello.action 其中hello对应action里面的字符串,“.action”表示请求的是一个action。
 

这里是运行调用说明:
1)客户端在浏览器中输入一个url地址。
2)这个url请求通过http协议发送给tomcat。
3)tomcat根据url找到对应项目里面的web.xml文件。
4)在web.xml里面会发现有struts2的配置。
5)然后会找到struts2对应的struts.xml配置文件。
6)根据url解析struts.xml配置文件就会找到对应的class。
7)调用完class返回一个字String,根据struts.xml返回到对应的jsp。
 

原创粉丝点击