码迷,mamicode.com
首页 > 系统相关 > 详细

Eclipse + Maven 搭建 SSH 环境

时间:2016-07-03 19:18:18      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

1、安装Maven,下载地址:http://mirrors.cnnic.cn/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.zip,下载后,解压缩到D:盘,系统变量中添加M2_HOME=D:\apache-maven-3.3.9,编辑PATH变量,在末尾添加%M2_HOME%\bin。

在%M2_HOME%下创建repo文件夹,编辑%M2_HOME%\conf\settings.xml,添加配置

 

<localRepository>D:/apache-maven-3.3.9/repo</localRepository>

 

2、打开Eclipse,选择Help - Install New Software,在Work with输入框中输入:http://mirror.bit.edu.cn/eclipse/technology/m2e/releases/,这是国内的mirror,速度稍微快点,Pending后,选择安装Maven Integration for Eclipse,一路Next,漫长的安装结束后,重启Eclipse。

 

3、选择Window - Preferences - Maven - Installations - add,选择Maven安装目录,保存结果。

 

4、File - New - Project,选择Maven Project,Next,Next,漫长的Retrieving archetypes后,Catalog选择Maven Central,Filter输入:maven-archetype-webapp,Next,Group Id输入:com.moapp,Artifact Id输入工程名:mavenSSH,点击Finish。

 

5、编辑pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.moapp</groupId>
	<artifactId>mavenSSH</artifactId>
	<version>1.0</version>
	<name>mavenSSH</name>
	<url>http://maven.apache.org</url>
	<packaging>war</packaging>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.0.RELEASE</spring.version>
		<hibernate.version>5.2.0.Final</hibernate.version>
		<struts2.version>2.5.1</struts2.version>
		<jackson.version>2.7.5</jackson.version>
		<log4j.version>2.5</log4j.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.5.1</version>
			<exclusions>
				<exclusion>
					<groupId>javax.servlet</groupId>
					<artifactId>servlet-api</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
			<version>1.0.1.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>${struts2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>${struts2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mortbay.jetty</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0.20100224</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-web</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.3</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.13</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.21</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.9</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>mavenSSH</finalName>
		<plugins>
			<!-- Run the JUnit unit tests in an isolated classloader -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19.1</version>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.4</version>
				<configuration>
					<javadocDirectory>target/javadoc</javadocDirectory>
					<reportOutputDirectory>target/javadoc</reportOutputDirectory>
					<charset>UTF-8</charset>
					<encoding>UTF-8</encoding>
					<docencoding>UTF-8</docencoding>
					<show>private</show>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.cargo</groupId>
				<artifactId>cargo-maven2-plugin</artifactId>
				<version>1.5.0</version>
				<configuration>
					<container>
						<containerId>tomcat7x</containerId>
						<home>D:\tomcat</home><!--Tomcat安装目录-->
					</container>
					<configuration>
						<type>existing</type>
						<home>D:\tomcat</home><!--Tomcat安装目录-->
					</configuration>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

保存pom.xml,系统自动下载jar及其依赖文件
 

6、编辑src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="mavenSSH" version="3.0">

	<display-name>mavenSSH</display-name>

	<!-- spring 和  Hibernate的配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
		     classpath:spring.xml
		     classpath:spring-hibernate.xml
	    </param-value>
	</context-param>

	<!-- 编码设置 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- openSessionInView配置 作用是延迟session关闭到view层 -->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 防止spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- Struts2 filter -->
	
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>


	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>

	<!-- 配置session超时时间,单位分钟 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>

	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


7、新建src/main/java/spring.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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 加载配置文件 -->
	
	<context:property-placeholder location="classpath:config.properties"/>
	<!-- 扫描service自动注入为bean -->
	<context:component-scan base-package="com.moapp.mavenSSH" />

</beans>


8、新建src/main/java/spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<!-- 配置数据源 使用的是Druid数据源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 初始化连接大小 -->
		<property name="initialSize" value="0" />
		<!-- 连接池最大使用连接数量 -->
		<property name="maxActive" value="20" />
		
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="0" />
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="60000" />
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="33" />
		<!-- 用来检测有效sql -->
		<property name="validationQuery" value="${validationQuery}" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="testWhileIdle" value="true" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />
		<!-- 打开removeAbandoned功能 -->
		<property name="removeAbandoned" value="true" />
		<!-- 1800秒,也就是30分钟 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 关闭abanded连接时输出错误日志 -->
		<property name="logAbandoned" value="true" />
		<!-- 监控数据库 -->
		<property name="filters" value="mergeStat" />
	</bean>

	<!-- 配置hibernate的SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 注入数据源 相关信息看源码 -->
		<property name="dataSource" ref="dataSource" />
		<!-- hibernate配置信息 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
			</props>
		</property>
		<!-- 扫描hibernate注解配置的entity -->
		<property name="packagesToScan" value="com.moapp.mavenSSH.beans" />
	</bean>

	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 配置事务增强处理Bean,指定事务管理器 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<!-- 配置详细事务处理语义 -->
		<tx:attributes>
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />

			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="load*" propagation="SUPPORTS" read-only="true" />

			<!-- 其他采用默认事务方式 -->
			<tx:method name="*" />

		</tx:attributes>
	</tx:advice>

	<!-- Spring aop事务管理 -->
	<aop:config>
		<!-- 配置切入点 -->
		<aop:pointcut id="transactionPointcut" expression="execution(* com.moapp.mavenSSH.serviceImpl.*.*(..))" />
		<!-- 指定在txAdvice切入点应用txAdvice事务增强处理 -->
		<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
	</aop:config>

</beans>


9、新建src/main/java/config.properties

#application configs

#jdbc druid config
validationQuery = SELECT 1
#mysql connect 6.x 使用com.mysql.cj.jdbc.Driver
jdbc.driverClassName = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
jdbc.username = devel
jdbc.password = 123456

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update

 

10、新建src/main/java/struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<!-- 指定由spring负责action对象的创建 -->
	<constant name="struts.objectFactory" value="spring" />
	<!-- 所有匹配*.action的请求都由struts2处理 -->
	<constant name="struts.action.extension" value="action" />
	<!-- 是否启用开发模式 -->
	<constant name="struts.devMode" value="true" />
	<!-- struts配置文件改动后,是aa否重新加载 -->
	<constant name="struts.configuration.xml.reload" value="true" />
	<!-- 设置浏览器是否缓存静态内容 -->
	<constant name="struts.serve.static.browserCache" value="false" />
	<!-- 请求参数的编码方式 -->
	<constant name="struts.i18n.encoding" value="utf-8" />
	<!-- 每次HTTP请求系统都重新加载资源文件,有助于开发 -->
	<constant name="struts.i18n.reload" value="true" />
	<!-- 文件上传最大值 -->
	<constant name="struts.multipart.maxSize" value="104857600" />
	<!-- 让struts2支持动态方法调用 -->
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<!-- Action名称中是否还是用斜线 -->
	<constant name="struts.enable.SlashesInActionNames" value="false" />
	<!-- 允许标签中使用表达式语法 -->
	<constant name="struts.tag.altSyntax" value="true" />
	<!-- 对于WebLogic,Orion,OC4J此属性应该设置成true -->
	<constant name="struts.dispatcher.parametersWorkaround" value="false" />

	<!-- 用于CRUD Action的parent package -->
	<package name="crud-default" extends="convention-default">
		<!-- 基于paramsPrepareParamsStack, 增加store interceptor保证actionMessage在redirect后不会丢失 -->
		<interceptors>
			<interceptor-stack name="crudStack">
				<interceptor-ref name="store">
					<param name="operationMode">AUTOMATIC</param>
				</interceptor-ref>
				<interceptor-ref name="paramsPrepareParamsStack" />
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="crudStack" />
	</package>

	<!-- 使用Convention插件,实现约定大于配置的零配置文件风格. 特殊的Result路径在Action类中使用@Result设定. -->

</struts>


11、新建src/main/java/log4j.properties

### set log levels ###
log4j.rootLogger = INFO , C , D , E 

### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [mavenSSH][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/ssh_mavenSSH.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [mavenSSH][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/ssh_mavenSSH_error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [mavenSSH][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n


 12、新建src/main/java/log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" />
		</Root>
	</Loggers>
</Configuration>

 

13、建立mysql数据库test,新建表user,新建用户devel,密码123456,赋予devel对test数据库的所有权限

create database test default charset utf8 collate utf8_general_ci;
use test;
create table user (
id int auto_increment not null,
userName varchar(50) not null,
password char(32) not null,
gender tinyint not null,
primary key(id)
)ENGINE=MyISAM;
grant all privileges on test.* to 'devel'@'localhost' identified by '123456';
flush privileges;


14、bean/dao/service/action文件

com.moapp.mavenSSH.beans.User.java
 

package com.moapp.mavenSSH.beans;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name = "user")
public class User implements Serializable {
	private static final long serialVersionUID = 3834833794454172304L;
	private int id;
	private String userName;
	private String password;
	private int gender;
	
	@Id
	@Column(name = "id", unique = true,  nullable = false, insertable = false, updatable = false)
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	@Column(name = "userName", nullable = false)
	public String getUserName() {
		return userName;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Column(name = "password", nullable = false)
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}

	@Column(name = "gender", nullable = false)
	public int getGender() {
		return gender;
	}
	
	public void setGender(int gender) {
		this.gender = gender;
	}
}


com.moapp.mavenSSH.dao.BaseDao.java

package com.moapp.mavenSSH.dao;

import java.io.Serializable;
import java.util.List;

public interface BaseDao <T, PK extends Serializable> {
	T load(PK id);
	T get(PK id);
	List<T> findAll();
	void persist(T entity);
	PK save(T entity);
	void saveOrUpdate(T entity);
	void delete(PK id);
	void flush();
}


com.moapp.mavenSSH.dao.UserDao.java

package com.moapp.mavenSSH.dao;

import com.moapp.mavenSSH.beans.User;
import com.moapp.mavenSSH.dao.BaseDao;

public interface UserDao extends BaseDao<User, Integer> {
}


com.moapp.mavenSSH.daoImpl.UserDaoImpl.java

package com.moapp.mavenSSH.daoImpl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.moapp.mavenSSH.beans.User;
import com.moapp.mavenSSH.dao.UserDao;

@Repository("UserDao")
public class UserDaoImpl implements UserDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public User load(Integer id) {
		return getCurrentSession().load(User.class, id);
	}

	@Override
	public User get(Integer id) {
		return getCurrentSession().get(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		return getCurrentSession().createQuery("from user").getResultList();
	}

	@Override
	public void persist(User entity) {
		getCurrentSession().persist(entity);
	}

	@Override
	public Integer save(User entity) {
		return (Integer)getCurrentSession().save(entity);
	}

	@Override
	public void saveOrUpdate(User entity) {
		getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public void delete(Integer id) {
		getCurrentSession().delete(this.get(id));
	}

	@Override
	public void flush() {
		getCurrentSession().flush();
	}

}

com.moapp.mavenSSH.service.UserManager.java

package com.moapp.mavenSSH.service;

import java.util.List;

import com.moapp.mavenSSH.beans.User;

public interface UserManager {
	User load(Integer id);
	User get(Integer id);
	List<User> findAll();
	void persist(User entity);
	Integer save(User entity);
	void saveOrUpdate(User entity);
	void delete(Integer id);
	void flush();
}


com.moapp.mavenSSH.serviceImpl.UserManagerImpl.java

package com.moapp.mavenSSH.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.moapp.mavenSSH.beans.User;
import com.moapp.mavenSSH.dao.UserDao;
import com.moapp.mavenSSH.service.UserManager;

@Service("userManager")
public class UserManagerImpl implements UserManager {
	@Autowired
	UserDao userDao;

	@Override
	public User load(Integer id) {
		return null;
	}

	@Override
	public User get(Integer id) {
		return userDao.get(id);
	}

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	@Override
	public void persist(User entity) {
		userDao.persist(entity);
	}

	@Override
	public Integer save(User entity) {
		return userDao.save(entity);
	}

	@Override
	public void saveOrUpdate(User entity) {
		userDao.saveOrUpdate(entity);
	}

	@Override
	public void delete(Integer id) {
		userDao.delete(id);
	}

	@Override
	public void flush() {
		userDao.flush();
	}

}


com.moapp.mavenSSH.action.UserAction.java

package com.moapp.mavenSSH.action;

import com.moapp.mavenSSH.beans.User;
import com.moapp.mavenSSH.service.UserManager;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.AllowedMethods;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

@ParentPackage("struts-default")
@Namespace("/user")
@AllowedMethods("detail")
@Results({
	@Result(name = "success", location = "/user/user.jsp")
})
public class UserAction extends ActionSupport implements ModelDriven<User>, Preparable {
	private static final long serialVersionUID = -4611010990125262639L;
	private static final Logger LOGGER = Logger.getLogger(UserAction.class);
	private Integer id;
	User user;
	List<User> userList;
	
	@Autowired
	private UserManager userManager;
	
	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
	
	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	public List<User> getUserList() {
		return userList;
	}
	
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	
	@Override
	public void prepare() throws Exception {
		
	}

	@Override
	public User getModel() {
		if (null != id) {
			user = userManager.get(id);
		} else {
			user = new User();
		}
		return user;
	}
	
	@Override
	public String execute() throws Exception {
		LOGGER.info("查询所有用户");
		userList = userManager.findAll();
		return SUCCESS;
	}

	public void detail() throws IOException {
		String id = ServletActionContext.getRequest().getParameter("id");
		LOGGER.info("查询用户详情:" + id);
		user = userManager.get(Integer.valueOf(id));
		//AjaxUtil.ajaxJSONResponse(user);
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		out.println("Hello " + user.getUserName());
	}

}


src/main/webapp/user/user.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<title>userInfo</title>
</head>
<body>
	全部用户信息:
	<c:forEach items="${userList}" var="user">
	    <div>姓名:${user.userName } 性别:${user.gender } <a target="_blank" href="user/user!detail.action?id=${user.id}">用户详情</a></div>
	</c:forEach>

</body>
</html>


15、JUnit测试文件

com.moapp.mavenSSH.service.TestUserManager.java

package com.moapp.mavenSSH.service;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.moapp.mavenSSH.beans.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
		"classpath:spring.xml",
		"classpath:spring-hibernate.xml"
})
public class TestUserManager {
	private static final Logger LOGGER = Logger.getLogger(TestUserManager.class);
	@Autowired
	UserManager userManager;
	
	@Test
	public void save() {
		User user = new User();
		user.setUserName("fengwusan");
		user.setPassword("123456");
		user.setGender(0);
		Integer id = userManager.save(user);
		JSON.toJSONString(id);
	}
}

选择Debug-Debug as - JUnit Test,配置无误,则运行正常,不然需要自己调试了。

Eclipse + Maven 搭建 SSH 环境

标签:

原文地址:http://blog.csdn.net/fengwusan/article/details/51815427

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!