首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Struts记要

2012-09-01 
Struts记录前段控制器ActionServlet在Web.xml中加以定义 !-- Standard Action Servlet Configuration --

Struts记录
前段控制器ActionServlet

在Web.xml中加以定义

 <!-- Standard Action Servlet Configuration -->         <servlet>         <servlet-name>action</servlet-name>         <servlet-class> org.apache.struts.action.ActionServlet        </servlet-class>         <init-param>             <param-name>config</param-name>             <param-value>                /WEB-INF/struts-config.xml            </param-value>         </init-param>         <load-on-startup>1</load-on-startup>     </servlet>     <!-- Standard Action Servlet Mapping -->     <servlet-mapping>         <servlet-name>action</servlet-name>         <url-pattern>*.do</url-pattern>     </servlet-mapping>



控制器
控制物件的實作是透過繼承org.apache.struts.action.Action類別,並重新定義其execute()方法來完成,例如在以下的實作中,將取得使用者的"user"請求參數值,並設定給一個Map型態的Model物件

package onlyfun.caterpillar;import java.util.*;import javax.servlet.http.*;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;public class HelloAction extends Action {    public ActionForward execute(                    ActionMapping mapping,                     ActionForm form,                    HttpServletRequest request,                    HttpServletResponse response)                    throws Exception {        String username = request.getParameter("user");        Map model = new HashMap();                if(username != null) {            model.put("username", username);        }        else {            model.put("username", "nobody");        }         request.setAttribute("userInfo", model);        return mapping.findForward("helloUser");    }}


从controller到view的映射 struts-config.xml

    <action-mappings>        <action          path="/hello"           type="onlyfun.caterpillar.HelloAction">                      <forward                name="helloUser"                 path="/WEB-INF/jsp/hello.jsp"/>         </action>     </action-mappings> 



View显示 hello.jsp

<%@page contentType="text/html"%><%@page pageEncoding="UTF-8"%><html>    <head>        <meta http-equiv="Content-Type"               content="text/html; charset=UTF-8">        <title>Struts Demo</title>    </head>    <body>       <H1>Hello, ${userInfo["username"]} !</H1>    </body></html> 

热点排行