项目开发环境
1.Eclipse
2.tomcat7.0
3.MySQL
项目的整体架构
所用到的jar包
数据库表
数据库表就不用教大家了,一张表,很简单的,下面是我建好的表
下面是web.xml的详情信息
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee" 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>json_test</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <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/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</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> <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>
下面是spring-common.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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!--扫描映射 --> <context:component-scan base-package="ssh"/> <!-- 引入property配置文件 --> <context:property-placeholder location="classpath:prop/jdbc.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${jdbc.mysql.driverClassName}"></property> <property name="url" value="${jdbc.mysql.url}"></property> <property name="username" value="${jdbc.mysql.username}"></property> <property name="password" value="${jdbc.mysql.password}"></property> <!-- 初始化连接大小 <property name="initialSize" value="${jdbc.initialSize}"></property> --> <!-- 连接池最大数量 <property name="maxActive" value="${jdbc.maxActive}"></property>--> <!-- 连接池最大空闲 --> <!-- <property name="maxIdle" value="${maxIdle}"></property> --> <!-- 连接池最小空闲 <property name="minIdle" value="${jdbc.minIdle}"></property>--> <!-- 获取连接最大等待时间 <property name="maxWait" value="${jdbc.maxWait}"></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">${jdbc.mysql.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <!--是否显示sql语句 我在这里是显示的 --> <prop key="hibernate.show_sql">true</prop> <!--格式化显示sql语句 --> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 自动扫描制定位置下的实体进行映射 --> <property name="packagesToScan" value="ssh.entity"/> </bean> <!-- 配置一个事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 应该是开启事物 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
下面是spring-mvc.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: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 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="ssh" /> <!-- 开启注解 --> <mvc:annotation-driven /> <!-- 定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
Hibernate用于连接数据库的小配置文件jdbc.properties的详情信息
# JDBC # 设置连接池连接时的数量 jdbc.initialSize=1 jdbc.filters=stat # 连接池中存在的最小连接数目。连接池中连接数目可以变很少,如果使用了maxAge属性,有些空闲的连接会被关闭因为离它最近一次连接的时间过去太久了。但是,我们看到的打开的连接不会少于minIdle。 jdbc.minIdle=1 # 连接数据库的最大连接数。这个属性用来限制连接池中能够打开连接的数量,可以方便数据库做连接容量规划。 jdbc.maxActive=99 jdbc.maxWait=1000 jdbc.minEvictableIdleTimeMillis=300000 jdbc.poolPreparedStatements=true jdbc.maxPoolPreparedStatementPerConnectionSize=50 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.validationQuery=select 1 from dual jdbc.removeAbandonedTimeout=150 jdbc.logAbandoned=true jdbc.removeAbandoned=true jdbc.testOnBorrow=false jdbc.testOnReturn=false #ORACLE 数据库连接方式 #jdbc.oracle.driverClassName=oracle.jdbc.driver.OracleDriver #jdbc.oracle.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl #jdbc.oracle.username=wrg #jdbc.oracle.password=wrg #jdbc.oracle.dialect=org.hibernate.dialect.Oracle10gDialect # MYSQL 数据库连接方式 jdbc.mysql.driverClassName=com.mysql.jdbc.Driver jdbc.mysql.url=jdbc:mysql://localhost:3806/springmvc?characterEncoding=UTF-8 jdbc.mysql.username=root jdbc.mysql.password=HZIMS_GP jdbc.mysql.dialect=org.hibernate.dialect.MySQL5InnoDBDialect #HIBERNATE jdbc.show_sql=false jdbc.format_sql=false
下面是log4j.properties日志文件的详情信息
#console log log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n #logger log4j.logger.org.springframework=DEBUG,CONSOLE log4j.logger.org.hibernate=INFO,CONSOLE log4j.logger.org.apache=INFO,CONSOLE log4j.rootLogger=DEBUG,CONSOLE
创建Entity类User实体
package ssh.entity; 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="TUSER") public class User{ @Id @GeneratedValue(generator="id") @GenericGenerator(name = "id",strategy="identity") private Integer id; private String name; private String password; @Column(name="LOGIN_DATE") private String loginDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getLoginDate() { return loginDate; } public void setLoginDate(String loginDate) { this.loginDate = loginDate; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + ", loginDate=" + loginDate + "]"; } }
创建Dao层接口
package ssh.dao; import java.util.List; import ssh.entity.User; public interface UserDao { //登录 User selectUser(User user) throws Exception; //查询所有 List<User> getAllUsers() throws Exception; //添加用户 void addUser(User user) throws Exception; //删除用户 void delUser(Integer id) throws Exception; //修改用户 void updateUser(User user) throws Exception; //单个查询 User getUser(Integer id) throws Exception ; }
Dao层接口的实现
package ssh.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import ssh.entity.User; @Repository @SuppressWarnings("unchecked") public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; //登录 public User selectUser(User user) throws Exception { Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.name=? and u.password=?"); query.setString(0, user.getName()); query.setString(1, user.getPassword()); List<User> list = query.list(); if(list==null||list.size()==0){ throw new RuntimeException("查询失败"); } return list.get(0); } //查询所有 public List<User> getAllUsers() throws Exception { Query query = sessionFactory.getCurrentSession().createQuery("from User"); List<User> list = query.list(); return list; } //单个查询 public User getUser(Integer id) throws Exception { return (User) sessionFactory.getCurrentSession().createQuery("from User u where u.id ="+id).uniqueResult(); } //添加用户 public void addUser(User user) throws Exception { System.out.println("11111111111111111"+user.getName()); sessionFactory.getCurrentSession().save(user); } //删除用户 public void delUser(Integer id) throws Exception { sessionFactory.getCurrentSession().createQuery("delete User u where u.id="+id).executeUpdate(); } //修改用户 public void updateUser(User user) throws Exception { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); String hql = ("update User u set u.name = ?,u.password = ?,u.loginDate = ? where u.id = ?"); Query query = session.createQuery(hql); query.setParameter(0, user.getName()); query.setParameter(1, user.getPassword()); query.setParameter(2, user.getLoginDate()); query.setParameter(3, user.getId()); query.executeUpdate(); session.getTransaction().commit(); } }
创建Service层的接口
package ssh.service; import java.util.List; import ssh.entity.User; public interface UserService { //登录 User selectUser(User user ) throws Exception; //查询所有 List<User> getAllUsers() throws Exception; //添加用户 void addUser(User user) throws Exception; //删除用户 void delUser(Integer id) throws Exception; //修改用户 void updateUser(User user) throws Exception; //单个查询 User getUser(Integer id) throws Exception; }
Service层的接口的实现
package ssh.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ssh.dao.UserDao; import ssh.entity.User; @Service("userService") public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; //登录 public User selectUser(User user) throws Exception { return userDao.selectUser(user); } //单个查询 public User getUser(Integer id) throws Exception { return userDao.getUser(id); } //查询所有 public List<User> getAllUsers() throws Exception { List<User> users = userDao.getAllUsers(); return users; } //添加用户 public void addUser(User user) throws Exception { userDao.addUser(user); } //删除用户 public void delUser(Integer id) throws Exception { userDao.delUser(id); } //修改用户 public void updateUser(User user) throws Exception { userDao.updateUser(user); } }
控制层Action层的代码如下
package ssh.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import ssh.entity.User; import ssh.path.Path; import ssh.service.UserService; @Controller @RequestMapping(value=Path.USER) public class UserAction { @Autowired private UserService userService; @RequestMapping(value=Path.LOGIN_INDEX) public String login(HttpServletRequest request, HttpServletResponse response) throws Exception{ return Path.LOGIN_INDEX; } @RequestMapping(value=Path.LOGIN_OK,method=RequestMethod.POST) public String loginCheck(User user,HttpServletRequest request, HttpServletResponse response) throws Exception{ response.setContentType("text/html;charset=utf-8"); User u = userService.selectUser(user); System.out.println("user is ------------------------ "+u); request.setAttribute("user", u); return "redirect:/user/index.do"; } //单个查询 @RequestMapping(value=Path.GET_USER) public String getUser(Integer id,HttpServletRequest request) throws Exception{ request.setAttribute("user", userService.getUser(id)); return Path.UPDATE_USER; } //查询所有 @RequestMapping(value=Path.INDEX) public String getAllUsers(HttpServletRequest request) throws Exception{ request.setAttribute("userList", userService.getAllUsers()); return Path.INDEX; } //添加跳转方法 @RequestMapping(value=Path.TO_ADDUSER) public String toAddUser(){ return Path.ADD_USER; } //添加用户 @RequestMapping(value=Path.ADD_USER) public String addUser(User user,HttpServletRequest request) throws Exception{ System.out.println("用户名:======"+user.getName()); userService.addUser(user); return "redirect:/user/index.do"; } //删除用户 @RequestMapping(value=Path.DEL_USER) public String delUser(Integer id,HttpServletResponse response) throws Exception{ userService.delUser(id); return "redirect:/user/index.do"; } //更新用户 @RequestMapping(value=Path.UPDATE_USER) public String updateUser(User user,HttpServletRequest request) throws Exception{ userService.updateUser(user); user = userService .getUser(user.getId()); request.setAttribute("user", user); return "redirect:/user/index.do"; } }
全局路径Path的代码
package ssh.path; public class Path { public static final String USER = "/user"; /** * 登陆 */ public static final String LOGIN_INDEX = "/login"; /** * 登陆成功 */ public static final String LOGIN_OK = "/loginok"; /** * 查询所有 */ public static final String INDEX = "/index"; /** * 添加用户 */ public static final String ADD_USER = "/addUser"; /** * 跳转添加用户 */ public static final String TO_ADDUSER = "/toaddUser"; /** * 删除用户 */ public static final String DEL_USER = "/delUser"; /** * 更新用户 */ public static final String UPDATE_USER = "/updateUser"; /** * 跳转更新用户 */ public static final String GET_USER = "/getUser"; }
测试类Test的代码
package ssh.test; import org.hibernate.SessionFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import ssh.dao.UserDao; import ssh.entity.User; import ssh.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring/spring-common.xml") @Transactional /** * * @author hello * 说明:在这里 所有实例化的注解我都使用 @Autowrited (spring通用的) * 也可以使用 @Resource (J2EE通用的) * 两者区别百度 */ public class TestAll { @Autowired private SessionFactory sessionFactory; /** * 测试sessionfactory * 测试时 spring-common 不能存在 事物bean * 不能存在 事物管理器 bean * 不能存在dao * 不能存在service * 不能存在action * 只是为了防止当其他内容写错时 sessionfactory也开启不了 除非是其他的bean没有错 */ @Test public void testSf(){ System.out.println("测试开启"); System.out.println(" sessionfactory = "+sessionFactory); System.out.println("测试完成"); } /** * 测试UserDao */ @Autowired private UserDao userDao; @Test public void testUserDao() throws Exception{ User u = new User(); u.setName("admin"); u.setPassword("12345678"); User user = userDao.selectUser(u); System.out.println("user is "+user); userDao.addUser(u); } /** * 测试UserService */ @Autowired private UserService userService; @Test public void testUserService() throws Exception{ User u = new User(); u.setName("admin"); u.setPassword("12345678"); User user = userService.selectUser(u); System.out.println("user is "+user); } }
登录界面login.jsp的代码
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <script type="text/javascript" src="../js/jquery-1.8.3.js"></script> <style> body{ text-align:center} .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00} /* css注释:为了观察效果设置宽度 边框 高度等样式 */ </style> <body> <div class="div"> <h1>用户登录</h1> <form action="/spring_springmvc_hibernate/user/index.do" method="post"> 用户名:<input type="text" name="name" > 密码:<input type="password" name="password"> <input type="submit" value="提交" > </form> </div> </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"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <% String path = request.getContextPath(); %> <script type="text/javascript" src="<%=path%>/js/jquery-1.9.1.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style> body{ text-align:center} .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00} /* css注释:为了观察效果设置宽度 边框 高度等样式 */ .t{ margin:0 auto; width:600px; height:300px; border:1px solid #F00} </style> </head> <body> <div class="div"> <h1><a href="/spring_springmvc_hibernate/user/toaddUser.do">添加用户</a></h1> <table border="1" class="t"> <tbody> <tr> <th>姓名</th> <th>密码</th> <th>登录时间</th> <th>操作</th> </tr> <c:if test="${!empty userList }"> <c:forEach items="${userList}" var="user"> <tr> <td>${user.name }</td> <td>${user.password }</td> <td>${user.loginDate }</td> <td> <a href="/spring_springmvc_hibernate/user/getUser.do?id=${user.id }">编辑</a> <a href="/spring_springmvc_hibernate/user/delUser.do?id=${user.id }">删除</a> </td> </tr> </c:forEach> </c:if> </tbody> </div> </table> </body> </html>
添加用户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"%> <!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> <style> body{ text-align:center} .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00} /* css注释:为了观察效果设置宽度 边框 高度等样式 */ </style> <script type="text/javascript"> function addUser(){ var form = document.forms[0]; form.action = "/spring_springmvc_hibernate/user/addUser.do"; form.method="post"; form.submit(); } </script> </head> <body> <div class="div"> <h1>添加用户</h1> <form action="" name="userForm"> 姓名:<input type="text" name="name"> 密码:<input type="text" name="password"> 时间:<input type="text" name="loginDate"> <input type="button" value="添加" onclick="addUser()"> </form> </div> </body> </html>
更新数据updateUser.jsp的页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <% String path = request.getContextPath(); %> <script type="text/javascript" src="<%=path %>/js/jquery-1.9.1.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style> body{ text-align:center} .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00} /* css注释:为了观察效果设置宽度 边框 高度等样式 */ </style> </head> <body> <div class="div"> <h1>编辑用户</h1> <form action="/spring_springmvc_hibernate/user/updateUser.do" name="userForm" method="post"> <input type="hidden" name="id" value="${user.id }"> 姓名:<input type="text" name="name" value="${user.name }"> 密码:<input type="text" name="password" value="${user.password }"> 时间:<input type="text" name="loginDate" value="${user.loginDate }"> <input type="submit" value="编辑" > </form> </div> </body> </html>
用户登录界面
查询所有界面
编辑用户页面
添加用户页面
删除就不说了,点击删除自动回到查询所有的界面
以上就是所有关于三大框架整合的所有代码
项目源码下载
http://download.csdn.net/detail/qq_34413570/9516697导入就可以运行
时间: 2024-10-07 22:59:12