2011年11月6日日曜日

Struts2 + Spring + mybatis! web.xmlとstruts.xml

できる限りXMLレスで行こうという今回のアプリ作成。
でも、やっぱり必要なXMLは書かなきゃね。

まずは、web.xml。当然。
<?xml version="1.0" encoding="UTF-8" ?>

<web-app 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_3_0.xsd"
 version="3.0">
 <display-name>TagDiary</display-name>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <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>

 <jsp-config>
  <jsp-property-group>
   <url-pattern>*.jsp</url-pattern>
   <el-ignored>false</el-ignored>
   <page-encoding>UTF-8</page-encoding>
   <scripting-invalid>false</scripting-invalid>
   <include-prelude>/WEB-INF/include/jsp_header.jsp</include-prelude>
  </jsp-property-group>
 </jsp-config>
</web-app>
context-paramとlistenerがSpringのため。
filterとfilter-mappingがStruts2のため。

で、JSPではJSTLとStruts2のカスタムタグをよく使う予定なのですが、
いちいち<%@ taglib ... %>を書くのが嫌なので、
JSPに共通の宣言は、 jsp_header.jsp ファイルに押しやって、
そいつをinclude-prelude。
これはほんとうに便利だ・・・。

次は、struts.xml。これは、クラスパスが通っているところに置くと、勝手に読み込んでくれるらしいので便利。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory"/>
</struts>
org.apache.struts2.spring.StrutsSpringObjectFactoryを使わないと、ActionにサービスをInjectできないっぽい。
でも、基本的にアノテーションでやりたいので、struts.xmlには全然書きません。

次のエントリでは、Springとmybatisの設定であるところの、
applicationContext.xml を書くと思います。