教育サーバーのページ
オンラインテキスト目次
システムプログラミング演習
新たなWebアプリケーションを以下の操作にしたがって作成する。
以下のプロジェクトウインドウのファイル構成では、上記の操作に より作成されたファイルが示されている。
「構成ファイル」ノードには、Strutsで使う構成ファイル"struts-config.xml"が 含まれている。さらに、Struts controller servletは、以下の"web.xml"の ディプロイ記述子に基づいてマップされる。
<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> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>2</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<html:form action="login"> <html:submit value="Login" /> </html:form>
<html:form action="login"> <table border="1"> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <html:submit value="Login" /> </html:form>
<bean:message key="login.name" />
さらに、<td>タグ間に以下を挿入する。
<html:text property="name" />
最終的には、"loginForm.jsp"のbody部は、以下のようになる。
login.name=Name
"actionform bean"ファイルをエディタで開き、フィールド"name"が"String型で、 フィールド"number"がint型で宣言され、それぞれのgettersとsettersが定義されて いることを確認せよ。
<form-beans> <form-bean name="NewStrutsActionForm" type="com.myapp.struts.NewStrutsActionForm" /> </form-beans>
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (getName() == null || getName().length() < 1) { errors.add("name", new ActionMessage("error.name.required")); // TODO: add 'error.name.required' key to your resources } return errors; }
error.name.required=Enter a name!
エラーメッセージの整形をおこなうために、このファイルの先頭の 4つのキーを以下のように修正する。
errors.header= errors.prefix=<span style="color: red" > errors.suffix=</span> errors.footer=
<action-mappings> <action input="/loginForm.jsp" name="NewStrutsActionForm" path="/login" scope="session" type="com.myapp.struts.NewStrutsAction" /> <action path="/Welcome" forward="/welcomeStruts.jsp" /> </action-mappings>
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(SUCCESS);}
"NewStrutsAction"の先頭において、SUCCESSの定義が以下のように なされていることを確認せよ。
private final static String SUCCESS = "success";
"struts-config.xml"ファイルは、以下のようになることを確認せよ。
<action-mappings> <action input="/loginForm.jsp" name="NewStrutsActionForm" path="/login" scope="session" type="com.myapp.struts.NewStrutsAction"> <forward name="success" path="/loginSuccessful.jsp"/> </action> <action path="/Welcome" forward="/welcomeStruts.jsp"/> </action-mappings>
ログイン画面を出すには、以下の方法AかBのどちらかを行えばよい。
アプリケーションを実行すると、Struts controller servlet にマッピングしていた.doマッピングが利用され、リクエスト に対応する。
以上の操作で、最終的に作成されるファイルは、以下のとおりである。
[loginFrom.jsp]
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %> <%@page contentType="text/html" 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>Login Form</title> </head> <body> <h2>Login Form</h2> <html:form action="login"> <table border="1"> <thead> <tr> <th><bean:message key="login.name" /></th> </tr> </thead> <tbody> <tr> <td><html:text property="name" /></td> </tr> </tbody> </table> <html:submit value="Login" /> <html:errors /> </html:form> </body> </html>
[loginSuccessful.jsp]
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %> <%@page contentType="text/html" 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>Login Successful!</title> </head> <body> <h2>Login Successful!</h2> </body> </html>
[welcomeStruts.jsp]
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %> <html:html locale="true"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body style="background-color: white"> <logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application"> <div style="color: red"> ERROR: Application resources not loaded -- check servlet container logs for error messages. </div> </logic:notPresent> <h3><bean:message key="welcome.heading"/></h3> <p><bean:message key="welcome.message"/></p> </body> </html:html>
[struts-config.xml]
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="NewStrutsActionForm" type="com.myapp.struts.NewStrutsActionForm"/> </form-beans> <global-exceptions> </global-exceptions> <global-forwards> <forward name="welcome" path="/Welcome.do"/> </global-forwards> <action-mappings> <action input="/loginForm.jsp" name="NewStrutsActionForm" path="/login" scope="session" type="com.myapp.struts.NewStrutsAction"> <forward name="success" path="/loginSuccessful.jsp"/> </action> <action path="/Welcome" forward="/welcomeStruts.jsp"/> </action-mappings> <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/> <message-resources parameter="com/myapp/struts/ApplicationResource"/> <!-- ========================= Tiles plugin ===============================--> <!-- This plugin initialize Tiles definition factory. This later can takes some parameters explained here after. The plugin first read parameters from web.xml, thenoverload them with parameters defined here. All parameters are optional. The plugin should be declared in each struts-config file. - definitions-config: (optional) Specify configuration file names. There can be several comma separated file names (default: ?? ) - moduleAware: (optional - struts1.1) Specify if the Tiles definition factory is module aware. If true (default), there will be one factory for each Struts module. If false, there will be one common factory for all module. In this later case, it is still needed to declare one plugin per module. The factory will be initialized with parameters found in the first initialized plugin (generally the one associated with the default module). true : One factory per module. (default) false : one single shared factory for all modules - definitions-parser-validate: (optional) Specify if xml parser should validate the Tiles configuration file. true : validate. DTD should be specified in file header (default) false : no validation Paths found in Tiles definitions are relative to the main context. --> <plug-in className="org.apache.struts.tiles.TilesPlugin" > <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> <set-property property="moduleAware" value="true" /> </plug-in> <!-- ========================= Validator plugin ================================= --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in> </struts-config>
[web.xml]
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <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> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>2</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
[ApplicationResource.properties]
errors.header= errors.prefix=<span style="color: red" > errors.suffix=</span> errors.footer= errors.invalid={0} is invalid. errors.maxlength={0} can not be greater than {1} characters. errors.minlength={0} can not be less than {1} characters. errors.range={0} is not in the range {1} through {2}. errors.required={0} is required. errors.byte={0} must be an byte. errors.date={0} is not a date. errors.double={0} must be an double. errors.float={0} must be an float. errors.integer={0} must be an integer. errors.long={0} must be an long. errors.short={0} must be an short. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address. errors.cancel=Operation cancelled. errors.detail={0} errors.general=The process did not complete. Details should follow. errors.token=Request could not be completed. Operation is not in sequence. welcome.title=Struts Application welcome.heading=Struts Applications in Netbeans! welcome.message=It's easy to create Struts applications with NetBeans. login.name=Name errors.name.required=Enter a name!
[NewStrutsAction.java]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.myapp.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForward; /** * * @author nagai */ public class NewStrutsAction extends org.apache.struts.action.Action { /* forward name="success" path="" */ private final static String SUCCESS = "success"; /** * This is the action called from the Struts framework. * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * @throws java.lang.Exception * @return */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(SUCCESS); } }
[NewStrutsActionForm.java]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.myapp.struts; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; /** * * @author nagai */ public class NewStrutsActionForm extends org.apache.struts.action.ActionForm { private String name; private int number; /** * @return */ public String getName() { return name; } /** * @param string */ public void setName(String string) { name = string; } /** * @return */ public int getNumber() { return number; } /** * @param i */ public void setNumber(int i) { number = i; } /** * */ public NewStrutsActionForm() { super(); // TODO Auto-generated constructor stub } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (getName() == null || getName().length() < 1) { errors.add("name", new ActionMessage("error.name.required")); // TODO: add 'error.name.required' key to your resources } return errors; } }
問題-1
問題-2
問題-3
問題-4