1,整合Struts2
a)導入struts的jar包
struts2-core-2.1.6.jar xwork-2.1.2.jar ognl-2.6.11.jar freemarker-2.3.13.jar commons-logging-1.1.jar commons-fileupload-1.2.1.jar
b)將struts.xml文件拷貝到src目錄下
c)在web.xml裡配置struts的核心過濾器
<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>
2,整個Spring
a)導入Spring的jar包 spring.jar commons-logging.jar
b)將applicationContext.xml文件拷貝到WEB-INF目錄下
c)在web.xml裡配置spring的監聽器
<!-- 配置spring監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
d)添加spring與struts2整合的插件 struts2-spring-plugin-2.1.6.jar
3,編寫代碼測試
登錄頁面login.jsp
<body>
<form action="login" method="post">
USERNAME:<input type="text" name="username" /><br>
PASSWORD:<input type="password" name="password" /><br>
<input type="submit" value="登錄">
</form>
</body>
登錄成功頁面 success.jsp
<body>
登錄成功!
</body>
LoginDao業務接口
package com.itmyhome.actioin;
interface LoginDao {
public boolean login(String username,String password);
}
LoginDaoImpl業務接口實現
package com.itmyhome.actioin;
public class LoginDaoImpl implements LoginDao {
public boolean login(String username, String password) {
// TODO Auto-generated method stub
if("zhangsan".equals(username)&&"123".equals(password)){
return true;
}else{
return false;
}
}
}
LoginAction
package com.itmyhome.actioin;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
private LoginDao loginDao; //此DAO交給spring來處理
public String execute(){
if(loginDao.login(username, password)){
return "success";
}else{
return "input";
}
}
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 LoginDao getLoginDao() {
return loginDao;
}
public void setLoginDao(LoginDao loginDao) {
this.loginDao = loginDao;
}
}
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>
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="com.itmyhome.actioin.LoginAction">
<result name="success">/success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
<!-- Add packages here -->
</struts>
applicationContext.xml配置文件
<bean id="loginDao" class="com.itmyhome.actioin.LoginDaoImpl" />
<!-- 可注釋 -->
<bean id="loginAction" class="com.itmyhome.actioin.LoginAction">
<property name="loginDao" ref="loginDao" />
</bean>
部署,啟動tomcat 輸入"zhangsan","123" 跳轉到success.jsp 整合成功
摘自 itmyhome的專欄