码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-16 06:19:15      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:springmvc   springmvc+hibernate4   springmvc+hibe..+mav   spring3+mvc+hibernat   spring3mvc+hibernate   

首先新建一个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="${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="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="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="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>
到这里配置的已经差不多了,接下来开始编写服务器端的代码。
记得先建立一个数据库哈,这个不要忘记了,我建的是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="<%=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="<%=basePath%>css/login.css">
<script type="text/javascript" src="<%=basePath%>js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="<%=basePath%>js/md5.js"></script>
<script type="text/javascript" src="<%=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加密呀,这个是一个很简单的东西,你们可以不用那个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("服务器发生故障,请尝试重新登录!");
}
});
});
 
});
还有一个登录成功的页面,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加密的字符串存在数据库中的,但是我前面在数据库直接使用的密码是123456,所以在前台输入123456经过加密后的就不对了,看下面,这是后台打印的东西,
-------------------------------------------------------------------------------------
     技术分享
-------------------------------------------------------------------------------------
对应数据库中的数据是这样的
-------------------------------------------------------------------------------------
     技术分享
-------------------------------------------------------------------------------------
所以才会报错嘛,你看我试试输入用户名123和密码123,结果就对了,如下
-------------------------------------------------------------------------------------       
    技术分享技术分享
-------------------------------------------------------------------------------------
       技术分享        技术分享
-------------------------------------------------------------------------------------
好啦,项目搭建就成功了,这里就到此为止了,睡觉!
剩下的坑就明天再填啦,记得再来哦,欢迎大家一起讨论哦
源码在GitHub上



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

标签:springmvc   springmvc+hibernate4   springmvc+hibe..+mav   spring3+mvc+hibernat   spring3mvc+hibernate   

原文地址:http://blog.csdn.net/yannanying/article/details/44288179

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