GuiceのStruts2 pluginサンプル
User's Guideに載っていて、ソースコードもついてくるGuiceのStruts2 pluginのサンプルを動かしてみました。が、これがなかなか動いてくれなくて苦労したのでメモです。
ここ数年?Strutsなんてまったく使っていなかったのでどうやったら動かせるのかわからなくなっていました。加えてGuiceのUser's Guideにはweb.xmlにGuiceFilterの設定が必要だなんてことは書いていないし、struts.xmlも断片的、import文が無いので SUCCESSって何?と思いました。なんとか動いたときのファイルはこんなものです。
- web.xml
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts Guice Test</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter> <filter-name>guice</filter-name> <filter-class>com.google.inject.servlet.GuiceFilter</filter-class> </filter> <filter-mapping> <filter-name>guice</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<?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="guice" /> <package name="strutsguicetest" extends="struts-default"> <action name="Count" class="com.google.inject.struts2.example.Count"> <result>/Counter.jsp</result> </action> </package> </struts>
- Counter.java
package com.google.inject.struts2.example; import com.google.inject.servlet.SessionScoped; @SessionScoped public class Counter { private int count = 0; public synchronized int increment() { return count++; } public Counter() { } }
- Count.java
package com.google.inject.struts2.example; import com.google.inject.Inject; import com.opensymphony.xwork2.ActionSupport; public class Count { private final Counter counter; @Inject public Count(Counter counter) { this.counter = counter; } public String execute() throws Exception { return ActionSupport.SUCCESS; } public int getCount() { return counter.increment(); } }
- Counter.jsp
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!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>JSP Page</title> </head> <body> <h1>JSP Page</h1> <h2>Counter Example</h2> <h3> <b>Hits in this session:</b> <s:property value="count"/> </h3> </body> </html>
- Jarアーカイブ
guice-1.0.jar, guice-servlet-1.0.jar, guice-struts2-plugin-1.0.jar, struts2-core-2.0.6.jar, xwork-2.0.1.jar, ognl-2.6.11.jar, freemarker-2.3.8.jar, commons-logging-1.0.4.jar
- URL
http://localhost:8084/strutsguicetest/Count.actionで実行できました。projectの名前をstrutsguicetestにしてあるので、そういうパス名になっています。ポートが8084なのはnetbeansを使っていたからです。
以上で、リロードするたびに無事カウントアップされました。