<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>
import com.google.inject.ImplementedBy;
import com.hopeteam.service.impl.MyServiceImpl;
/*
* 采用annotation进行接口与实现类之间的绑定
* 接口与实现类之间绑定是必须的
*
*/
@ImplementedBy(MyServiceImpl.class)
public
interface MyService {
boolean valid(String username,String password);
}
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;
}
}
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);
}
}
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>
<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>
欢迎光临 黑色海岸线论坛 (http://bbs.thysea.com/) | Powered by Discuz! 7.2 |