使用工具及环境
idea,Navicat,maven,mysql,Tomcat
搭建项目
- file->module
- 设置项目名称
- 添加maven配置
- 完成后的项目结构
- 项目创建完成后添加坐标
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<!--数据库连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis整合spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
- 构建项目框架目录
- com.zy.controller 控制层
- com.zy.service 服务层
- com.zy.mapper 数据访问层
- com.zy.pojo 实体类
mybatis层编写
- 数据库配置jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456
- 编写实体类
public class User {
private Integer id;
private String username;
private String sex;
private String address;
private String telephone;
//别忘记getxxx()/setxxx()方法
}
- dao层的mapper接口编写
@Repository
public interface UserMapper {
/***
* 查询所有
*/
@Select(value = "select * from user")
List<User> findAll();
/***
* 新增用户
*/
@Insert(value = "insert into user(username,telephone,sex,address) values(#{username},#{telephone},#{sex},#{address})")
void saveUser(User user);
/***
* 根据id删除
*/
@Delete(value = "delete from user where id=#{id}")
void delUser(@Param("id")Integer id);
/***
* 根据id查询
*/
@Select(value = "select * from user where id=#{id}")
User findUserById(@Param("id") Integer id);
/***
* 更新用户
*/
@Update(value = "update user set username=#{username},telephone=#{telephone},sex=#{sex},address=#{address} where id=#{id}")
int updateUser(User user);
}
- service层的接口和实现类
public interface UserService {
/***
* @Description 查询所有
*/
List<User> findAll();
/***
* @Description 新增用户
*/
void saveUser(User user);
/***
* @Description 根据id删除
*/
void delUser(Integer id);
/***
* @Description 根据id查询
*/
User findUserById(Integer id);
/***
* @Description 更新用户
*/
int updateUser(User user);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
/***
* @Description 查询所有用户
* @Param: []
* @return: java.util.List<com.zy.pojo.User>
*/
@Override
public List<User> findAll() {
return userMapper.findAll();
}
/***
* @Description 新增用户
* @Param: [user]
* @return: void
*/
@Override
public void saveUser(User user) {
userMapper.saveUser(user);
}
/***
* @Description 根据id删除用户
* @Param: [id]
* @return: void
*/
@Override
public void delUser(Integer id) {
userMapper.delUser(id);
}
/***
* @Description 根据id查询
* @Param: [id]
* @return: com.zy.pojo.User
*/
@Override
public User findUserById(Integer id) {
return userMapper.findUserById(id);
}
/***
* @Description 更新用户
* @Param: [user]
* @return: int
*/
@Override
public int updateUser(User user) {
return userMapper.updateUser(user);
}
}
spring层配置文件
spring整合dao以及包扫描都写在一个配置文件里面了applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--加载数据库连接配置文件-->
<context:property-placeholder location="classpath:jdbc/jdbc.properties"/>
<!--扫描service层-->
<context:component-scan base-package="com.zy.service"/>
<!--数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--四个基本属性-->
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置扫描Dao接口包,动态实现Dao接口注入到spring容器中-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--给出需要扫描Dao接口包-->
<property name="basePackage" value="com.zy.mapper"/>
</bean>
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
springmvc层的配置文件
主要是包扫描,注解驱动,静态资源过滤,视图解析器
<?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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller层-->
<context:component-scan base-package="com.zy.controller"/>
<!--springmvc的注解驱动-->
<mvc:annotation-driven />
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml主要是配置spring监听器,post请求乱码,mvc拦截
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<!-- 配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件,所以需要配置文件路径 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<!--配置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/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>
<!--解决post乱码-->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
controller类的代码编写
- 具体代码实现
@Controller
@RequestMapping(path = "/user")
public class UserController {
@Autowired
private UserService userService;
/***
* @Description 查询所有
* @Param: [model]
* @return: java.lang.String
*/
@RequestMapping(path = "/findAll", method = RequestMethod.GET)
public String findAll(Model model) {
List<User> users = userService.findAll();
model.addAttribute("users", users);
return "info";
}
/***
* @Description 新增用户
* @Param: [model]
* @return: java.lang.String
*/
@RequestMapping(path = "/addUser", method = RequestMethod.POST)
public String saveUser(User user) throws Exception {
userService.saveUser(user);
return "redirect:/user/findAll";
}
/***
* @Description 根据id删除
* @Param: [model]
* @return: java.lang.String
*/
@RequestMapping(path = "/delUser", method = RequestMethod.GET)
public String delUser(Integer id) {
userService.delUser(id);
return "redirect:/user/findAll";
}
/***
* @Description 根据id查询
* @Param: [model]
* @return: java.lang.String
*/
@RequestMapping(path = "/edit", method = RequestMethod.GET)
public String findUserById(Integer id, Model model) {
User user = userService.findUserById(id);
model.addAttribute("user", user);
return "edit";
}
/***
* @Description 更新用户
* @Param: [user]
* @return: java.lang.String
*/
@RequestMapping(path = "/updateUser", method = RequestMethod.POST)
public String updateUser(User user) {
userService.updateUser(user);
return "redirect:/user/findAll";
}
/***
* @Description 新增页面跳转
*/
@RequestMapping(path = "/add",method = RequestMethod.GET)
public String add(){
return "add";
}
}
- jsp页面
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/user/findAll">点击进入</a>
</h3>
</body>
</html>
- info.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户信息</title>
<style>
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
text-align: center;
padding: 15px;
}
</style>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/add">新增</a>
<table>
<tr>
<th>id</th>
<th>姓名</th>
<th>性别</th>
<th>电话</th>
<th>地址</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.sex}</td>
<td>${user.telephone}</td>
<td>${user.address}</td>
<td>
<a href="${pageContext.request.contextPath}/user/edit?id=${user.id}">编辑</a>
<a href="${pageContext.request.contextPath}/user/delUser?id=${user.id}" >删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
- add.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增用户</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增用户</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/user/addUser" method="post">
姓名:<input type="text" name="username"><br><br><br>
性别:<input type="text" name="sex"><br><br><br>
电话:<input type="text" name="telephone"><br><br><br>
地址:<input type="text" name="address"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
- edit.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改用户</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改用户</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/user/updateUser" method="post">
<input type="hidden" name="id" value="${user.id}"><br><br><br>
姓名:<input type="text" name="username" value="${user.username}"><br><br><br>
性别:<input type="text" name="sex" value="${user.sex}"><br><br><br>
电话:<input type="text" name="telephone" value="${user.telephone}"><br><br><br>
地址:<input type="text" name="address" value="${user.address}"><br><br><br>
<input type="submit" value="保存">
</form>
</div>