使用Spring 2.5 和 Hibernate 3.2 开发MVC Web程序(基于annotation特性)

使用Spring 2.5 和 Hibernate 3.2 开发MVC Web程序(基于annotation特性)

 

Spring 和 Hibernate 都支持annotation开发应用程序,无疑减少呢很多XML配置,使程序看起来更”干净”,下面我们以一个简单的例子来说明:

程序的开发环境:eclipse3.2.2+ WTP + tomcat(推荐)

首先我们建一个动态的Web项目

修改WEB-INF/web.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="ascweb" version="2.4"

      xmlns="http://java.sun.com/xml/ns/j2ee"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

     

      <display-name>ascweb</display-name>

 

      <!-- 载入Spring配置文件 -->

      <context-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>/WEB-INF/applicationContext.xml</param-value><!-- 自动载入的spring配置 -->

      </context-param>

      <listener>

      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

 

      <!-- 字符编码转换 -->

      <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>

      </filter>

      <filter-mapping>

           <filter-name>encodingFilter</filter-name>

           <url-pattern>*.do</url-pattern>

      </filter-mapping>

      <!-- Spring MVC 的Servlet -->

      <servlet>

           <servlet-name>ascweb</servlet-name>

           <servlet-class>

                 org.springframework.web.servlet.DispatcherServlet

           </servlet-class>

           <load-on-startup>1</load-on-startup>

      </servlet>

 

      <servlet-mapping>

           <servlet-name>ascweb</servlet-name>

           <url-pattern>*.do</url-pattern>

      </servlet-mapping>

 

      <welcome-file-list>

           <welcome-file>index.htm</welcome-file>

           <welcome-file>index.jsp</welcome-file>

           <welcome-file>index.do</welcome-file>

      </welcome-file-list>

</web-app>

 

建立好这个文件之后,我们在WEB-INF目录下面建一个ascweb-servlet.xml文件,其实这个文件的命名就是Web.xml中servlet-name的名字加-servlet.xml.其文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

 

<beans>

<!-- 定义Spring MVC 的模板文件 -->

      <bean id="viewResolver"

      class="org.springframework.web.servlet.view.InternalResourceViewResolver">

           <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>     <!-- 支持JSTL -->

           <property name="prefix" value="WEB-INF/views/" />     <!-- 模板的路径 -->

           <property name="suffix" value=".jsp" />                 <!-- 模板文件的后缀-->

      </bean>

 

      <!-- 依赖注入到HelloController这个类 -->

      <bean id="helloController" class="com.asc.web.ctl.HelloController">

           <property name="viewName">  <!-- 设定viewName属性的值为hello -->

                 <value>hello</value>

           </property>

           <property name="userDao">     <!-- 设置属性userDao为Hibernate的Dao对象 -->

                 <ref bean="userDAOProxy" /> <!-- 注入一个bean(定义在Hibernate的配置文件里) -->

           </property>

      </bean>

</beans>

 

然后我们建立一个/WEB-INF/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"

      xsi:schemaLocation="http://www.springframework.org/schema/beans

      http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

      <-- 数据源配置 -->

      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

           <property name="driverClassName">

                 <value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value>

            </property>

           <property name="url">

                 <value>jdbc:sqlserver://192.168.1.21:2433;DatabaseName=expert</value>

           </property>

           <property name="username">

                 <value>sa</value>

           </property>

           <property name="password">

                 <value>oilchem2006</value>

           </property>

      </bean>

     

<!-- hibernate3 session Bean-->

      <bean id="sessionFactory"

      class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

           <property name="dataSource"> <!-- 注入数据源 -->

                 <ref local="dataSource" />

           </property>

           <property name="annotatedClasses">    <!-- 需要加载的Hibernate实体类(不需要hbm.xml了) -->

                 <list>

                      <value> com.asc.dao.User</value>

                 </list>

           </property>

           <property name="hibernateProperties">

                 <props>

                      <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>

                      <prop key="hibernate.show_sql">true</prop>

                 </props>

           </property>

      </bean>

 

      <!-- 事务管理 -->

      <bean id="transactionManager"

           class="org.springframework.orm.hibernate3.HibernateTransactionManager">

           <property name="sessionFactory">

                 <ref local="sessionFactory" />

           </property>

      </bean>

 

      <!-- UserDAO bean-->

      <bean id="userDAO" class=" com.asc.dao.UserDAO">

           <property name="sessionFactory">

                 <ref local="sessionFactory" />

           </property>

      </bean>

 

      <!-- 带事务处理的userDao 代理 -->

      <bean id="userDAOProxy"

      class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

           <property name="transactionManager">

                 <ref bean="transactionManager" />

           </property>

           <property name="target">

                 <ref local="userDAO" />

           </property>

           <property name="transactionAttributes">

                 <props>

                      <prop key="insert*">PROPAGATION_REQUIRED</prop>

                      <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>

                 </props>

           </property>

      </bean>

</beans>

 

然后我们开始写hibernate的代码,很简单

实体类User.java:

package com.asc.dao;

import javax.persistence.*;

import java.io.Serializable;

 

//指定表格的名称,注解方式

@SuppressWarnings("serial")

@Entity

@Table(name = "users2")

public class User implements Serializable {

 

      public Integer id;

 

      public String username;

 

      public String password;

     

//主键,注解方式

      @Id

      @GeneratedValue(strategy = GenerationType.AUTO)

      public Integer getId() {

           return id;

      }

 

      public void setId(Integer id) {

           this.id = id;

      }

 

      public String getPassword() {

           return password;

      }

 

      public void setPassword(String password) {

           this.password = password;

      }

 

      public String getUsername() {

           return username;

      }

 

      public void setUsername(String username) {

           this.username = username;

      }

}

 

然后我们新建一个接口IUserDAO:

package com.asc.dao;

import java.util.List;

 

public interface IUserDAO {

 

      public abstract void insertUser(User user);

      public abstract List<User> selectUser();

 

}

 

我们再建一个接口的实现UserDAO:

package com.asc.dao;

import java.util.List;

 

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

 

public class UserDAO extends HibernateDaoSupport implements IUserDAO{

      //插入数据

      public void insertUser(User user) {

           getHibernateTemplate().saveOrUpdate(user);

      }

     

//查询数据

      @SuppressWarnings("unchecked")

      public List<User> selectUser(){

           String sql="From User Order By id";

           List<User> findByNamedQuery = getHibernateTemplate().find(sql);

           return findByNamedQuery;

      }

}

 

现在我们的Hibernate部分就全部写好了.简单吧,发现什么了吗,没有讨厌的hbm.xml文件呢,那些配置写道User这个实体类里了,这个是Java 5之后才有的功能,叫annotation(相当于元数据).

 

现在我们开始写MVC层

建立一个文件:

package com.asc.web.ctl;

 

import java.util.ArrayList;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import com.asc.dao.IUserDAO;

import com.asc.dao.User;

 

//还是注解方式,不用继承任何类或者实现任何接口

@Controller

public class HelloController{

      private String viewName;

      private IUserDAO userDao;

     

//在ascweb-servlet.xml里配置的,该属性已经被注入userDAOProxy接口了

      public IUserDAO getUserDao() {

           return userDao;

      }

      public void setUserDao(IUserDAO userDao) {

           this.userDao = userDao;

      }

      public String getViewName() {

           return viewName;

      }

      public void setViewName(String viewName) {

           this.viewName = viewName;

      }

     

//注解其url映射

      @SuppressWarnings("unchecked")

      @RequestMapping("/hello.do")

      public String index(ModelMap map,HttpServletRequest request,HttpServletResponse response) {

           // map是用来设置View层数据的

           map.put("a1", "Spring真好用");

           request.getSession().setAttribute("a2", "测试Session");

List<User> list2 = userDao.selectUser();

           map.put("a3", list2);

           return this.viewName;  //该属性被注入值hello了,就是渲染视图hello.jsp

      }

}

现在我们可以做最后一部了.写View层,在WEB-INF/views里新建一个hello.jsp(还记得我们在配置Spring MVC层中配置view的路径是WEB-INF/views,后缀是jsp吗)

<%@ page language="java" contentType="text/html; charset=utf-8"

      pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="/WEB-INF/c.tld"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>在此处插入标题</title>

</head>

<body>

测试: ${a1} ${a2}

<br />

<c:forEach var="list" items="${a3}">

      <c:out value="${list.id}"></c:out>

      <c:if test="${list.id % 2 == 0}">

           <a href="#" style="color:red;border:1px #ececec solid"><c:out

                 value="${list.username}"></c:out></a>

      </c:if>

      <c:if test="${list.id % 2 != 0}">

           <a href="#" style="color:green;border:1px #ececec solid"><c:out

                 value="${list.username}"></c:out></a>

      </c:if>

      <c:out value="${list.password}"></c:out>

      <br />

</c:forEach>

</body>

</html>

我们再加入log4j.properties到src目录,配置日志显示.方便调试Ok,运行一下.

你可能感兴趣的:(annotation)