1. 程式人生 > >Maven搭建SSH框架

Maven搭建SSH框架

1. 新建Maven專案

2. pom.xml設定依賴

3. 新建applicationContext.xml

4. web.xml配置spring監聽器和struts2過濾器

5.新建struts.xml

6.建立action

 7.建立service 

 8.建立dao 

 9.建立實體類和與之對應的hbm檔案 

1. 新建Maven專案

2. pom.xml設定依賴

<dependencies>
        <!-- log4j 日誌 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- servlet API -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1-b09</version>
            <scope>provided</scope>
        </dependency>
        <!-- MySQL驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.24</version>
        </dependency>
        <!-- mchange C3P0 資料來源 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5-pre2</version>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.29</version>
        </dependency>
        <!-- sf.json -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier><!--指定jdk版本 -->
        </dependency>
        <!-- struts2 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.14</version>
            <exclusions>
                <exclusion>
                    <groupId>javassist</groupId>
                    <artifactId>javassist</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.3.14</version>
        </dependency>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <!-- aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.2</version>
        </dependency>
        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
		<dependency>
		    <groupId>commons-dbcp</groupId>
		    <artifactId>commons-dbcp</artifactId>
		    <version>1.4</version>
		</dependency>
        <dependency>  
          <groupId>org.slf4j</groupId>  
          <artifactId>slf4j-log4j12</artifactId>  
          <version>1.5.8</version>  
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-entitymanager</artifactId>
		    <version>4.2.2.Final</version>
		</dependency>
		
    </dependencies>
    <build>
       
		 <plugins>
		    <!-- 資原始檔拷貝外掛 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.7</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- java編譯外掛 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<port>8081</port>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>

3. 新建applicationContext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd        
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	
	<context:component-scan base-package="com.lq" />

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver">
		</property>
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/test">
		</property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">
					true
				</prop>
			</props>
		</property>
		
		<property name="mappingResources"> 
			<list> 
				<value>hbm/User.hbm.xml</value> 
			</list>
		</property>

	</bean>
	<!-- 配置事務管理器(採用註解的方式) -->
	<bean id="txManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 開啟註解事務 -->
	<tx:annotation-driven transaction-manager="txManager" />
</beans>

4. web.xml配置spring監聽器和struts2過濾器

<!-- 配置Spring的監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     
    <!-- 指定Spring配置檔案所在路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param> 
  	<!-- 配置Struts2過濾器 -->
    <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>

5.新建struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="false" />
    <!-- <constant name="struts.objectFactory" value="spring" /> -->
    <package name="default" namespace="/" extends="struts-default">
        <action name="user" class="com.lq.action.UserAction">
            <result name="success">/index.jsp</result>
        </action>
    </package> 
</struts>

6.建立action

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.lq.model.User;
import com.lq.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;
@Controller
public class UserAction extends ActionSupport{
	private User user;
	@Autowired
	private IUserService userService;
	
	@Override
	public String execute() throws Exception {
		userService.login();
		return "success";
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
}

 7.建立service 

public interface IUserService {
	public boolean login();
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lq.dao.UserDao;
/**
 * 
 * @author haowl
 *@Transactional 可以作用於介面、介面方法、類以及類方法上。當作用於類上時,
 * 該類的所有 public 方法將都具有該型別的事務屬性
 * 該屬性用於設定需要進行回滾的異常類陣列,當方法中丟擲指定異常陣列中的異常時,則進行事務回滾。例如:
         指定單一異常類:@Transactional(rollbackFor=RuntimeException.class)
        指定多個異常類:@Transactional(rollbackFor={RuntimeException.class, Exception.class})
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService{
	@Autowired
	private UserDao userDao;
	
	@Override
	public boolean login() {
		return userDao.login();
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
}

 8.建立dao 

import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import com.lq.model.User;

@Repository
public class UserDao extends HibernateDaoSupport{
	
	public boolean login() {
	    Session session =getSessionFactory().openSession();
	    String sql="select * from tb_users where username=?";
	    User user = (User)session.createSQLQuery(sql).addEntity(User.class).setParameter(0, "123456").uniqueResult();
		System.out.println(user.getLikes());
	    return false;
	}
	//按照名稱找到sessionFacotry注入給父類的sessionFacotry屬性
	@Resource
	public void setSessionFacotry(SessionFactory sessionFacotry) {  
        super.setSessionFactory(sessionFacotry);  
    } 

}

 9.建立實體類和與之對應的hbm檔案

public class User implements java.io.Serializable {
    private String username;
    private String password;
    private String email;
    private String sex;
    private String likes;
    
	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 getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getLikes() {
		return likes;
	}
	public void setLikes(String likes) {
		this.likes = likes;
	}
    
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.lq.model.User" table="tb_users" >
        <id name="username" type="string">
            <column name="username" />
            <generator class="uuid" />
        </id>
        <property name="password" type="string">
            <column name="password" length="32" />
        </property>
        <property name="email" type="string">
            <column name="email" length="32" />
        </property>
        <property name="sex" type="string">
            <column name="sex" length="32" />
        </property>
        <property name="likes" type="string">
            <column name="likes" length="32" />
        </property>
    </class>
</hibernate-mapping>

注:hbm檔案放在resources下