SSHフレームワークのコントロール層構築
1、コントロール層にPOと同等のVOオブジェクトを作成する
package com.caicai.elec.contorl.vo;
/*
* VOは値オブジェクトであり、ページのプロパティ値に対応する
*
* VOオブジェクトとPOの共通点と相違点
*
* 共通点:どちらもJavaBeanオブジェクトである
* 相違点:POオブジェクトのプロパティ関係はデータベースフィールドに関連しており、データベースフィールドが変更されるとPOの設定も変更が必要になる。
* VOオブジェクトのプロパティ関係はページに対応しており、自由に変更・追加・削除可能で、フォームプロパティに対応する
*
*
* POオブジェクトはバックエンドロジックを処理する
*
* VOはフロントエンド表示を処理する
*
* */
public class ElecTextVo implements java.io.Serializable {
//データベースフィールドを定義
private String textID;
private String textName;
private String textDate;
private String textRemark;
//get/setメソッドを設定
public String getTextID() {
return textID;
}
public void setTextID(String textID) {
this.textID = textID;
}
public String getTextName() {
return textName;
}
public void setTextName(String textName) {
this.textName = textName;
}
public String getTextDate() {
return textDate;
}
public void setTextDate(String textDate) {
this.textDate = textDate;
}
public String getTextRemark() {
return textRemark;
}
public void setTextRemark(String textRemark) {
this.textRemark = textRemark;
}
}
2、actionクラスを作成する
リクエストを使用してページパラメータを取得するテストを行う場合、汎用クラスを記述できます
BaseAction
package com.caicai.elec.contorl.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware {
protected HttpServletRequest request = null;
protected HttpServletResponse response = null;
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request=request;
}
@Override
public void setServletResponse(HttpServletResponse response) {
// TODO Auto-generated method stub
this.response=response;
}
}
文字列から日付型に変換するメソッドクラスを記述する
<strong>StringConverDate</strong>
package com.caicai.elec.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringHelper {
/**
* 文字列を日付型に変換する
*
*/
public static Date StringConverDate( String Date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date=simpleDateFormat.parse(Date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
}
BaseActionを継承する
package com.caicai.elec.contorl.action;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.caicai.elec.contorl.vo.ElecTextVo;
import com.caicai.elec.doamin.ElecText;
import com.caicai.elec.service.IElecTextService;
import com.caicai.elec.util.StringHelper;
import com.opensymphony.xwork2.ModelDriven;
//ActionはActionSupportを継承する必要がある
//モデルドライバクラスを実装する
public class ElecTextAction extends BaseAction implements ModelDriven<ElecTextVo> {
/**
*
*/
private static final long serialVersionUID = 1707074060653507324L;
private ElecTextVo elecTextVo = new ElecTextVo();
@Override
public ElecTextVo getModel() {
System.out.println("request comes in getModel");
return elecTextVo;
}
public String save (){
// System.out.println("request comes in save");
// System.out.println(elecTextVo.getTextName());
//タグの内容を取得し、request方式を使用する
// System.out.print(request.getParameter("textRemark"));
//VoオブジェクトをPOオブジェクトに変換する。入力値を永続層に渡す必要がある。
//POオブジェクトをインスタンス化する
ElecText elecText = new ElecText();
elecText.setTextName(elecTextVo.getTextName());//テスト名
elecText.setTextDate(StringHelper.StringConverDate(elecTextVo.getTextDate()));//テスト日付
elecText.setTextRemark(elecTextVo.getTextRemark());//備考
//Springアノテーションを使用し、serviceを呼び出す
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
IElecTextService elecTextService = (IElecTextService)applicationContext.getBean(IElecTextService.IELecTextservice);
elecTextService.saveElecText(elecText);
return "save";
}
}
3、struts.xmlを作成し、設定する
<?xml version="1.0" encoding="UTF-8"?>
<struts>
<!-- actionのアクセスパスを.do形式に設定する -->
<constant name="struts.action.extension" value="do"></constant>
<!-- strutsの開発モードを設定する -->
<constant name="struts.devMode" value="true"></constant>
<!-- strutsのシンプルモードを設定する -->
<constant name="struts.ui.theme" value="simple"></constant>
<package name="system" namespace="/system" extends="struts-default">
<action name="elecTextAction_*" class="com.caicai.elec.contorl.action.ElecTextAction" method="{1}">
<result name="save">
/system/textAdd.jsp
</result>
</action>
</package>
</struts>
4、web.xmlにstrutsフィルターを設定する
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>dainli20210421</display-name>
<welcome-file-list>
<welcome-file>/system/textAdd.jsp</welcome-file>
</welcome-file-list>
<!-- struts2フィルターを設定する -->
<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>
5、jspページを設定する
<%@ page language="java" pageEncoding="UTF-8"%>
<script type="text/javascript" language="JavaScript" src="${pageContext.request.contextPath }/script/calendar.js" charset="gb2312"></script>
<html>
<head>
<title>テスト用jsp</title>
<link href="${pageContext.request.contextPath }/css/Style.css" type="text/css" rel="stylesheet">
<script language="javascript">
function checkchar(){
document.Form1.action="system/elecTextAction_save.do";
document.Form1.submit();
//alert(" 保存完了!");
}
function addEnter(element){
document.getElementById(element).value = document.getElementById(element).value+"<br>";
}
</script>
</head>
<body>
<form name="Form1" id="Form1" method=post>
| <font face="宋体" size="2">**テスト用jsp**</font> |
|:-:|
| | |
| テスト名: | <textarea id="textName" name="textName" onkeydown="if(event.keyCode==13)addEnter('textName');" style="width: 500px; height: 160px; padding: 1;FONT-FAMILY: 宋体; FONT-SIZE: 9pt"></textarea> |
| テスト日付: | <input maxlength="50" name="textDate" onclick="JavaScript:calendar(document.Form1.textDate)" size="20" type="text"></input> |
| テスト備考: | <textarea id="textRemark" name="textRemark" onkeydown="if(event.keyCode==13)addEnter('textRemark');" style="width: 500px; height: 160px; padding: 1;FONT-FAMILY: 宋体; FONT-SIZE: 9pt"></textarea> |
| <input id="BT_Submit" name="BT_Submit" onclick="checkchar()" style="font-size:12px; color:black; height=20;width=50" type="button" value="保存"></input> |
</form>
</body>
</html>
プロジェクト開発において、できる限りカプセル化を行う
この2つのメソッドをカプセル化する
//設定ファイルをロードする<br></br> ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");<br></br>//JavaBeanを取得する
IElecTextDao iElecTextDao = (IElecTextDao)applicationContext.getBean(IElecTextDao.serivicename);
package com.caicai.elec.container;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ServiceProviderCord {
protected static ApplicationContext applicationContext;
public static void loadXML(String filename) {
//beans.xmlファイルをロードする(filenemaはSpring設定ファイル(beans.xml))
applicationContext = new ClassPathXmlApplicationContext(filename);
}
}
package com.caicai.elec.container;
import org.apache.commons.lang.StringUtils;
public class ServiceProvider{
//設定ファイルをロードする
public static ServiceProviderCord serviceProviderCord;
//メソッドを実行する前に、プログラムはデフォルトでstaticメソッドを最初に呼び出す
static{
System.out.print("最初にstaticを実行");
serviceProviderCord = new ServiceProviderCord();
serviceProviderCord.loadXML("beans.xml");
}
public static Object getSetvice(String ServiceName) {
System.out.print("2回目にstaticを実行");
//サービス名が空かどうかを確認する
if(StringUtils.isBlank(ServiceName)){
throw new RuntimeException("現在のサービス名が存在しません");
}
Object object = null;
//現在のノード名が含まれているかどうかを確認する
if(serviceProviderCord.applicationContext.containsBean(ServiceName)){
object = serviceProviderCord.applicationContext.getBean(ServiceName);
}
if(object == null){
throw new RuntimeException("現在のサービス名 ["+ServiceName+" ]の下のサービス名が存在しません");
}
return object;
}
}