自己花了兩天時間去網上查找了相關資料,搭建的一個綜合springmvc、hibernate和spring三種框架類型的環境,進行了一些簡單的實例實踐,下面貼出搭建步驟和代碼,方便大家交流學習,也方便日後自己回來查閱
1.創建一個java網站,創建的網站類型爲Dynamic web
勾選Generate web.xml,生成web.xml文件,點Finish
2.導入相關jar包,把jar包放到WEB-INF的lib文件夾下,我這裏導入了34個相關包,附上圖給大家
3.下面是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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvc_spring3_hibernate4</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 加載所有的spring配置文件 -->
<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>
<!-- 配置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*:config/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>
<!--配置session控制器開關 -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.在與web.xml配置的相應位置建立相關的xml文件,下面是根據我的web配置,我創建的相關xml配置文件的位置截圖
5.配置spring文件,下面貼出spring-commom.xml的代碼,代碼有註釋,不懂的可以看註釋
<?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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!--配置數據源 ,可將property value放置在配置文件中 -->
<context:property-placeholder location="classpath:/config/scottDB.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${scott.jdbc.driverClassName}"></property>
<property name="url" value="${scott.jdbc.url}"></property>
<property name="username" value="${scott.jdbc.username}"></property>
<property name="password" value="${scott.jdbc.password}"></property>
</bean>
<!-- 配置hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.firstest.entity.SpringUser</value>
</list>
</property>
</bean>
<!-- 事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事務代理攔截器 -->
<bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<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>
6.spring-mvc配置文件的代碼
<?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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!--註解掃描的包 ,bean實例化使用註解@Component -->
<context:component-scan base-package="com.firstest"></context:component-scan>
<!--開啓註解 -->
<mvc:annotation-driven/>
<!--攔截以Service結尾的類,實現事務代理 -->
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>transactionBase</value>
</list>
</property>
</bean>
<!-- 靜態資源(js/image)訪問 -->
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<!-- 視圖解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
7.scottDB.properties配置文件,用於存放數據庫的連接信息,這裏相信大家應該都能看懂的,看不懂的自己上網查閱一下相關資料,上面有許多介紹properties配置文件的內容
#oracle 11g
scott.jdbc.driverClassName = oracle.jdbc.driver.OracleDriver
scott.jdbc.url = jdbc:oracle:thin:@192.168.0.134:1521:THUND
scott.jdbc.username = scott
scott.jdbc.password = tiger
#hibernatep配置
hibernate.show_sql = true
hibernate.format_sql = true
8.到這裏,基本上的輪廓已經出來了,下面就是javabean的創建,以及dao層,service層的編寫,還有後臺的controller後臺實現代碼的編寫,這裏最需要注意的是dao層中接口的實現類UserManage以及service層的實現類UserManageService這兩個類,因爲剛剛前面所說的報錯,基本上都是出現在這兩個類中間,下面我一 一貼上代碼。
Javabean代碼
package com.firstest.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="SPRINGMVC_USERS",schema="SCOTT")
public class SpringUser implements Serializable{
private static final long serialVersionUID = -7010217787841007904L;
private String userId; //用戶id
private String userName; //用戶名
private String phone; //手機號碼
private String age; //年齡
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid",strategy="uuid")
@Column(name="USERID")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Column(name="USERNAME")
public String getuserName() {
return userName;
}
public void setuserName(String userName) {
this.userName = userName;
}
@Column(name="PHONE")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name="AGE")
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
dao層的接口類和實現類
package com.firstest.dao;
import java.util.List;
import com.firstest.entity.SpringUser;
public interface IUserManage {
public List<SpringUser> getSpringUser();
public void addSpringUser(SpringUser springUser);
}
package com.firstest.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.firstest.dao.IUserManage;
import com.firstest.entity.SpringUser;
@Repository
public class UserManage implements IUserManage{
@Resource
@Autowired
private SessionFactory sessionFactory;
/* public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}*/
@Override
public List<SpringUser> getSpringUser(){
String hql = "from SpringUser";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
List<SpringUser> list = query.list();
return list;
}
@Override
public void addSpringUser(SpringUser springUser){
sessionFactory.getCurrentSession().save(springUser);
}
}
service層的接口類和實現類
package com.firstest.service;
import java.util.List;
import com.firstest.entity.SpringUser;
public interface IUserManageService {
public List<SpringUser> getSpringUser();
public void addSpringUser(SpringUser springUser);
}
package com.firstest.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.firstest.dao.IUserManage;
import com.firstest.entity.SpringUser;
import com.firstest.service.IUserManageService;
@Service
public class UserManageService implements IUserManageService{
@Resource
@Autowired
private IUserManage iUserManage;
/**
* 獲取用戶信息
*/
@Override
public List<SpringUser> getSpringUser(){
return iUserManage.getSpringUser();
}
/**
* 新增用戶
*/
@Override
public void addSpringUser(SpringUser springUser) {
iUserManage.addSpringUser(springUser);
}
}
9.controller後臺實現的代碼
package com.firstest.controller;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletException;
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.RequestParam;
import com.firstest.entity.SpringUser;
import com.firstest.service.IUserManageService;
@Controller
@RequestMapping("/user")
public class UserManageController {
@Resource(name="iUserManageService")
private IUserManageService iUserManageService;
/**
* 查詢所有用戶
* @param request
* @param response
* @return /pages/show
*/
@RequestMapping(value="/getSpringUser")
public String getSpringUser(HttpServletRequest request,HttpServletResponse response){
List<SpringUser> list = iUserManageService.getSpringUser();
request.setAttribute("list", list);
return "/pages/show";
}
/**
* 添加用戶
* @param springUser
* @param request
* @param response
* @return /user/getSpringUser
*/
@RequestMapping(value="/addSpringUser")
public String addSpringUser(SpringUser springUser,
HttpServletRequest request,HttpServletResponse response){
iUserManageService.addSpringUser(springUser);
return "redirect:/user/getSpringUser";
}
}
10.最後就是頁面展現啦,在spring-mvc.xml配置文件中,我們已經配置了靜態資源的位置,所以,我們只需要按照上面的路徑建立pages文件夾,在裏面寫jsp頁面就可以了,下面是頁面的代碼。
addUser.jsp
<%@ page language="Java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>
<script type="text/javascript">
function adduser() {
var form = document.forms[0];
form.action = "/springmvc_spring3_hibernate4/user/addSpringUser";
form.mothod = "POST";
form.submit();
}
</script>
</head>
<body>
<h2 align="center">添加用戶</h2>
<form name="forms_user" action="">
<table width="320" height="180" align="center" border="0">
<tr>
<td>用戶名:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>手機號碼:</td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>年齡:</td>
<td><input type="text" name="age"></td>
</tr>
<tr align="center"><td colspan="2"><input type="button" value="提交" onclick="adduser()"></input></td></tr>
</table>
</form>
</body>
</html>
index.jsp
<%@ page language="Java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>
</head>
<body>
<a href="<%=basePath%>user/getSpringUser">查看已註冊用戶</a>
<a href="<%=basePath%>pages/addUser.jsp">添加用戶</a>
</body>
</html>
show.jsp
<%@ page language="Java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>
</head>
<body>
<h2 align="center">註冊用戶信息</h2>
<form name="form">
<table width="320" align="center" border="0">
<tr>
<td>用戶名</td>
<td>年齡</td>
<td>手機號碼</td>
</tr>
<c:forEach var="list" items="${list}">
<tr>
<td>${list.userName }</td>
<td>${list.age }</td>
<td>${list.phone }</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
第一次寫博客,有點小激動,寫的不好還請大家多多包涵,有錯誤請給我留言。spring擁有強大的註解功能,這項功能方便了大家進行代碼的編寫,所以大家可以多多使用註解。這一個實例我實現的功能比較簡單,只是實現了增和查這兩個功能,大家有興趣的同學可以繼續往下寫,可以補充改跟刪這兩個功能,由於之前在網上有查閱過相關的資料,下面給大家貼出一個鏈接,大家可以繼續看看別的大神的文章:
http://blog.csdn.net/bjyfb/article/details/8998267
http://blog.csdn.net/bjyfb/article/details/8998439
下面也附上我的工程文件下載鏈接:
http://download.csdn.net/detail/tianxiezuomaikong/9675156