解答例 - 実習課題2 - 1.ActionServletとAction
(実習課題2)
以下のWebアプリケーションを、Strutsを用いて作成しなさい。
- パラメータ「op」の値が「time」である場合には、時刻を表示する事。
- パラメータ「op」の値が「ip」である場合には、接続元のIPアドレスを表示する事。
- いずれも表示はフォワード先のJSPページで行う事。
解答例
▼ディレクトリ構成は以下の通り
.
├─com
│ └─techscore
│ └─struts
│ └─chapter1
│ └─exercise2 time.jsp,ip.jsp
└─WEB-INF web.xml(実習課題1と同じ),struts-config.xml
├─classes
│ └─com
│ └─techscore
│ └─struts
│ └─chapter1
│ └─exercise2 ParameterCheckAction.class
└─lib strutsライブラリjarファイル
※strutsライブラリjarファイル
struts.jar,commons-beanutils.jar,commons-collections.jar,commons-digester.jar,commons-logging.jar
/**
* ParameterCheckAction.java
* TECHSCORE Java JakartaStruts 1章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*
*/
package com.techscore.struts.chapter1.exercise2;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ParameterCheckAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception{
//パラメータopの値によって分岐
String parameter = request.getParameter("op");
if (parameter.equals("time")) {
return mapping.findForward("time");
} else if (parameter.equals("ip")) {
return mapping.findForward("ip");
} else {
return null;
}
}
}
<!-- time.jsp -->
<!-- TECHSCORE Java JakartaStruts 1章 実習課題2 -->
<!-- Copyright (c) 2004 Four-Dimensional Data, Inc. -->
<%@ page contentType="text/html; charset=Windows-31J"
session="false"
pageEncoding="Windows-31J" %>
<html>
<head>
<title>TECHSCORE Java JakartaStruts 1章 実習課題2</title>
</head>
<body>
<%=new java.util.Date()%>
</body></html>
<!-- ip.jsp -->
<!-- TECHSCORE Java JakartaStruts 1章 実習課題2 -->
<!-- Copyright (c) 2004 Four-Dimensional Data, Inc. -->
<%@ page contentType="text/html; charset=Windows-31J"
session="false"
pageEncoding="Windows-31J" %>
<html>
<head><title>TECHSCORE Java JakartaStruts 1章 実習課題2</title></head>
<body>
<%= java.net.InetAddress.getLocalHost().toString()%>
</body></html>
▼struts-config.xml
<?xml version="1.0" encoding="Windows-31J" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<action-mappings>
<action path="/com/techscore/struts/chapter1/exercise2/ParameterCheck"
type="com.techscore.struts.chapter1.exercise2.ParameterCheckAction">
<forward name="time"
path="/com/techscore/struts/chapter1/exercise2/time.jsp" />
<forward name="ip"
path="/com/techscore/struts/chapter1/exercise2/ip.jsp" />
</action>
</action-mappings>
</struts-config>
▼起動URLは以下の通り
WEB_ROOT/com/techscore/struts/chapter1/exercise2/ParameterCheck.do?op=time
WEB_ROOT/com/techscore/struts/chapter1/exercise2/ParameterCheck.do?op=ip

