• ベストアンサー

struts2とspringとの連携のメリットが分らない

ので教えてください。 アプリケーションコンテキストを得るために struts2とspringが連携していない場合は ApplicationContext appContext=new ClassPathXmlApplicationContext("ApplicationContext.xml"); の1行でできますが、 struts2とspringが連携している場合は ActionContext context=ActionContext.getContext(); Map<?, ?> map=context.getContextMap(); ServletContext application=(ServletContext) map.get(StrutsStatics.SERVLET_CONTEXT); WebApplicationContext appContext=(WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); の長文の4行になります。 勿論この場合は最初の方法も使えます。 struts2とspringを連携しないほうがspringを簡単に使えるように思います。 設定ファイルの記述やプログラムコードが長くなるのにもかかわらず、 敢てstruts2とspringを連携するメリットを教えてください。

質問者が選んだベストアンサー

  • ベストアンサー
  • kakusuke
  • ベストアンサー率36% (95/259)
回答No.2

struts2(画面)->spring2.5(Business Logic)->Hibernate(Data Access Object) なだけですよね? それぞれが依存性がないPOJOで作成することができるため、 単体テストにおいて、テスト対象モジュール以外が未作成でも テスト可能というのが最大のメリットです。 単純に考えると、 Business Logicにて複数のエンティティを同時に更新することがなければあまり重要となることはないですが、 バージョンアップやポーティング対応で struts2を他の画面系Frameworkに、 Hibernateを他のData Access Object Frameworkに差し替えた場合に、 他の部品をを修正する必要がないため、 工数が削減できると考えられます。

reiman
質問者

お礼

ありがとうございます。 テストが簡単にできる フレームワークやORマッピングの変更が用意になる ということですね フレームワークの変更は現実的でないと思いますが 開発規模が大きいとそれなりに大きくなりそうですね。

全文を見る
すると、全ての回答が全文表示されます。

その他の回答 (1)

  • lv4u
  • ベストアンサー率27% (1862/6715)
回答No.1

>>敢てstruts2とspringを連携するメリットを教えてください。 システム開発は、開発をしていく途上で、またリリース後に仕様が変わることが多いと思います。このとき、「ちょっとした軽微な修正が1カ所発生した!」ということがよくあります。その影響が予想外に、玉突き的に多くのモジュールに影響することもよくあると思います。 そのとき、JavaやJspのソースを何本もメンテする必要が発生するよりも、最初は作るのが大変でも「1カ所の修正はしょうがないが、連携しているので他のソースを修正しないでもいい」となれば嬉しいのではないでしょうか?つまり開発中やその後のメンテが楽になる(かもしれない)というメリットを狙っているのではないでしょうか。 ただ、個人的な印象では、例にあげられた1行を長ったらしい5行に置き換える価値はあるのか?プログラマ的に損得勘定としてどうなの?(センス悪ーい!)とか、「連携しているから、1カ所で済む修正が、さまざまな多数のモジュールの修正を逆に呼び込んで大変になるのでは?」なーんてJavaの初心者は思ってしまいますけどね。

reiman
質問者

お礼

ありがとうございます。 最初の環境設定、設定ファイル作成、初期のコードの記述 において多少導入が大変でも後は少し楽になり、メンテにも有利ということでしょうか。 大勢で開発しているや規模の大きいものを開発している場合は導入で苦労する人は一人であり苦労するのは開発期間からすればとるの足らないので 全体として導入コストはペイできるということですね。 逆にいえば 少人数、小規模でプログラミングする場合は連携するまでもないと言うことですね。 目的がSpring+Hibernateの機能でデータベースアクセスをDAOにより行うためだけならば連携をするまでもないですね。 有難うございました。

全文を見る
すると、全ての回答が全文表示されます。

関連するQ&A

  • StrutsのValidatorについて

    Struts1.2.7 で開発を始めました。 validator の勉強をしているのですが、リソースファイルの設置場所がわからず困っています。 WEB-INF/struts-config.xml に下記記述をしています。 message-resources parameter="resources.application" この場合は下記のようにリソースファイルを設置すれば良いと思っていますが、 WEB-INF/classes/resources/application.properties うまく動きません。 手元の本には、「クラス/ソースパッケージツリーのresourcesパッケージに作成」とあります。 ValidatorResources not found in application scope under key "org.apache.commons.validator.VALIDATOR_RESOURCES" このようなエラーが別途出力されています。

    • ベストアンサー
    • Java
  • Struts2でのStaticイニシャライザ

    Struts2でのインターセプターにてStaticイニシャライザを実行するとエラーになってしまいます。 ファイルの絶対パスを取得しようとしています。 以下がそのコードなのですがTomcat再起動時にイニシャライザが実行され getRealPath()の部分で例外が発生し、java.lang.ExceptionInInitializerError が発生します。 同じコードをintercept()メソッド内に記述した場合は例外が発生せず絶対パスを取得することが できます。どなたか原因及び対処方法がおわかりになられますでしょうか。 public class CheckValueInterceptor extends AbstractInterceptor { private static final long serialVersionUID = 1L; //ファイルの絶対パスの取得 static { ServletContext context = ServletActionContext.getServletContext(); String path = context.getRealPath("/WEB-INF/Test.txt"); } public String intercept(ActionInvocation invocation) throws Exception { } }

    • ベストアンサー
    • Java
  • struts2でのフィルターを使ったセッション管理

    はじめまして。 struts2,spring frameworkでソフトを作ってますが、セッション管理について質問があります。 1.ログイン画面で、ログイン後にセッションidを登録する。 session.setAttribute (USER_HANDLE, user); 2.他の画面に移動する時に、セッションid(user)が格納されているか確認する。格納されていない場合は、ログイン画面に戻る。 という処理をする場合、actionごとに HttpSession session = request.getSession (true); Object user = session.getAttribute (USER_HANDLE); if (user != null) { //処理1 return true; } else { //処理2 return false; } と記述すると手間がかかるので、下記の様なFilterでまとめて管理できないかと考えているのですが、こういう考え方は一般的なのでしょうか? public class TestAccessFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); HttpSession session = request.getSession (true); Object user = session.getAttribute (USER_HANDLE); if (user == null) { //処理1 return "login-success"; } else { //処理2 return "login"; } } actionごとにセッションidが格納されているか確認する代わりに、Filterでまとめて確認できないかということなのですが.... struts2でこういう書き方をして良いのかわからず困っています。 アドバイスをお願いいたします。

    • ベストアンサー
    • Java
  • Struts、Spring、iBATISについて

    Struts1、Spring3、iBATIS2 であるプロジェクトを 勉強の為に作成しているのですが、どうしても わからないエラーが発生してしまい、質問させて いただきました。 【現象】 eclipseによりtomcatを使用してサーバサービスを起動のとき、 エラーが発生してしまう。 【applicationContext.xml】抜粋 <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:sqlMapConfig.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="jtaTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="testDAO" class="bestone.app.dao.impl.testDAOImpl"> <property name="sqlMapClient" ref="sqlMapClient" /> </bean> 【testDAOImpl.java】 package bestone.app.dao.impl; import java.sql.SQLException; import bestone.app.dao.testDAO; import bestone.app.dao.bean.testBean; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; public class testDAOImpl extends SqlMapClientDaoSupport implements itestDAO { public testBean selectInfo(testBean bean) throws SQLException { // TODO Auto-generated method stub return (testBean) getSqlMapClient().queryForObject("test.SELECT_INFO", bean); } } 【エラー内容】 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse config resource: ServletContext resource [/WEB-INF/conf/sqlMapConfig.xml]; nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource jp/co/best/app/dao/map/test_SqlMap.xml at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222).............................. ======================================= わかる方いらっしゃいましたらご教授ください。 よろしくお願いいたします。

  • Struts2、Spring、iBATIS splMapClientについて

    Struts2、Spring、iBATIS で勤務管理サイトを 勉強の為に作成しているのですが、どうしても わからないエラーが発生してしまい、質問させて いただきました。 【事象】 ・eclipseよりサーバでの実行を起動させた際ですが、  @ResourceでDAOのBeanを注入時にエラーが発生してしまいます。  ※@Resourceを外せば当事象のエラーは発生しませんでした。 【applicationContext.xml】抜粋 <bean id="splMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" scope="singleton"> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <bean id="loginDao" class="login.LoginDao" scope="singleton"> <property name="splMapClient" ref="splMapClient"></property> </bean> 【sqlMapConfig.xml】 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <settings cacheModelsEnabled="true" statementCachingEnabled="true" enhancementEnabled="true" classInfoCacheEnabled="true" lazyLoadingEnabled="false" /> <sqlMap url="file:c:/eclipse/workspace/tiles/WebContent/WEB-INF/sql/login.xml" /> </sqlMapConfig> 【Login.java】 package login; import java.util.Map; import javax.annotation.Resource; import jp.co.hershe.struts2.util.Struts2Action; import com.opensymphony.xwork2.ActionSupport; @Struts2Action("Login") public class Login extends ActionSupport { private static final long serialVersionUID = 1L; @Resource private LoginDao loginDao; @Override public String execute() throws Exception { (もろもろ処理が入ります) } } 【エラーログ】 情報: Loaded JDBC driver: oracle.jdbc.driver.OracleDriver 2009/06/26 1:05:28 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons 情報: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@269997: defining beans [org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,Login,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,login,transactionManager,dataSource,TransactionInterceptor,splMapClient,loginDao]; root of factory hierarchy 2009/06/26 1:05:28 org.springframework.web.context.ContextLoader initWebApplicationContext 致命的: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'splMapClient' of bean class [login.LoginDao]: No property 'splMapClient' found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at …… ================================================== sqlMapClientのあたりで記述がおかしいのかと思いまして 見直しや検索などしてみたのですが、わからず、、 わかる方いらっしゃいましたらご教授ください。 よろしくお願いいたします。

    • ベストアンサー
    • Java
  • Strutsのfilter.jarを使用したときの文字化けについて

    StrutsによるWebアプリケーションスーパーサンプル(ソフトバンククリエィティブ)の本の中で文字化けを解消するためにfilter.jarというものを使用しています。 filter.jarの中EncodingFileter.javaの内容は以下のとおりです。 ここから-----------------------------------------------------/* /* * Created on 2004/06/15 * EncodingFileter.java */ package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * EncodingFileter.java * Copyright 2004 A.Takayasu * */ public class EncodingFileter implements Filter{ public void destroy() { } public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)throws IOException, ServletException { request.setCharacterEncoding("Windows-31J"); chain.doFilter(request,response); } public void init(FilterConfig config) throws ServletException { } } ここまで--------------------------------------------------- あと、web.xmlの中で以下のような記述があります。 ここから-------------------------------------------- <!-- エンコーディングフィルタの設定 --> <filter> <filter-name>Encoding</filter-name> <filter-class>filter.EncodingFileter</filter-class> </filter> <filter-mapping> <filter-name>Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ここまで--------------------------------------------------- Windowsからのリクエストの場合は、Windows-31Jの設定でいいと思うのですが、それでも文字化けが起こります。 試しに、Windows-31Jの部分をShift_JISに変更してコンパイルして jarファイルを作成してjarファイルを差し替えてみたのですが、 文字化けしてしまいます。jarファイルの中身は確かにShift_JISに 変わっているのを確認しています。 なにかほかに設定するところがあるのでしょうか? 原因がわからなくて困っています。 ちなみにTomcatのバージョンは、jakarta-tomcat-4.1.29で strutsは1.1です。 どうかご教授よろしくお願いします。

    • ベストアンサー
    • Java
  • 2点質問があります。

    2点質問があります。 ●1点目 Struts + Springで開発を行っています。 その開発チーム内では、DBから一覧画面用のデータを取得する際に SimpleJdbcTemplateのqueryForList()を用い、 上記メソッドより返されたList<Map<String, Object>>型のデータを そのままAction、JSP等で利用しています。 queryForList()の使い方を調べてみると、 Map<String, Object>型のデータをDTOのようなオブジェクトに入れ替えて 再度リスト化してJSP等で利用している例を見かけます。 (http://www.techscore.com/tech/Others/Spring/5-4.htmlなど) 私の開発チームでは、Map<String, Object>型をDTOに入れ替えると その分余計なクラス(DTO)を作らなければならないため、 Map<String, Object>型のまま使っているのですが、 DTOに入れ替えない場合に保守性、性能面等で問題はあるのでしょうか? ●2点目 1点目の質問でMap<String, Object>型のまま利用することに重大な問題点がない という回答が頂けた場合の話です。 登録内容変更画面にて、 以前登録した内容をDBから取得してテキストボックス内に表示し 画面上で値を変更しDBを更新する処理を行う際に、 入力項目が繰り返し入力フィールドとなっています。 この場合、以前の登録内容がDBよりList<Map<String, Object>>型で返され、 JSPで表示する場合に以下のようにして表示が可能でした。 <nested:iterate property="dataList"> <nested:text property='dataString1'/> <nested:text property='dataString2'/> </nested:iterate> またActionFormは以下のように定義しています。 public class DataForm extends ActionForm { private List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>(); //以下dataListのgetter、setter } しかし、画面にてdataString1、dataString2に入力した内容を DataForm.dataListで受け取ることはできませんでした。 ActionFormにて配列やオブジェクトで各入力項目を一旦受け取り List<Map<String, Object>>型に入れなおすのではなく、 直接List<Map<String, Object>>型フィールドで値を受け取ることは不可能なので しょうか? ※これも余計なクラスやフィールドを作成しないという考えに基づいています。 尚、Struts、Springのバージョンは以下の通りです。  Struts:1.2.9  Spring:2.0.8

  • jspでの表示の仕方

    下記のような、jspへの受け渡しができずにいます。 ご回答お願いします。 Servletは、 String query = "SELECT * FROM test"; ResultSet resultset = statement.executeQuery( query ); request.setAttribute("obj",resultset); ServletContext context = getServletContext(); RequestDispatcher rd = context.getRequestDispatcher("/kekka.jsp"); rd.forward(request,respons); とした時、jsp側で、 <%@ page contentType="text/html;charset=Shift_JIS" %> <%@ page import = "java.sql.*" %> <%! ResultSet rs = (ResultSet)request.getAttribute("obj"); %> <% While(rs.next()){String hinmei = rs.getString("hinmei");} %> <html> <head> <title>JSP</title> </head> <body> <table border="0"> <tr> <td><%=hinmei%></td> </tr> </table> </body> </html> と、したいのですが、白い画面になりjspの表示ができません。 やはり、ResultSetオブジェクトのAttributeはできないのでしょうか? それとも、jspの構文に問題があるのでしょうか? Vector、Stringは、この形のやり方で表示できたのですが・・・。 間違いを指摘してください。 よろしくお願いします。

    • ベストアンサー
    • Java
  • javaサーブレット sessionの使い方

    sessionを使ってデータの受け渡しをしたいのですが、ページ移動が増えると上手く受け渡せ無くて困っています。 jsp→Servlet のみでテストした時は正常に動いたのですが、ページを増やすと値が上手く更新されないのです。 下のプログラムではjspでセッションを開始して、ボタンを押すことでNS1.javaに移動し値を1増やしてNS2.javaに移動します。NS2.javaでも値を1増やしているので結果的に2つ値が増えるはずなのに1つも増えません。 何が悪いのでしょうか。解決策を教えて下さい。 // NStest.jsp <%@ page contentType="text/html;charset=Windows-31J" %> <html> <head> <title>移動</title> </head> <body> <% // isNewメソッドでセッション管理されているか確認します。 if (session.isNew()) { // セッション管理されていない場合、データを登録します。 session.setAttribute("count", 0); // 初回用メッセージ out.println(" Nice to meet you."); } else { // セッション管理されている場合、データを表示します。 out.println("count: " + session.getAttribute("count")); } %> <form method="POST" enctype="multipart/form-data" action="NS1"> <INPUT type="SUBMIT" name="button1" value="移動"> </form> </body> </html> // NS1.java package NStest; import java.io.*; import javax.servlet.*; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class NS1 extends HttpServlet { public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // 出力形式等の設定 ServletContext context = this.getServletContext(); response.setContentType("text/html;charset=Windows-31J"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); String message; if (null == session) { // nullが返ってくる場合はセッションが作成されていない session.setAttribute("count", 0); out.println("セッションが開始されていません。"); } else { // セッションインスタンスからcountの値を取得して表示 // 1加算してふたたび保存 Integer count = (Integer)session.getAttribute("count"); session.setAttribute("count", 1 + count.intValue()); message = "ページカウント: " + count; out.println(message); } // 処理後はNS2.javaにリダイレクト response.sendRedirect("NS2.java"); } } // NS2.java package NStest; import java.io.*; import javax.servlet.*; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class NS2 extends HttpServlet { public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // 出力形式等の設定 ServletContext context = this.getServletContext(); response.setContentType("text/html;charset=Windows-31J"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); String message; if (null == session) { // nullが返ってくる場合はセッションが作成されていない session.setAttribute("count", 0); out.println("セッションが開始されていません。"); } else { // セッションインスタンスからcountの値を取得して表示 // 1加算してふたたび保存 Integer count = (Integer)session.getAttribute("count"); session.setAttribute("count", 1 + count.intValue()); message = "ページカウント: " + count; out.println(message); } } }

    • ベストアンサー
    • Java
  • バッキングビーンとは? マネージドビーンとは?

    バッキングビーンとマネージドビーンについて教えて頂けないでしょうか。 faces-configで定義したbeanがマネージドビーンであるという記述は見たのですが バッキングビーン=マネージドビーンという認識は正しいでしょうか? またJSF+Springでアプリケーションを開発し、bean定義をfaces-configではなくSpring側で行った場合も そのbeanももちろんマネージドビーンと呼びますよね……? 何か勘違いしている箇所がありましたらご指摘をお願いします;;

    • ベストアンサー
    • Java