1,web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>chauvet</display-name> <!-- 工程的根名称 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>chauvet.root</param-value> </context-param> <!-- loj4j的配置文件路径 和log4j的监听器--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- 设置Spring容器加载配置文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:/spring/applicationContext.xml ,classpath:/spring/spring-connection.xml <!-- ,classpath:/spring/spring-hibernate.xml ,classpath:/spring/spring-c3p0.xml--> </param-value> </context-param> <!-- spring IOC容器的配置文件位置和IOC容器的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring mvc的核心转发器 和转发的规则 --> <servlet> <servlet-name>chauvet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- 默认/WEB-INF/[servlet名字]-servlet.xml加载上下文, 如果配置了contextConfigLocation参数,将使用classpath:/spring/chauvet-servlet.xml加载上下文 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/chauvet-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>chauvet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 全局过滤器,主要用来判断登录、鉴权、编码转换,只过滤 /的动态资源 --> <filter> <filter-name>allFilter</filter-name> <filter-class>com.chauvet.utils.AllFilter</filter-class> </filter> <filter-mapping> <filter-name>allFilter</filter-name> <!-- 和spring核心转发器过滤规则相同 --> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置session超时时间 --> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
2.applicationContext.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" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"> <!-- bean管理 --> <!-- service --> <!-- dao --> <!-- util --> </beans>
3.chauvet-servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- spring核心配置 --> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) --> <context:component-scan base-package="com.chauvet" /> <!-- 启用注解 --> <mvc:annotation-driven /> <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 --> <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- Configures Handler Interceptors --> <mvc:interceptors> <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <!-- 允许对静态资源文件的直接访问 --> <mvc:default-servlet-handler /> <mvc:resources mapping="/resources/**" location="/resources/" /> <!-- Saves a locale change using a cookie --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <!-- Application Message Bundle --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages/messages" /> <property name="cacheSeconds" value="0" /> </bean> <!-- Resolves view names to protected .jsp resources within the /WEB-INF/chauvet directory --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/chauvet/"/> <property name="suffix" value=".jsp"/> </bean>
</beans>
4.spring-connection.xml(通过注入的方式为SessionFactory注入hibernate的配置信息,从而省去hibernate配置文件)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:/jdbc.properties" /> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${jdbc.driverClassName}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.user}"></property> <property name="password" value="${jdbc.pass}"></property> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.chauvet.po</value> </list> </property> </bean> <!-- 配置一个事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置事务,使用代理的方式 --> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop> <prop key="del*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> </beans>
5.Controller
package com.chauvet.controller; import java.io.IOException; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/login") public class LoginController extends BaseController { /** * 跳转到登录页面 * @param request * @param response * @return * @throws IOException */ @RequestMapping(value = "/gotoLogin", method = RequestMethod.GET) public ModelAndView gotoLogin(HttpServletRequest request,HttpServletResponse response){ return new ModelAndView("login/gotoLogin"); } }
6.index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head></head>
<body>
<script type="text/javascript">document.location.href='login/gotoLogin';</script>
</body>
</html>
7.BaseDao.java
package com.chauvet.dao.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class BaseDao { /** * log4j日志记录 */ private Logger log = Logger.getLogger(this.getClass()); @Resource private SessionFactory sessionFactory;
public Session getSession(){ // return sessionFactory.openSession(); // 需要自己关闭session /*** * getCurrentSession()的两个特性: * 1、在没有session的情况下不会自动创建一个 * 2、会自动关闭session */ return sessionFactory.getCurrentSession(); } /*** * 保存 * @param obj */ public void save(Object obj){ getSession().save(obj); } /** * 根据表名查出这个表下的所有记录 * @param <T> 泛型 * @param tableName 表名 * @return List<T> */ public <T> List<T> findAll(String tableName) { log.debug("findAll:"+tableName); String hql = "from " + tableName + " "; return findByHql(hql); } }
8.PO User.java
package com.chauvet.po; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="user") public class User{ private String id; //主键,自动生成UUID private String name;//名字 private int sex;//性别 private int age;//年龄 private Date registerTime;//注册时间 private Date createTime;//创建时间 @Id @GenericGenerator(name="systemUUID",strategy="uuid") @GeneratedValue(generator="systemUUID") @Column(name = "id", insertable = true, updatable = true, nullable = false,length = 32) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name="name",length=32) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="sex") public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } @Column(name="age") public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Temporal(TemporalType.TIMESTAMP) @Column(name="createTime") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Temporal(TemporalType.TIMESTAMP) @Column(name="registerTime") public Date getRegisterTime() { return registerTime; } public void setRegisterTime(Date registerTime) { this.registerTime = registerTime; } }