一.数据库表
/*
Navicat MySQL Data Transfer
Source Server : 本地连接
Source Server Version : 50720
Source Host : localhost:3306
Source Database : ssh_demo
Target Server Type : MYSQL
Target Server Version : 50720
File Encoding : 65001
Date: 2019-10-07 14:19:04
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`address` varchar(255) DEFAULT NULL,
`username` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('6', 'GZ', '张三', '13456789487');
INSERT INTO `t_user` VALUES ('7', 'GZ', '张三', '15674635267');
二.使用idea创建一个maven项目,然后创建如下的目录
三.各种配置文件如下
1.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" version="3.0"> <welcome-file-list> <welcome-file>/index.jspwelcome-file> welcome-file-list> <context-param> <param-name>contextConfigLocationparam-name> <param-value> classpath:applicationContext.xml param-value> context-param> <servlet> <servlet-name>springservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:spring-mvc.xmlparam-value> init-param> <load-on-startup>1load-on-startup> servlet> <servlet-mapping> <servlet-name>springservlet-name> <url-pattern>/url-pattern> servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <filter> <filter-name>encodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>UTF-8param-value> init-param> <init-param> <param-name>forceEncodingparam-name> <param-value>trueparam-value> init-param> filter> <filter-mapping> <filter-name>encodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> web-app>
2.applicationContext.xml
<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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:component-scan base-package="com.ssh"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> context:component-scan> <context:property-placeholder location="classpath:config.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxPoolSize" value="40" /> <property name="minPoolSize" value="1" /> <property name="initialPoolSize" value="10" /> <property name="maxIdleTime" value="20" /> bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.ssh.entity" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}prop> <prop key="hibernate.dialect">${hibernate.dialect}prop> <prop key="hibernate.show_sql">${hibernate.show_sql}prop> <prop key="hibernate.format_sql">${hibernate.format_sql}prop> props> property> bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> bean> beans>
3.config.properties
#database connection config jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/ssh_demo?useUnicode=true&characterEncoding=utf-8 jdbc.username = root jdbc.password = ??? #hibernate config hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.show_sql = true hibernate.format_sql = true hibernate.hbm2ddl.auto = update
4.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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.ssh" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> bean> beans>
5.UserController.java
package com.ssh.controller; import com.ssh.entity.User; import com.ssh.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/getUsers") public String findUsers(Model model){ Listusers = userService.findUsers(); model.addAttribute("users",users); return "user"; } @RequestMapping("/saveUser") public String saveUsser(){ User user = new User(); userService.saveUser(user); return "success"; } }
6.User.java
package com.ssh.entity; import javax.persistence.*; @Entity @Table(name = "t_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "username") private String username; @Column(name = "address") private String address; @Column(name = "phone") private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Person{" + "id=" + id + ", address='" + address + '\'' + '}'; } }
7.UserDao.java
package com.ssh.dao; import com.ssh.entity.User; import java.util.List; public interface UserDao { ListfindUsers(); int saveUser(User entity); }
8.UserDaoImpl.java
package com.ssh.dao.impl; import com.ssh.dao.UserDao; import com.ssh.entity.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; private Session getCurrentSession() { return this.sessionFactory.openSession(); } @Override public int saveUser(User entity) { int id = (Integer) getCurrentSession().save(entity); return id; } @Override public ListfindUsers() { Query query = getCurrentSession().createQuery("from User"); List list = query.list(); return list; } }
9.UserService.java
package com.ssh.service; import com.ssh.entity.User; import java.util.List; public interface UserService { ListfindUsers(); int saveUser(User entity); }
10.UserServiceImpl.java
package com.ssh.service.impl; import com.ssh.dao.UserDao; import com.ssh.entity.User; import com.ssh.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public ListfindUsers() { return userDao.findUsers(); } @Override public int saveUser(User entity) { entity.setAddress("GZ"); entity.setUsername("张三"); entity.setPhone("15674635267"); return userDao.saveUser(entity); } }
11.success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>Title save user success
12.user.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %>用户信息
ID | 姓名 | 地址 | 电话号码 |
---|---|---|---|
${obj.id} | ${obj.username} | ${obj.address} | ${obj.phone} |
四.启动tomcat
1.输入http://localhost:8080/user/saveUser结果如下
表中数据增加了一个用户
2.浏览器输入http://localhost:8080/user/getUsers