搭建SpringMVC+Hibernate4+Spring3+Ajax+Maven项目
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFubmFueWluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
<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.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
#\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
<?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>
<?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>
<?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>
<?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>
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
+ " ]";
}
}
package com.phn.dao;
import com.phn.model.UserEntity;
/**
* @author phn
*/
public interface IUserDao {
public boolean isExist(UserEntity user);
}
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;
}
}
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);
}
}
package com.phn.service;
import com.phn.model.UserEntity;
/**
* @author phn
*/
public interface IUserService {
public boolean isExist(UserEntity user);
}
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);
}
}
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);
}
}
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFubmFueWluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
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;
}
}
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFubmFueWluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
<%@ 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>
$(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发生问题。请尝试又一次登录!");
}
});
});
});
<!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>
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFubmFueWluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
搭建SpringMVC+Hibernate4+Spring3+Ajax+Maven项目的更多相关文章
- maven项目快速搭建SSM框架(一)创建maven项目,SSM框架整合,Spring+Springmvc+Mybatis
首先了解服务器开发的三层架构,分配相应的任务,这样就能明确目标,根据相应的需求去编写相应的操作. 服务器开发,大致分为三层,分别是: 表现层 业务层 持久层 我们用到的框架分别是Spring+Spri ...
- maven学习日记(三)-------开发环境搭建(springmvc+hibernate4)各种maven错误汇总
1.maven编码 gbk 的不可映射字符 解决这个问题的思路: 在maven的编译插件中声明正确的字符集编码编码——编译使用的字符集编码与代码文件使用的字符集编码一致!! 安装系统之后,一般中文系统 ...
- spring + springMVC + spring Data + jpa + maven 项目框架搭建
首先看一下项目结构: 所用到的jar(pom.xml): <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:x ...
- 搭建一个ssm框架的maven项目需要配置的文件
单独功能需要的配置文件: 1,mybatis配置文件 mybatis-config.xml2,spring配置文件 spring-context.xml ......3,we ...
- Springmvc 如何配置一个MAVEN项目,eclipse视图详解
1,首先主页创建一个maven project项目, 2-3,创建完成会报错因为缺少WEB-INF文件右键点击选取,会自动创建web.xml文件 4 ,调试版本 因为默认创建的maven版本不支持,所 ...
- Maven搭建SpringMVC+Hibernate项目详解(转)
前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...
- Maven搭建SpringMVC+Hibernate项目详解 【转】
前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...
- Maven搭建SpringMVC+Mybatis项目详解
前言 最近比较闲,复习搭建一下项目,这次主要使用spring+SpringMVC+Mybatis.项目持久层使用Mybatis3,控制层使用SpringMVC4.1,使用Spring4.1管理控制器, ...
- Maven搭建SpringMVC+Hibernate项目详解
前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...
随机推荐
- 出租车(taxi)
出租车(taxi) 题目描述 Bessie在农场上为其他奶牛提供出租车服务.这些奶牛已经在沿着长度为M(1<= M <= 1,000,000,000)的栅栏上不同的地点聚集等候.不幸的是, ...
- C语言中 单引号与双引号的区别
在C语言中,字符用单引号,字符串用双引号.在c1='a';中,'a'是字符常量,必须用单引号."a"表示字符串,包含两个字符,一个是'a',一个是'\0'. 用数组来存储字符串. ...
- Python(2)-- 运算符
1. 算术运算符 常规: 加(+).减(-).乘(*).除(/).取模(%) 此外: 幂(**):返回x的y次幂, eg: 2**3---返回 2 的 5 次幂,输出结果32 取整除(//):返回商的 ...
- HDU3001 Travelling
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission( ...
- 鼠标放在预览图a.gif上,旁边有放大图出现
原文发布时间为:2009-04-23 -- 来源于本人的百度文章 [由搬家工具导入] <html><script type="text/javascript"&g ...
- 【shell入门】Shell用法
参考:http://www.cnblogs.com/Lynn-Zhang/p/5758287.html 1.sh/bash/csh/Tcsh/ksh/pdksh等shell的区别 sh(全称 Bour ...
- OpenMP参考链接
做个笔记. http://www.cnblogs.com/China3S/p/3500507.html
- ie8实现无刷新文件上传
ie8由于无法使用FormData,想要无刷新上传文件就显得比较麻烦.这里推荐使用jQuery-File-Upload插件,它能够很方便的解决ie8无刷新文件上传问题.(最低兼容到ie6) jQuer ...
- codevs——1044 拦截导弹(序列DP)
1999年NOIP全国联赛提高组 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题解 题目描述 Description 某国为了防御敌国的导弹袭击 ...
- php类中静态变量与常亮的区别
在效率上:常量编译过程比静态变量快的多. 代码: <?php error_reporting(E_ALL); class A { const c = 9; public static $b = ...