目录
需求分析
其中,查询条件中类型为下拉列表,可选值有“不限,支出,收入,转账,借出,借入,还入,还出”。日期输入框需要输入“yyyy-MM-dd”格式的日期字符串,点击“搜索”按钮提交表单,提交时如果输入项不符合输入要求,则显示相应提示信息。列表中根据记账类别在金额前添加相应的“+,-”符号,如果类别为“支出,借出,还出”时在金额前添加“-”。如果类别为“收入,借入,还入”时在金额前添加“+”。如果根据输入项进行查询后没有找到账单数据,则给出提示信息
点击“记账”按钮后,进入记账页面,如图
数据库设计
create table bills (
id int primary key auto_increment,
title varchar(50) not null,
billtime date not null,
typeid int not null,
price double not null,
explains varchar(500)
);
create table bill_type (
id int primary key auto_increment,
bname varchar(50) not null
);
环境搭建
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vv</groupId>
<artifactId>SSMDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SSMDemo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<springversion>5.0.8.RELEASE</springversion>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 加入ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- MySQL依赖 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 加入MyBatis 依赖 start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 引入Spring(包含SpringMVC) 依赖 start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springversion}</version>
</dependency>
<!-- 引用插件依赖:MyBatis整合Spring,如果mybatis版本在3.4及以上版本 mybatis-spring的版本要在1.3以上 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 德鲁伊数据连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<!--处理json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<!--javaee-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!--文件上传下载-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
<build>
<finalName>SSMDemo</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置⽂件的路径-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
web.xml
<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" version="2.5">
<!--1、配置前端控制器-->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--处理post乱码-->
<filter>
<filter-name>aa</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>aa</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:rx="http://www.springframework.org/schema/cache"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<!--配置数据源-->
<bean id="db" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<!--创建sqlSessionFactory-->
<bean id="fac" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="db"/>
<property name="configLocation" value="classpath:Mybatis.xml"></property><!--指定mybatis的路径-->
<property name="mapperLocations" value="classpath:mapper/*"></property><!--指定mybatis的mapper的路径-->
</bean>
<!--创建MapperScannerConfigurer,用于省略dao实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="fac"/>
<property name="basePackage" value="com.vv.dao"/><!--接口全路径-->
</bean>
<!--配置事务-->
<bean id="mytx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="db"/>
</bean>
<tx:annotation-driven transaction-manager="mytx"/>
<!--启用springmvc注解-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--扫描注解包-->
<context:component-scan base-package="com.vv"/>
<!--配置静态资源访问-->
<mvc:default-servlet-handler/>
</beans>
Mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--指定别名-->
<typeAliases>
<package name="com.vv.bean"/>
</typeAliases>
<!--分页插件-->
<plugins> <!-- PageHelper4.1.6 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置⽣成器 -->
<generatorConfiguration>
<!--数据库驱动jar(在maven中找) -->
<classPathEntry
location="D:\maven-repo\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar"/>
<context id="MyBatis" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="">
</jdbcConnection>
<!--⽣成实体类 指定包名 以及⽣成的地址 (可以⾃定义地址,但是路径不存在不会⾃动创建
使⽤Maven⽣成在target⽬录下,会⾃动创建) -->
<javaModelGenerator targetPackage="com.vv.bean"
targetProject="D:\IDEA\SSMDemo\src\main\java">
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--⽣成SQLmapper⽂件 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="D:\IDEA\SSMDemo\src\main\resources">
</sqlMapGenerator>
<!--⽣成Dao⽂件,⽣成接⼝ -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.vv.dao"
targetProject="D:\IDEA\SSMDemo\src\main\java">
</javaClientGenerator>
<!--指定表-->
<table tableName="bill_type" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>
<table tableName="bills" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
首页数据展示
展示全部账单和类型
我们需要展示的数据有两个,分别是所有的账单和所有的账单类型,所有我们要写账单和账单类型两个接口及其实现类
@Service
public class BillsServiceImpl implements BillsService {
@Resource
private BillsMapper billsMapper;
@Override
public List<Bills> getBills() {
//在BillsMapper中新增getBills的接口,并且在BillsMapper.xml中增加sql语句
return billsMapper.getBills();
}
}
@Service
public class BillTypesImpl implements BillTypesService {
@Resource
private BillTypeMapper typeMapper;
@Override
public List<BillType> getTypes() {
//在BillTypeMapper中新增getTypes的接口,并且在BillTypeMapper.xml中增加sql语句
return typeMapper.getTypes();
}
}
然后再在Controller来调取方法,返回数据给前台
@Controller
public class BillsController {
@Resource
private BillsService billsService;
@Resource
private BillTypesService typesService;
@RequestMapping("/getTypes")
public String getTypes(ModelMap map){
//查询所有的类型
List<BillType> types = typesService.getTypes();
//查询所有的账单
List<Bills> bills = billsService.getBills();
//返回数据给前台
map.addAttribute("types",types);
map.addAttribute("bills",bills);
return "show";
}
}
在前台的时候,我们在加载index.jsp的时候,发送个getTypes请求,然后再在show.jsp展示数据
show.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>展示数据</title>
</head>
<body>
<h1>记账管理</h1>
<p>
<form>
类型:
<select>
<%--value 属性规定在表单被提交时被发送到服务器的值,如果没有指定 value 属性,选项的值将设置为 <option> 标签中的内容--%>
<option value="-1">不限</option>
<c:forEach items="${types}" var="type">
<option value="${type.id}">${type.bname}</option>
</c:forEach>
</select>
时间:
从<input type="text" name="begin">到<input type="text" name="end">
<input type="submit" value="搜索">
</form>
<input type="button" value="记账">
</p>
<table border="1" width="500">
<tr>
<td>标题</td>
<td>记账时间</td>
<td>类型</td>
<td>金额</td>
<td>说明</td>
<td>操作</td>
</tr>
<c:forEach items="${bills}" var="bill">
<tr>
<td>${bill.title}</td>
<td><fmt:formatDate value="${bill.billtime}" pattern="yyyy-MM-dd"/></td>
<td>${bill.typeid}</td>
<td>${bill.price}</td>
<td>${bill.explains}</td>
<td>删除 修改</td>
</tr>
</c:forEach>
</table>
</body>
</html>
显示具体类型
但是这里的类型只显示的是数字,我们希望显示具体的类型,所有在查询的时候我们需要用两表连查。两表表查询的时候,易知这是个一对多的关系,所有在Bills对象中新增BillType类型的对象,BillType对象中新增List<Bills>集合。并且要修改BillsMapper.xml的SQL语句和resultMap
金额显示正负
如果类别为“支出,借出,还出”时在金额前添加“-”。 如果类别为“收入,借入,还入”时在金额前添加“+”
根据类型和时间段查询
我们可以把查询所有和模糊查询用同一个方法,用动态sql实现。
首先改一下表单
Controller
@RequestMapping("/search")
public String getTypes(Integer typeid,String begin,String end,ModelMap map) {
List<Bills> bills = billsService.getBills(typeid, begin, end);
List<BillType> types = typesService.getTypes();
map.addAttribute("bills",bills);
map.addAttribute("types",types);
//数据回显
map.addAttribute("tid",typeid);
map.addAttribute("begintime",begin);
map.addAttribute("endtime",end);
return "show";
}
并且还要修改一下,查询所有的方法参数
修改SQL语句
<select id="getBills" resultMap="rs1">
select * from bills b,bill_type t where b.typeid = t.id
<if test="tid!=-1">
and t.id=#{tid}
</if>
<if test="begin!=null and begin!=''">
and b.billtime>=#{begin}
</if>
<if test="end!=null and end!=''">
and b.billtime <![CDATA[ <= ]]> #{end}
</if>
</select>
回显信息
查询不到,显示‘无结果’
分页
首先我们需要修改一下getBills方法的参数,增加当前页码和页面大小的参数,并且使用分页插件,返回PageInfo<Bills>集合
@Override
public PageInfo<Bills> getBills(int typeid,String begin,String end,int index,int size) {
Map map = new HashMap();
map.put("tid",typeid);
map.put("begin",begin);
map.put("end",end);
//使用分页插件分页
PageHelper.startPage(index,size);
List<Bills> bills = billsMapper.getBills(map);
//创建分页工具类
PageInfo<Bills> info = new PageInfo<>(bills);
return info;
}
并且修改传递到前台的参数
在页面最下方加分页栏,但是在使用模糊查询的时候,无法进行数据回显,所有需要在请求后面加参数
<tr>
<td colspan="6">
<a href="/search?typeid=${tid}&begin=${begintime}&end=${endtime}">首页</a>
<a href="/search?index=${info.prePage==0?1:info.prePage}&typeid=${tid}&begin=${begintime}&end=${endtime}">上一页</a>
<a href="/search?index=${info.nextPage==0?info.pages:info.nextPage}&typeid=${tid}&begin=${begintime}&end=${endtime}">下一页</a>
<a href="/search?index=${info.pages}&typeid=${tid}&begin=${begintime}&end=${endtime}">尾页</a>
总页数:${info.pages}
总条数:${info.total}
</td>
</tr>
新增
首先我们需要获得所有的类型,用于在新增的时候展示
controller
@RequestMapping("/getBillType")
public String getBillType(ModelMap map) {
//得到所有账单类型,用于添加,然后跳转到添加页面
List<BillType> types = typesService.getTypes();
map.addAttribute("types",types);
return "add";
}
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新增</title>
</head>
<body>
<h1>记账</h1>
<form action="/insert" method="post">
<p>
类型:
<c:forEach items="${types}" var="type">
<input type="radio" value="${type.id}" name="typeid">${type.bname}
</c:forEach>
</p>
<p>标题:<input type="text" name="title"></p>
<p>日期:<input type="text" name="billtime"></p>
<p>金额:<input type="text" name="price"></p>
<p>说明:<textarea cols="50" rows="4" name="explains"></textarea></p>
<input type="reset" value="重置">
<input type="submit" value="提交">
</form>
</body>
</html>
name属性要和bills对象的属性一致,只要传到后台就可以直接用一个对象接收,并且接口实现方法
@RequestMapping("/insert")
public String insert(Bills bill) {
int insert = billsService.insert(bill);
if(insert>0) {
return "redirect:/getTypes";//回到主页面
}
return "redirect:/getBillType";//新增失败回到新增页面,但是不能直接去
}
更新
更新和新增差不多,用的页面差不多。更新需要调用获取所有类型和主键查询,查询出来结果用于在页面回显数据,然后再进行修改。
@RequestMapping("/findById")
public String findById(int id,ModelMap map) {
Bills bills = billsService.selectByPrimaryKey(id);
List<BillType> types = typesService.getTypes();
map.addAttribute("types",types);
map.addAttribute("bill",bills);
return "update";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>更新</h1>
<form action="/updateBill" method="post">
<input type="hidden" name="id" value="${bill.id}"><!--这里隐藏域用来提交id-->
<p>
类型:
<c:forEach items="${types}" var="type">
<input type="radio" value="${type.id}" ${type.id==bill.typeid?'checked':''} name="typeid">${type.bname}
</c:forEach>
</p>
<p>标题:<input type="text" name="title" value="${bill.title}"></p>
<p>日期:<input type="text" name="billtime" value="<fmt:formatDate value="${bill.billtime}" pattern="yyyy/MM/dd"/>"></p>
<p>金额:<input type="text" name="price" value="${bill.price}"></p>
<p>说明:<textarea cols="50" rows="4" name="explains">${bill.explains}</textarea></p>
<input type="reset" value="重置">
<input type="submit" value="保存">
</form>
</body>
</html>
@RequestMapping("/updateBill")
public String updateBill(Bills bills) {
int update = billsService.updateByPrimaryKey(bills);
if(update>0) {
return "redirect:/getTypes";//回到主页面
}
return "redirect:/findById?id="+bills.getId();
}
删除
删除是所有功能中最简单的
@RequestMapping("/deleteById")
public void deleteById(int id, HttpServletResponse response) {
int delete = billsService.deleteByPrimaryKey(id);
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
if(delete>0) {
writer.print("<script>alert('删除成功');location.href='/getTypes'</script>");
return;
}
writer.print("<script>alert('删除失败');location.href='/getTypes'</script>");
} catch (IOException e) {
e.printStackTrace();
}
}