java学习笔记(11) —— Struts2与Spring的整合

1、右键 项目名称 —— MyEclipse —— Add Spring Capabilities

2、选取 Copy checked Library contents to project folder

3、建立IService 与 Service 【Spring 同样是面向接口编程,因此需要引入IService】

public interface ILoginService
{
public boolean isLogin(String username,String password);
}
public class LoginService implements ILoginService {

    public boolean isLogin(String username, String password) {
if("james".equals(username) && "james".equals(password))
return true;
else
return false;
}
}

4、Action类引入接口,并通过具体实现调用isLogin 方法

   private ILoginService loginservice;
   
public void setLoginservice(ILoginService loginservice) {
        this.loginservice = loginservice;
    }
public String execute() throws Exception
{
if(loginservice.isLogin(this.getUsername(), this.getPassword()))
return SUCCESS;
else {
return "failer";
}
}

5、配置struts.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="ILoginService" class="com.test.service.impl.LoginService"></bean>
//每有一个请求就生成一个Action的实例
<bean id="loginAction" class="com.test.action.LoginAction" scope="prototype">
  //loginservice 是LoginAction中引用的对象名称
<property name="loginservice">
<ref local="ILoginService"/>
</property>
</bean>
</beans>

6、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param> <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> <servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.test.servlet.UploadServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> </web-app>

7、引入的jar包

java学习笔记(11) —— Struts2与Spring的整合

上一篇:多浏览器兼容用javascript获取url参数的方法比较推荐的一种


下一篇:即将上线的Kafka 集群(用CM部署的)无法使用“--bootstrap-server”进行消费,怎么破?