Struts2使用

来源:互联网 发布:牛仔衬衫 男 知乎 编辑:程序博客网 时间:2024/04/29 18:33

-----------First Struts2.0 Project------------
1.建立一个web Project;

2.导入struts2.0的核心包,注意全部导入全部的lib会引起错误;
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
freemarker-2.3.12.jar
ognl-2.6.11.jar
struts2-core-2.1.2.jar
xwork-2.1.1.jar

3.工程配置
3.1 struts.xml
把配置文件放在src的根目录下,在struts2.0中默认的配置文件不再是struts-default.xml,而是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>
 <include file="struts-default.xml"></include>
 <package name="com" extends="struts-default">
   <action name="Hello" class="com.Hello">
     <result>/hello.jsp</result>
   </action>
 </package>
</struts>

--其中<package name="com"中的name可以调整;
<action name="Hello" class="com.Hello">  //代表Action的名称和实际存放位置
     <result>/hello.jsp</result>         //表示导向页面

3.2 web.xml中必须说明filter和filter-mapping的内容
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">
  <filter>
   <filter-name>struts</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>struts</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.3 Action在Struts2.0种已经把ActionForm和Action合二为一;
package com;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class Hello extends ActionSupport {
 private String message;

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }
 
 public String execute(){
  message = message + ",Hello";
  return SUCCESS;
 }

}

3.4 index.jsp 起始页面
<%@ taglib prefix="s" uri="/struts-tags"%>
...
<s:form action="Hello">
     Message:<s:textfield name="message"></s:textfield>
     <s:submit></s:submit>
    </s:form>

3.5 hello.jsp 响应页面
<%@ taglib prefix="s" uri="/struts-tags"%>
...
<h3><s:property value="message"/> </h3><br>
   <a href="index.jsp">Back</a>

原创粉丝点击