SSH框架搭建 筆記 (含spring註解驅動)
好久沒有搭建框架了,今天整理下以前的知識,整合下SSH,沒想到手生了,一時半會各種異常出來,經過一番掙扎後,終於搞出來了雛形,
下面是我做整合框架的筆記,如果大家開發過程中又遇到的情況,可以參考下
首先是包的結構,(命名不算正規哈~,臨時寫的倉促了點)
框架是基於JAR包的基礎上構建的,所以必須必備的jar包必須先下好,
如圖:
沒有的可以在本文原始碼裡下:
搭建框架:
修改web.xml, 加入 struts配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
建立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="struts2" extends="struts-default">
<action name="login" class="test.action.loginAction">
<result name="success" type="redirect">index.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
接下來我們建立一個 測試用的ACTION類,loginAction
package test.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
public String username;
public String password;
public String execute(){
if(!username.equals("admin")){
super.addFieldError("username", "使用者名稱錯誤!");
return ERROR;
}
if(!password.equals("001")){
super.addFieldError("password", "密碼錯誤!");
return ERROR;
}
return SUCCESS;
}
public void validate(){
if(username==null||username.length()==0){
super.addActionError("使用者名稱不能為空");
}
if(password==null||password.length()==0){
super.addActionError("密碼不能為空");
}
}
}
為了方便我們除錯strut是否有效,我們建立一個login.jsp 用於測試
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登入</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<s:form name="form1" action="login" >
<s:textfield name="username" label="username" ></s:textfield>
<s:password name="password" label="password" ></s:password>
<s:submit label="submit"></s:submit>
</s:form>
<s:actionerror/>
</body>
</html>
修改下index.jsp 頁面 登陸成功則友好提示一下
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
login success. <br>
</body>
</html>
使用tomcat載入專案,如果啟動時候不爆出異常,說明strust 基本配置完成,我們進入頁面
如果登陸成功則轉到
Index.jsp
接下配置spring 和hibernate
重新迴歸到 web.xml
我們在其中新增,spring的相關配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/applicationContext*.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
建立applicationContext.xml 檔案 我們在此使用註解驅動(其實說真的,spring到後面不用註解去寫,也就失去它本身的意義,精髓就在於註解的簡潔和易用)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<aop:aspectj-autoproxy />
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="test" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:spring/hibernate.cfg.xml</value>
</property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:advice id="smAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="smMethod" expression="execution(* test.service.impl.*.*(..))" />
<aop:advisor pointcut-ref="smMethod" advice-ref="smAdvice" />
</aop:config>
</beans>
建立hibernate.cfg.xml (使用者名稱密碼,可以自己修改一下)
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test?characterEncoding=utf-8</property>
<property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="test/hibernate/TUser.hbm.xml" />
</session-factory>
</hibernate-configuration>
建立相關DTO類,以及hbm.xml 配置檔案
TUser.java
package test.hibernate;
publicclassTUserimplements java.io.Serializable {
privateintuserid ;
private String username;
private String allname;
private String address;
public String getUsername() {
returnthis.username;
}
publicvoid setUsername(String username) {
this.username = username;
}
public String getAllname() {
returnthis.allname;
}
publicvoid setAllname(String allname) {
this.allname = allname;
}
public String getAddress() {
returnthis.address;
}
publicvoid setAddress(String address) {
this.address = address;
}
publicint getUserid() {
returnuserid;
}
publicvoid setUserid(int userid) {
this.userid = userid;
}
}
TUser.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="test.hibernate.TUser" table="tuser">
<id name="userid" type="java.lang.Integer" column="userid">
<generator class="increment"></generator>
</id>
<property name="username" type="string" column="username" />
<property name="allname" type="string" column="allname" />
<property name="address" type="string" column="address" />
</class>
</hibernate-mapping>
由於測試關係,我們在這裡就省略了DAO層,直接寫service層類去測試 ,採用註解標記
建立相關service 介面以及實現類
IUserService.java
package test.service.imp;
import java.util.List;
import test.hibernate.TUser;
public interface IUserService {
public void saveTuser(TUser user);
public List<TUser> getUserById( String id);
}
UserServiceImpl.java
package test.service.impl;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import test.hibernate.TUser;
import test.service.imp.IUserService;
@Service("userServiceImpl")
public class UserServiceImpl implements IUserService {
@Resource(name = "hibernateTemplate")
private HibernateTemplate hibernateTemplate;
public void saveTuser(TUser user) {
hibernateTemplate.save(user);
hibernateTemplate.flush();
}
@SuppressWarnings("unchecked")
@Transactional(propagation=Propagation.REQUIRED)
public List<TUser> getUserById(String id) {
final String ids = id;
//List<TUser> list = hibernateTemplate.find("from TUser where userid = ?");
List<TUser> list =hibernateTemplate.executeFind(new HibernateCallback() {
public List<TUser> doInHibernate(Session session) throws HibernateException,
SQLException {
Query query = (Query) session.createQuery("from TUser where userid = ? ");
query.setString(0, ids);
return query.list() ;
}
});
return list;
}
}
接下來我們寫一個main 主類來測試我們的spring 和hibernate
SpringTest.java
package test.spring;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import test.hibernate.TUser;
import test.service.imp.IUserService;
@Component("springTest")
public class SpringTest {
@Resource(name = "userServiceImpl")
private IUserService userService ;
public static void main( String[] args ) {
//載入spring配置檔案,初始化IoC容器
ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
//從容器 接管Bean
// TUser user = (TUser) ac.getBean("TUser");
//輸出歡迎資訊
// System.out.println( "Hello:" + user.getUsername() + ";u is in " + user.getAddress() + " ; and b is " + user.getAllname() );
// SessionFactory ss = (SessionFactory) ac.getBean("sessionFactory");
// HibernateTemplate ht = new HibernateTemplate(ss);
// HibernateTemplate ht = (HibernateTemplate) ac.getBean("hibernateTemplate");
//
// List<TUser> list = ht.find("from TUser ");
SpringTest st =(SpringTest) ac.getBean("springTest");
// TUser tu = new TUser();
// tu.setAddress("河西");
// tu.setAllname("河西走廊");
// tu.setUserid(45);
// tu.setUsername("故鄉");
//
// st.userService.saveTuser(tu);
List<TUser> list = st.userService.getUserById("4");//ID在資料庫內找到相應的
for(TUser xx : list){
System.out.println(xx.getAddress()+"||"+xx.getAllname()+"||"+xx.getUsername());
}
}
}
如果出現下面提示,說明你的配置已經完成
以上只是本人臨時的的筆記,如有不妥之處還望網友們指明,和修正,歡迎拍磚