Struts2基础应用二

第一个Struts2应用:
1、新建一个Web项目,导入一些所需的jar包;

2、 进行Struts2的配置,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>
<package name="huhui" namespace="/com/huhui" extends="struts-default">
         <action name="helloworld" class="com.huhui.action.HelloWorldAction" method="execute">
<result name="success">/WEB-INF/page/hello.jsp</result>
                  </action>
</package>
</struts>

3、 配置web.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></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.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>
  </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping></web-app>

4、 编写Action,HellowWorldAction.java和hello.jsp代码:
public class HelloWorldAction {
private String message;
//省略get/set方法
public String execute() throws Exception{//方法
message="我的第一个struts2应用";
                  ActionContext.getContext().put("message", message);
return "success";
}

//public String message(){
// return "message";
//}
}



<body>
    ${message }
  </body>


5、测试,第一个Struts2应用就完了。所需的jar包在附件中。最后说明一下:
测试时访问的路径跟你所设置的命名空间(namespace已加粗)和action中的name(已加粗)属性值有关,最后的.action后缀可加可不加。访问路径是:http://localhost:8080/项目名/命名空间属性值(我这里是/com/huhui)/action中的name值(我这里是helloworld).action

猜你喜欢

转载自javahuhui.iteye.com/blog/1459218