第一步,配置在web.xml中Struts2以及Guice的filter
<filter>
<filter-name>guice</filter-name>
<filter-class>
com.google.inject.servlet.GuiceFilter
</filter-class>
</filter>
<filter>
<filter-name>struts</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>guice</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第二步,建立一个Service的接口:MyService
import com.google.inject.ImplementedBy;
import com.hopeteam.service.impl.MyServiceImpl;
/*
* 采用annotation进行接口与实现类之间的绑定
* 接口与实现类之间绑定是必须的
*
*/
@ImplementedBy(MyServiceImpl.class)
public
interface MyService {
boolean valid(String username,String password);
}
第三步,创建Service的实现类:MyServiceImpl
import com.google.inject.Singleton;
import com.hopeteam.service.MyService;
/*
* 我们用@Singleton来标注它
*
*/
@Singleton
public
class MyServiceImpl implements MyService{
public
boolean valid(String username,String password)
{
if(username.equals("fengzhizi")
&& password.equals("123456"))
return
true;
else
return
false;
}
}
Guice通过Module来配置而不同于Spring框架通过xml进行配置。Guice通过绑定器Binder来传递我们的模块。一个绑定通常包含一个从接口到具体实现的映射
第四步,创建Module:MyModule
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.hopeteam.service.MyService;
import com.hopeteam.service.impl.MyServiceImpl;
public
class MyModule implements Module {
public
void configure(Binder binder) {
/*
* 将接口MyService 与其实现MyServiceImpl 绑定在一起
并且作用域为Scopes.SINGLETON
*其中如果不配置作用域,默认就是类似于Spring的Scope="prototype"
*/
binder.bind(MyService.class).to(MyServiceImpl.class).in(
Scopes.SINGLETON);
}
}
第五步,创建Action:LoginAction
import com.google.inject.Inject;
import com.hopeteam.service.MyService;
import com.opensymphony.xwork2.Action;
public
class LoginAction implements Action{
private String username;
private String password;
private String tip;
/*
* 通过field字段进行注入
*/
@Inject
private MyService ms;
public String getUsername() {
return
username;
}
public
void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return
password;
}
public
void setPassword(String password) {
this.password = password;
}
public String getTip() {
return
tip;
}
public
void setTip(String tip) {
this.tip = tip;
}
public String execute() throws Exception
{
if(ms.valid(getUsername(),getPassword()))
{
setTip("Guice和Struts2整合成功!");
return
SUCCESS;
}
else
return
ERROR;
}
}
配置struts的配置文件:struts.xml
<struts>
<constant name="struts.objectFactory" value="guice" />
<package name="fengzhizi" extends="struts-default">
<action name="login" class="com.hopeteam.action.LoginAction">
<result name="error">/error.jsp</result>
<result name="success">/welcome.jsp</result>
</action>
</package>
</struts>
其中,<constant name="struts.objectFactory" value="guice" />是将Struts2的对象进行注入,包括动作和拦截器。
好了大功告成,我们看一下登陆页面吧
登陆后的页面: