首先需要准备SPRING和HIBERNATE 相应的JAR包,在ECLIPSE 中新建一个WEB工程,将解压的SPRING中的 \dist\modules 下的JAR和HIBERNATE 中的 hibernate3.jar 和 /lib/ 目录下的包全部拷入到工程的LIB目录,这时我们就可以真正开始编写SPRING+HIBERNATE应用了,首先我们建立一个SPRING的控制器,代码清单如下:
package com.spring25.action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.spring25.service.ILoginService;
/* 描述该bean为springMVC控制器,将由spring容器来创建和管理 */
@Controller
public class LoginController {
/* 自动装载 */
@Autowired
private ILoginService loginService;
/* 将该控制器的login方法与login.do 的请求进行关联,真正实现控制功能的是 @RequestMapping 注解 */
/*
* springMVC 控制请求处理的方式有如下几种:
* 1、直接在class头加 @RequestMapping("login.do"),能后在请求处理的方法头上加@RequestMapping,表明该请求由该控制器的该方法处理
* 2、在方法头上加 @RequestMapping("login.do"),当该请求到达时将会调用这个方法处理
* 3、通过参数:该控制处理的请求地址只有一个,但又想通过参数来调用不同的方法,这个时候就可以在类的头上加@RequestMapping("users.do")
* 处理方法头上加@RequestMapping(params="method=login"),这是一个分流规则,其中 method=login就是请求中带的参数
* 4、根据特殊的表单提交方法进行处理,如: @RequestMapping(params="method=login",method=RequestMethod.POST)
* 这样只能当提交方法是 POST 时 login 方法才会处理该请求
* */
@RequestMapping("/login.do")
public String login(String userName,String password,ModelMap model){
boolean succeed = this.getLoginService().login(userName,password);
model.addAttribute("userName", userName);
/* 返回一个String,该名称应为逻辑视图的名称 */
if(succeed){
return "error";
}
return "success";
}
}
HIBERNATE 持久类
package com.spring25.hibernate;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@SuppressWarnings("serial")
@Entity
@Table(name="users") //持久类与表的映射
public class Users implements Serializable{
private Integer uid;
private String userName;
private String password;
private Date birthday;
public Users(){
}
@Id
@GeneratedValue
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
@Column(name="username",nullable=true,length=20)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password= password;
}
@Column(name="password",nullable=true,length=20)
public String getPassword() {
return password;
}
@Column(name="birthday")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
接下来建立一个业务类
package com.spring25.service.impl;
import com.spring25.dao.ILoginDao;
import com.spring25.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
public class LoginService implements ILoginService {
@Autowired
private ILoginDao loginDao;
public boolean login(String userName,String password) {
return this.getLoginDao().login(userName,password);
}
}
数据处理层代码
package com.spring25.dao.impl;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.spring25.dao.ILoginDao;
public class LoginDaoImpl extends HibernateDaoSupport implements ILoginDao{
public boolean login(String userName,String password) {
Query query = this.getSession(true).createQuery("from Users where userName=:userName and password=:password");
query.setParameter("userName", userName);
query.setparameter("password",password);
if(query.list().size() > 0){
return true;
}
return false;
}
}
接下来我们需要添加SPRING配置文件,其中applicationContext.xml为业务层配置,spring25annmvc-servlet.xml 声明SPRING MVC 相应配置
spring25annmvc-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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- 在web.xml 中配置了 spring25annmvc 的模块,根据spring的规范,需要在 spring25annmvc-servlet.xml 定义springMVC的具体配置 --> <!-- 对 action 包中的所有 Controller 类进行扫描,以完成自动装载功能 --> <context:component-scan base-package="com.spring25.action"></context:component-scan> <!-- 启动springMVC的注解驱动 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> <!-- 模型视图的解析 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:suffix=".jsp"></bean> </beans>
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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- JDBC 数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"></property> <property name="url" value="jdbc:microsoft:sqlserver://localhost:1433;databaseName=test"></property> <property name="username" value="sa"></property> <property name="password" value="sa"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">false</prop> </props> </property> <property name="annotatedClasses"> <list> <value>com.spring25.hibernate.Users</value> </list> </property> </bean> <!-- hibernate 模板,用来代替 sessionFactory --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> <property name="cacheQueries" value="true"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="dataSource" ref="dataSource"/> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 声明式事务管理 --> <aop:config> <aop:pointcut id="servicePointcut" expression="execution(* com.spring25.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/> </aop:config> <!--事务控制--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="login*" read-only="true"/> </tx:attributes> </tx:advice> <bean id="loginDao" class="com.spring25.dao.impl.LoginDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"/> </bean> <bean id="loginService" class="com.spring25.service.impl.LoginService"> <property name="loginDao" ref="loginDao"/> </bean> </beans>
最后配置web.xml 和建立相应 jsp 文件,web.xml 代码如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- spring 相关配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- spring 启动监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 处理请求的 servlet,它将加载 WEB-INF/spring25annmvc-servlet.xml下的配置文件,以启动springMVC模块 --> <servlet> <servlet-name>spring25annmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring25annmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
login.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login</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> <form action="login.do"> userName:<input type="text" name="userName" size=15> <br /> passWord:<input type="password" name="password" size="15"> <br /> <input type="submit" value="login"> </form> </body> </html>
登录成功页面 success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>success</title> </head> <body> 欢迎你: ${userName} </body> </html>
登录失败页面 error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>error</title>
</head>
<body>
登录失败!
<a href="index.jsp" mce_href="index.jsp">返回</a>
</body>
</html>
好了,以上就是整个编写的过程,是不是很简单呢! 经过运行后完全正确
spring2.5基于注解的 spring mvc
参考文档:http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/
本例程源码可到 : http://download.csdn.net/source/1301364 下载