1、概述
本文旨在搭建Spring+Spring MVC+Hibernate开发框架,通过一个简单的demo讲解Spring MVC的相关配置文件,以及通过注解方式实现简单功能。
开发框架:Spring + Spring MVC+Hibernate(Spring所用的版本为3.0.5)。
数据库:MySQL(数据库名称test,demo工程所用的表名为t_test)。
2、开发框架搭建
2.1 创建工程
在Eclipse的Java EE版本或MyEclipse中创建一个Dynamic Web Project。
![这个是我项目结构图,jar自己在结构图中寻找]
2.3 配置文件
2.3.1 配置web.xml
在web.xml中需要配置Spring的配置文件(applicationContext.xml)和Spring MVC配置文件(spring-mvc.xml),配置指定所有的请求都由Spring的DispatcherServlet类进行处理。
web.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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>json_test</display-name>
<!-- 加载所有的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-*.xml</param-value>
</context-param>
<!-- 配置Spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置SpringMVC -->
<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>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置字符集 -->
<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>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.3.2 配置spring的配置文件
Spring的配置文件applicationContext.xml文件中主要配置对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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://10.16.124.70:3306/papertc?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></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">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>cxn.web.test.model.User</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>
2.3.3 配置Spring MVC配置文件
Spring MVC的配置文件spring-mvc.xml中的配置信息,该文件的参考配置如下:
<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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="cxn.web.test"
use-default-filters="false" >
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 开启注解 -->
<mvc:annotation-driven />
<!-- 静态资源(js/image)的访问
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:default-servlet-handler/>-->
<!-- 定义视图解析器 -->
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
</bean>
</beans>
2.4 创建数据库和表
创建test数据库和t_test表的SQL语句如下:
CREATE TABLE t_test (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30) DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY (id)
)
3、实例代码
3.1Model层
package cxn.web.test.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;
@Entity
@Table(name="t_test")
public class User {
private int id;
private String name;
private Integer age;
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "AGE")
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3.2 DAO层
接口类IUserDao的代码如下:
package cxn.web.test.dao;
import java.util.List;
import cxn.web.test.model.User;
public interface IUserDao {
public void addUser(User user);
public List<User> getAllUser();
public boolean delUser(String id);
public User getUser(String id);
public boolean updateUser(User user);
}
实现类UserDaoImpl类的代码如下:
package cxn.web.test.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import cxn.web.test.model.User;
@Repository("iUserDao")
public class UserDaoImpl implements IUserDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addUser(User user) {//添加用户
sessionFactory.getCurrentSession().save(user);
}
@Override
public List<User> getAllUser() {//查找所有用户信息
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
@Override
public boolean delUser(String id) {//删除用户
String hql = "delete User u where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (query.executeUpdate() > 0);
}
@Override
public User getUser(String id) {//根据id得到单个用户
String hql = "from User u where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);//此时使用的是hql语句
query.setString(0, id);
return (User) query.uniqueResult();
}
@Override
public boolean updateUser(User user) {
// TODO Auto-generated method stub
return false;
}
}
3.3 业务逻辑层
接口类IUserService的代码如下:
package cxn.web.test.service;
import java.util.List;
import cxn.web.test.model.User;
public interface IUserService {
public void addUser(User user);
public List<User> getAllUser();
public boolean delUser(String id);
public User getUser(String id);
public boolean updateUser(User user);
}
实现类UserServiceImpl类的代码如下:
package cxn.web.test.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cxn.web.test.dao.IUserDao;
import cxn.web.test.model.User;
@Service("iUserService")
public class UserServiceImpl implements IUserService {
@Resource(name ="iUserDao")
private IUserDao userDao;
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
@Override
public List<User> getAllUser() {
return userDao.getAllUser();
}
@Override
public boolean delUser(String id) {
return userDao.delUser(id);
}
@Override
public User getUser(String id) {
return userDao.getUser(id);
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
}
3.4 控制层
控制类HelloControllor类的代码如下:
package cxn.web.test.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = "user")
public class UserController {
/* @Resource(name="iUserService")// 获取spring配置文件中bean的id为userManager的,并注入
private IUserService iUserService; */
@RequestMapping(value="index")
public ModelAndView list(){
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
return mv;
}
}
Index页面代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="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>Insert title here</title>
</head>
<body>
用户名:<input type="text" >
</body>
</html>
4、测试
测试时可以通过访问http://localhost:8080/bspringandhibtest/user/index
5、页面返回:
6、源码:
http://download.csdn.net/detail/qq394829044/9580930