首页 > 代码库 > 搭建SpringMVC+Hibernate4+Spring3+Ajax+Maven项目

搭建SpringMVC+Hibernate4+Spring3+Ajax+Maven项目

首先新建一个Maven项目。百度一下会有非常多实例,这里就不介绍了,直接奔主题。
如题:这里使用的是Hibernate4和Spring3,使用的JPA和Spring注解,然后JDK版本号是1.7
以下这张图片演示的是整个项目的结构图。
-------------------------------------------------------
     技术分享
---------------------------------------------------
首先配置pom.xml,将所需的jar包配置好。例如以下,
<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>org.phn</groupId>
<artifactId>PHN</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>PHN Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 指定maven仓库 -->
<repositories><!-- 发现依赖和扩展的远程资源库 -->
<!-- maven自己官方仓库 -->
<repository>
<id>maven</id>
<name>Maven Repository Switchboard</name>
<layout>default</layout>
<url>http://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<!-- 阿里巴巴公布版本号仓库 -->
<repository>
<id>alibaba-opensource</id>
<name>alibaba-opensource</name>
<url>http://code.alibabatech.com/mvn/releases/</url>
<layout>default</layout>
</repository>
<!-- 阿里巴巴快照版本号仓库 -->
<repository>
<id>alibaba-opensource-snapshot</id>
<name>alibaba-opensource-snapshot</name>
<url>http://code.alibabatech.com/mvn/snapshots/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号号 -->
<spring.version>3.2.4.RELEASE</spring.version>
<hibernate.version>4.2.5.Final</hibernate.version>
<!-- log4j日志文件管理包版本号 -->
<!-- <slf4j.version>1.7.10</slf4j.version> -->
<log4j.version>1.2.17</log4j.version>
</properties>
<!-- maven打成war包放到tomcat文件夹下,就可以执行 -->
<build>
<finalName>PHN</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- junit測试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
 
<!-- servlet api jar -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
 
<!-- fastJson json数组有关的 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.26</version>
</dependency>
 
<!-- 使用 Jackson 把 Java 对象转换成 JSON 字串 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- 阿里巴巴数据源包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency> -->
 
 
<!-- aspectjweaver.jar这是Spring AOP所要用到的包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.1</version>
</dependency>
 
<!-- hibernate4 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</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>
 
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
 
<!-- spring3 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-jdbc</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-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
 
 
</dependencies>
</project>
然后建日志配置文件log4j.properties,例如以下
log4j.rootLogger=INFO,A1,R
 
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n
 
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=sshf.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.Threshold=ALL
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
继续建jdbc配置文件config.properties,例如以下。当中非常多多余的。能够依照自己须要的进行配置。相信都会看得懂的,
#\u5C5E\u6027\u6587\u4EF6
 
#Oracle \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc_username=
#jdbc_password=
 
#SQLServer \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=
#jdbc_password=
 
#Derby \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=
#jdbc_password=
 
#MySQL \u7684\u914D\u7F6E
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/phn?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=123456
 
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
 
sessionInfoName=sessionInfo
 
uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
接着继续配置web.xml文件,当中有3个文件,名为:spring.xml,spring-hibernate.xml,spring-mvc.xml,顾名思义相信大家应该也能够猜出一部分。当中spring.xml和spring-hibernate.xml是能够合并成applicationcontext.xml文件的,这里是为了区分以后可能会有什么Spring-mybatis.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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name></display-name>
<!-- spring hibernate -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
</context-param>
<!-- openSessionInView配置 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--spring mvc 配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup> <!-- 是启动顺序,让这个Servlet随Servletp容器一起启动。 -->
</servlet>
 
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern> <!-- 会拦截/的请求。 -->
</servlet-mapping>
 
 
<!-- encodeing -->
<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>
<!-- encoding filter for jsp page -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 
 
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
接着我们開始建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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
 
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties" />
 
<!-- 自己主动扫描dao和service包(自己主动注入) -->
<context:component-scan base-package="com.phn.dao,com.phn.service" />
 
</beans>
继续建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-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
 
<!-- JNDI(通过Tomcat)方式配置数据源 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="http://www.mamicode.com/${jndiName}"></property> </bean> -->
<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<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="maxIdle" value="20" />
<!-- 连接池最小空暇 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
 
<!-- <property name="poolPreparedStatements" value="http://www.mamicode.com/true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="http://www.mamicode.com/33" /> -->
 
<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="http://www.mamicode.com/stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
 
<!-- 配置hibernate session工厂 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<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>
</props>
</property>
 
<!-- 自己主动扫描注解方式配置的hibernate类文件 -->
<property name="packagesToScan">
<list>
<value>com.phn.model</value>
</list>
</property>
</bean>
 
<!-- 配置事务管理器 -->
<bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
 
<!-- 注解方式配置事物 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
 
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" />
<tx:method name="save*" />
<tx:method name="update*" />
<tx:method name="modify*" />
<tx:method name="edit*" />
<tx:method name="delete*" />
<tx:method name="remove*" />
<tx:method name="repair" />
<tx:method name="deleteAndRepair" />
 
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<!-- 这里是针对我写的推断用户是否存在数据库的方法的事务,假设不配置的话就会出现no session异常 --> 
<tx:method name="is*" />
 
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.phn.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
</beans>
继续建spring-mvc.xml,这里也不讲了哈,感觉没什么讲的,哈哈,有几个须要注意的地方最后讲,先把项目搭起来再说。技术分享
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
<!-- 注解扫描包 -->
<context:component-scan base-package="com.phn.controller" />
 
<!-- <context:component-scan /> -->
<!-- 扫描指定的包中的类上的注解,经常使用的注解有: -->
<!-- @Controller 声明Action组件 -->
<!-- @Service 声明Service组件 @Service("xxxService") -->
<!-- @Repository 声明Dao组件 -->
<!-- @Component 泛指组件, 当不好归类时. -->
<!-- @RequestMapping("/menu") 请求映射 -->
<!-- @Resource 用于注入。( j2ee提供的 ) 默认按名称装配。@Resource(name="beanName") -->
<!-- @Autowired 用于注入。(spring提供的) 默认按类型装配 -->
<!-- @Transactional( rollbackFor={Exception.class}) 事务管理 -->
<!-- @ResponseBody将内容或对象作为 HTTP 响应正文返回。并调用适合HttpMessageConverter的Adapter转换对象,写入输出流 -->
<!-- @Scope("prototype") 设定bean的作用域 -->
 
 
<!-- 开启MVC注解,表示SpringMVC支持注解功能 做了非常多事情,不包含加入自定义的拦截器 -->
<mvc:annotation-driven />
 
<!-- 拦截器 -->
<!-- <mvc:interceptors> <bean class="com.phn.inteceptor" /> </mvc:interceptors> -->
 
<!-- 方案一 (二选一)表示不正确静态资源如CSS、JS、HTML等进行拦截 -->
<!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源,使用默认的servlet来响应请求 -->
<!-- <mvc:default-servlet-handler /> -->
 
<!-- 方案二 (二选一) 静态资源映射 -->
<mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
<mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
<mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
<mvc:resources mapping="/html/**" location="/WEB-INF/html/" />
 
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
 
 
<!-- 启动Spring MVC的注解功能,完毕请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
</beans>
到这里配置的已经差点儿相同了,接下来開始编写server端的代码。

记得先建立一个数据库哈,这个不要忘记了,我建的是phn命名的数据库。
大家先依照我对包命名的方式对自己的项目建好响应的包吧。这样高速好继续一下步骤。

先从实体開始吧。在model包中建一个UserEntity类,代码例如以下。这里使用了Java JPA,已经在Spring-Hibernate.xml里面配置了能够自己主动生成数据库表的对应代码了。
package com.phn.model;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
 
/**
* @author phn
*/
@Table(name="t_user")
@Entity
public class UserEntity {
private int id;
private String username;
private String password;
private boolean sex; // 默觉得0。0表示男,1表示女
 
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UID", nullable = false, length = 9)
public int getId() {
return id;
}
 
public void setId(int id) {
this.id = id;
}
 
@Column(name = "UNAME", nullable = false, length = 20)
public String getUsername() {
return username;
}
 
public void setUsername(String username) {
this.username = username;
}
 
@Column(name = "UPASSWORD", nullable = false, length = 32)
public String getPassword() {
return password;
}
 
public void setPassword(String password) {
this.password = password;
}
 
@Column(name = "USEX", nullable = false, length = 1)
public boolean isSex() {
return sex;
}
 
public void setSex(boolean sex) {
this.sex = sex;
}
 
@Override
public String toString() {
return "User [ \nid : " + this.id + "\nusername : " + this.username
+ "\npassword : " + this.password + "\nsex : " + this.sex
+ " ]";
}
 
}
接着開始编写数据訪问层(DAO层)接口。新建IUserDao接口。加入一下代码,这里就写了一个方法推断用户是否存在,用来验证用户登录。


package com.phn.dao;
 
import com.phn.model.UserEntity;
 
/**
* @author phn
*/
public interface IUserDao {
public boolean isExist(UserEntity user);
}
继续编写数据訪问层(DAO层)的实现类UserDaoImpl类,依赖注入使用的是@Resource注解,还能够用@Autowired注解的。这里先不解释。后面再解释,继续我们项目的搭建。
package com.phn.dao.impl;
 
import javax.annotation.Resource;
 
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
 
import com.phn.dao.IUserDao;
import com.phn.model.UserEntity;
 
/**
* @author phn
*/
 
@Repository("userDao")
public class UserDaoImpl implements IUserDao {
@Resource
protected SessionFactory sessionFactory;
 
 
public Session getSession() {
return sessionFactory.getCurrentSession();
}
 
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public boolean isExist(UserEntity user) {
Session session = this.getSession();
String hql = "from UserEntity where username =?

and password = ?

";

Query query = session.createQuery(hql);
query.setString(0, user.getUsername());
query.setString(1, user.getPassword());
if (query.list().size() >= 1) {
return true;
}
return false;
}
}
数据訪问层编写完了。我们測试看看方法能够用不咯
建一个UserDaoTest測试类,注意放在test资源包以下哈,代码例如以下,这里关于Junit+Spring測试使用注解引入单个和多个文件的差别留着后面讲,哈哈,是不是好多坑了。没事,等会一个一个填。我们先把项目弄好跑起来。最后来研究细节,这是我的学习方法,个人认为要是整了半天最后弄不好不就白干了。哈哈,不说多了,继续,
package com.phn.dao;
 
import javax.annotation.Resource;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
 
import com.phn.model.UserEntity;
 
@ContextConfiguration(locations = {"classpath:spring.xml","classpath:spring-hibernate.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
// defaultRollback=true不会改变数据库,false会改变数据库
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class UserDaoTest {
@Resource
private IUserDao userDao;
 
@Test
public void testIsExist() {
UserEntity user = new UserEntity();
user.setUsername("phn");
user.setPassword("123456");
boolean result = userDao.isExist(user);
System.out.println(result);
}
 
}
測试结果应该是对的吧。不正确的话赶紧从前面開始看看什么地方错了,改正一下继续。看我的測试结果
技术分享
技术分享
继续编写业务逻辑层(Service层)接口。新建IUserService接口。代码例如以下,
package com.phn.service;
 
import com.phn.model.UserEntity;
 
/**
* @author phn
*/
public interface IUserService {
public boolean isExist(UserEntity user);
}
继续编写业务逻辑层(Service层)实现类UserServiceImpl类,这里使用了@Transactional事务标签。不能少的哈。不多说,还是后面解释。

package com.phn.service.impl;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.phn.dao.IUserDao;
import com.phn.model.UserEntity;
import com.phn.service.IUserService;
 
/**
* @author phn
*/
@Transactional
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
 
@Override
public boolean isExist(UserEntity user) {
return userDao.isExist(user);
}
 
}
业务逻辑层也ok了。我们測试一下,相同建一个UserServiceTest測试类,代码例如以下。事实上和dao层的代码差点儿相同,就是一些细节须要注意一下的话,后面讲,继续
package com.phn.service;
 
 
import javax.annotation.Resource;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import com.phn.model.UserEntity;
 
@ContextConfiguration(locations= {"classpath:spring.xml","classpath:spring-hibernate.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceTest {
@Resource
private IUserService userService;
@Test
public void testIsExist(){
UserEntity user = new UserEntity();
user.setUsername("phn");
user.setPassword("123456");
boolean result = userService.isExist(user);
System.out.println(result);
}
 
}
相同測试结果应该是对的吧,不正确的话赶紧从前面開始看看什么地方错了,改正一下继续,我的測试结果例如以下
技术分享
技术分享
以下就開始控制层(Controller层或者又叫Action层)的编码,新建一个UserController类。代码例如以下
package com.phn.controller;
 
 
import java.util.HashMap;
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.phn.model.UserEntity;
import com.phn.service.IUserService;
 
/**
* @author phn
*/
@Controller
@RequestMapping("/user")
public class UserController{
@Resource
private IUserService userService;
@ResponseBody
@RequestMapping(value="/login", method = RequestMethod.POST)
public Map<String,Object> login( UserEntity user){
Map<String,Object> map = new HashMap<String,Object>();
System.out.println(user.toString());
boolean loginResult = userService.isExist(user);
map.put("loginResult", loginResult);
return map;
}
}
好啦,控制层写好了,以下測试,怎么測试呢。须要前台了,哈哈,ok,開始
看看我的项目的webapp目录
------------------------------------------------------------------
           技术分享  技术分享
-------------------------------------------------------------------
建一个jsp。弄个简单的Ajax提交。通过传输Json数据来进行交互,这里是不是有点高大上。哈哈。前后端分离的路啊。不扯这个了,博主自己还不是非常熟悉前后端分离的思想呢,慢慢来吧,少年。路还长着呢
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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="http://www.mamicode.com/<%=basePath%>">
 
<title>登录</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">
 
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/<%=basePath%>css/login.css">
<script type="text/javascript" src="http://www.mamicode.com/<%=basePath%>js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/<%=basePath%>js/md5.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/<%=basePath%>js/login.js"></script>
</head>
 
<body>
<div>
UserName:<input type="text" name="username" /> <br/>
PassWord:<input type="password" name="password" /><br/>
<input type="submit" id="loginBtn" value="Login" />
</div>
</body>
</html>
继续建一个js文件,login.js,代码例如以下。看到里面是不是进行了md5加密呀,这个是一个非常easy的东西,你们能够不用那个md5加密,相信这个操作你们还是会的吧,就是去掉hex_md5($("input[name=password]").val());外面的那个hex_md5()就ok了,继续没有了呢
$(function() {
$("#loginBtn").click(function() {
console.log("login");
var username = $("input[name=username]").val();
var password = hex_md5($("input[name=password]").val());
var user = {
"username" : username,
"password" : password
};
$.ajax({
type : "post",
dataType : "json",
data : user,
contentType : "application/x-www-form-urlencoded;charset=UTF-8",
url : "user/login",
// 同步async: false,(默认是true);
// 如上:false为同步,这种方法中的Ajax请求将整个浏览器锁死,
// 仅仅有test.jsp运行结束后,才干够运行其他操作。

async : false,
success : function(data) {
if (false == data.loginResult) {
alert("用户名或者密码错误,请又一次登录!

");

} else if (true == data.loginResult) {
alert("登录成功!");
var indexUrl = window.location.protocol+"//"+window.location.host+window.location.pathname+"html/index.html";
window.location = indexUrl;
}
},
error : function() {
alert("server发生问题。请尝试又一次登录!");
}
});
});
 
});
另一个登录成功的页面。index.html,代码例如以下
<!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">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
 
</head>
 
<body>
恭喜你。登录成功!
</body>
</html>

好了,把项目部署到tomcat上面去,试试看
----------------------------------------------------------------------------------
      技术分享
------------------------------------------------------------------------------------
输入phn,123456。看看測试结果,
--------------------------------------------------------------------------------------
     技术分享
-------------------------------------------------------------------------------------
奥,显示以下这个呢。是什么原因呢?嘿嘿。这是我用了md5加密,后台是直接将md5加密的字符串存在数据库中的。可是我前面在数据库直接使用的password是123456,所以在前台输入123456经过加密后的就不正确了。看以下,这是后台打印的东西,
-------------------------------------------------------------------------------------
     技术分享
-------------------------------------------------------------------------------------
相应数据库中的数据是这种
-------------------------------------------------------------------------------------
     技术分享
-------------------------------------------------------------------------------------
所以才会报错嘛,你看我试试输入username123和password123。结果就对了,例如以下
-------------------------------------------------------------------------------------       
    技术分享技术分享
-------------------------------------------------------------------------------------
       技术分享        技术分享
-------------------------------------------------------------------------------------
好啦,项目搭建就成功了。这里就到此为止了。睡觉。
剩下的坑就明天再填啦,记得再来哦。欢迎大家一起讨论哦
源代码在GitHub上
地址:https://github.com/panhainan/PHN



搭建SpringMVC+Hibernate4+Spring3+Ajax+Maven项目