搭建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.ConsoleAppenderlog4j.appender.A1.Target=System.outlog4j.appender.A1.layout=org.apache.log4j.PatternLayoutlog4j.appender.A1.layout.ConversionPattern=[%c]%m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=sshf.loglog4j.appender.R.MaxFileSize=10MBlog4j.appender.R.Threshold=ALLlog4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.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\u7F6Ehibernate.dialect=org.hibernate.dialect.MySQLDialectdriverClassName=com.mysql.jdbc.DrivervalidationQuery=SELECT 1jdbc_url=jdbc:mysql://localhost:3306/phn?useUnicode=true&characterEncoding=utf-8jdbc_username=rootjdbc_password=123456 hibernate.hbm2ddl.auto=updatehibernate.show_sql=truehibernate.format_sql=false sessionInfoName=sessionInfo uploadFieldName=filedatauploadFileMaxSize=20971520uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,miduploadDirectory=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,一樣註釋也都比較詳細了,你們仔細看是能夠看懂的,
    
    
    
    
    
<!-- 這裏是針對我寫的判斷用戶是否存在數據庫的方法的事務,若是不配置的話就會出現no session異常 -->
<?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.xsdhttp://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" />  <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")@Entitypublic 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)@Transactionalpublic 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上
相關文章
相關標籤/搜索