Eclipse完整工程如下 Jar包如下
CSDN下载地址:https://download.csdn.net/download/zhutouaizhuwxd/9721062
其中,整个工程主要可以分为四个部分(个人见解,怎么容易理解怎么来)
第一部分:配置文件
1、applicationContentx.xml:配置Spring容器相关内容.
1.1 hibernate.cfg.xml:
1.2 jdbc.properties:
2、Springmvc.xml:配置Springmvc相关内容
3、web.xml:配置整个工程相关内容
第二部分:(映射数据库)
1、实体类Entities
2、*.hbm.xml
第三部分:MVC:
1、控制层Controller(C)
2、业务逻辑层Service、Dao(M)
3、视图层index.jsp(V)
第四部分:JAR包
1、Spring3.X
2、Hibernate3.X
3、连接SqlServer2008数据库:sqljdbc4.jar(其他数据库使用对应的jar包即可)
4、数据库连接池:c3p0
5、commons-logging的jar包
具体代码如下:
第一部分:配置文件
1、applicationContentx.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-- 自动扫描与装配Bean -->
<context:component-scan base-package="com.zit" /> <context:annotation-config /> <context:property-placeholder location="classpath:config/jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<!-- 数据连接信息 -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource"></property> <!-- 指定hibernate的映射实体类位置 -->
<property name="mappingLocations" value="classpath:com/zit/entities/Student.hbm.xml"></property>
<!-- 指定hibernate的配置文件位置 -->
<property name="configLocation" value="classpath:config/hibernate.cfg.xml"></property> </bean> <!-- 配置一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
1.1 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL dialect 方言-->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 映射数据库对应实体类:注解生效方式生效方式 -->
<!-- <mapping class="Entity.Student"/> --> </session-factory> </hibernate-configuration>
1.2 jdbc.properties(根据个人的数据库,更改对应的参数,我的数据库名字是test)
driverClass = com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbcUrl = jdbc:sqlserver://localhost:1433;database=test
user = sa
password = xxxxx
2、Springmvc.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: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-3.0.xsd "> <!-- 注解扫描包,注意换成自己的路径 -->
<context:component-scan base-package="com.zit">
<!-- 只扫描@Controller的部分 -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->
</context:component-scan> <!-- 定义视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean> </beans>
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SSH</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- 加载所有的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<!-- 配置Spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 配置SpringMVC -->
<servlet>
<servlet-name>SSH</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>SSH</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> <!-- 加入Hibernate的过滤请求将session打开,不然在Dao层getCurrentSession()时报错 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter> <filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
第二部分:(映射数据库),我的数据库名字是test,里面有张Student表,有id(自增、主键),age,name三个字段
1、实体类Entities:Student.java
package com.zit.entities; import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; public class Student { private int id; private String name; private int age; public Student(){} public Student(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、Student.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>
<class name="com.zit.entities.Student" table="Student">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
第三部分:MVC:
1、控制层Controller(C):StudentController.java
package com.zit.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.zit.entities.Student;
import com.zit.service.StudentService; @Controller
@RequestMapping("/student")
public class StudentController { @Autowired
private StudentService studentService; @RequestMapping("/getAllStudent")
public String getAllStudent(HttpServletRequest request){
String ss = request.getParameter("userName");
List<Student> students = studentService.getAllStudent();
for(Student s : students){
System.out.println(s.getId());
System.out.println(s.getName());
System.out.println(s.getAge());
}
return "index";//返回index.jsp页面 } }
2、业务逻辑层Service、Dao(M)
2.1.1 StudentService.java
package com.zit.service; import java.util.List; import com.zit.entities.Student; public interface StudentService { public List<Student> getAllStudent(); }
2.1.2 StudentServiceImpl.java
package com.zit.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.zit.dao.StudentDao;
import com.zit.entities.Student;
import com.zit.service.StudentService; @Service
public class StudentServiceImpl implements StudentService{ @Autowired
private StudentDao studentDao; @Override
public List<Student> getAllStudent() {
return studentDao.getAllStudent();
} }
2.2.1 StudentDao.java
package com.zit.dao; import java.util.List; import com.zit.entities.Student; public interface StudentDao { public List<Student> getAllStudent(); }
2.2.1 StudentDaoImpl.java
package com.zit.dao.impl; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; import com.zit.dao.StudentDao;
import com.zit.entities.Student; @Repository
public class StudentDaoImpl implements StudentDao{ @Resource(name = "sessionFactory")
private SessionFactory sessionFactory; @Override
@Transactional
public List<Student> getAllStudent() {
String hql = "from Student";
//getCurrentSession()比openSession()安全,注意web.xml中的配置,不然会报错
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hql); return query.list();
} }
3、视图层index.jsp(V):index.jsp
<%@ 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> <script type="text/javascript">
function addUser(){
var form = document.forms[0];
form.action = "/SSH/student/getAllStudent";
form.method="post";
form.submit();
}
</script> </head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
姓名:<input type="text" name="userName">
年龄:<input type="text" name="age">
<input type="button" value="添加" onclick="addUser()">
</form> </body>
</html>
以上配置文件是完整、可行的,建议不要擅自删除,
因为本人搭建期间遇到过几个报错,就是因为擅自删除配置文件,比如:
No Hibernate Session bound to thread, and configuration does not allow creat
等等,在此不一 一列举。
到此,搭建好一个能访问数据库的SSH工程,启动Tomcat,可运行查看效果。
这里的jsp页面只是用来打断点验证能否正常访问数据库的,没有实际意义……