本项目是一个Spring+SpringMVC+Mybatis+MySQL的一个小项目,项目只有简单的增删改查。
前端用了JQuery和Boostrap(其实也没用啥)。
纯粹是为了练习一下框架整合。
版本:Spring(4.3.6)、SpringMVC(4.3.6)、Mybatis(3.4.2)、MySQL(5.7.0)
虽然界面是食堂管理系统,但是,这都不是关键。。毕竟想改成啥就是啥。
开发环境:Eclipse+Tomcat8.5
目录
https://download.csdn.net/download/LitongZero/11990182
1、目录结构
2、配置文件
applicationContext.xml
Spring核心配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!--读取db.properties -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="${jdbc.driver}" />
<!--连接数据库的url -->
<property name="url" value="${jdbc.url}" />
<!--连接数据库的用户名 -->
<property name="username" value="${jdbc.username}" />
<!--连接数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!--最大连接数 -->
<property name="maxTotal" value="${jdbc.maxTotal}" />
<!--最大空闲连接 -->
<property name="maxIdle" value="${jdbc.maxIdle}" />
<!--初始化连接数 -->
<property name="initialSize" value="${jdbc.initialSize}" />
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class=
"org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="select*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="get*" propagation="SUPPORTS"
read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* cn.lt.core.service.*.*(..))" />
</aop:config>
<!-- 配置 MyBatis的工厂 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBatis的核心配置文件所在位置 -->
<property name="configLocation"
value="classpath:mybatis-config.xml" />
</bean>
<!-- 接口开发,扫描 com.lt.core.dao包 ,写在此包下的接口即可被扫描到 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.lt.core.dao" />
</bean>
<!-- 配置扫描@Service注解 -->
<!-- 配置扫描@Service注解 -->
<context:component-scan base-package="cn.lt.core.service"/>
</beans>
db.properties
数据库配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmtest
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
log4j.properties
log日志文件配置
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.lt.core=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis-config.xml
mybatis配置文件
<?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="cn.lt.core.po" />
</typeAliases>
</configuration>
springmvc-config.xml
SpringMVC配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置扫描器 -->
<context:component-scan
base-package="cn.lt.core.web.controller" />
<!-- 注解驱动:配置处理器映射器和适配器 -->
<mvc:annotation-driven />
<!--配置静态资源的访问映射,此配置中的文件,将不被前端控制器拦截 -->
<mvc:resources location="/flex-slider/" mapping="/flex-slider/**" />
<mvc:resources location="/image/" mapping="/image/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/scripts/" mapping="/scripts/**" />
<mvc:resources location="/styles/" mapping="/styles/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<!-- 配置视图解释器ViewResolver -->
<bean id="jspViewResolver" class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
3、po
Food.java
package cn.lt.core.po;
import java.io.Serializable;
public class Food implements Serializable{
private static final long serialVersionUID = 1L;
// 主键
private String id;
// 食品名称
private String name;
// 价钱
private String price;
// 备注
private String msg;
// 时间
private String date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "Food [id=" + id + ", name=" + name + ", price=" + price
+ ", msg=" + msg + ", date=" + date + "]";
}
}
4、Dao
FoodDao.java
package cn.lt.core.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.lt.core.po.Food;
/**
* 用户DAO层接口
*/
public interface FoodDao {
/**
* 通过账号和密码查询用户
*/
public int addFood(Food food);
public List<Food> findAllFood();
public void delFood(int id);
public Food findFoodById(int id);
public int updateFood(Food food);
public Food findFoodByName(@Param("name")String name);
}
FoodDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.lt.core.dao.FoodDao" >
<!-- 添加信息 -->
<insert id="addFood" parameterType="Food" >
insert into food(
id,
name,
price,
msg,
date
)
values(#{id},
#{name},
#{price},
#{msg},
#{date}
)
</insert>
<select id="findAllFood" resultType="Food">
select *
from food
</select>
<delete id="delFood" parameterType="Integer">
delete from food where
id=#{id}
</delete>
<update id="updateFood" parameterType="Food">
update food set
name=#{name},
price=#{price},
msg=#{msg},
date=#{date}
where id=#{id}
</update>
<select id="findFoodById" parameterType="Integer" resultType="Food" >
select *
from food
where id=#{id}
</select>
<select id="findFoodByName" parameterType="String" resultType="Food" >
select *
FROM food
WHERE
<if test="name != '' " >
name LIKE CONCAT('%', #{name, jdbcType=VARCHAR}, '%')
</if>
<if test="name == '' " >
1=0
</if>
</select>
</mapper>
5、Service
FoodService.java
package cn.lt.core.service;
import java.util.List;
import cn.lt.core.po.Food;
public interface FoodService {
public List<Food> findAllFood();
public boolean addFood(Food food);
public void delFood(int id);
public Food findFoodById(int id);
public boolean updateFood(Food food);
public Food findFoodByName(String name);
}
FoodServiceImpl.java
package cn.lt.core.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 cn.lt.core.dao.FoodDao;
import cn.lt.core.po.Food;
import cn.lt.core.service.FoodService;
/**
* 用户Service接口实现类
*/
@Service("foodService")
@Transactional
public class FoodServiceImpl implements FoodService {
@Autowired
private FoodDao foodDao;
@Override
public boolean addFood(Food food) {
return this.foodDao.addFood(food)>0 ? true:false;
}
@Override
public List<Food> findAllFood() {
return this.foodDao.findAllFood();
}
@Override
public void delFood(int id) {
this.foodDao.delFood(id);
}
@Override
public Food findFoodById(int id) {
return this.foodDao.findFoodById(id);
}
@Override
public boolean updateFood(Food food) {
return this.foodDao.updateFood(food)>0 ? true:false;
}
@Override
public Food findFoodByName(String name) {
return this.foodDao.findFoodByName(name);
}
}
6、Controller
FoodController.java
package cn.lt.core.web.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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 org.springframework.web.bind.annotation.RequestMethod;
import cn.lt.core.po.Food;
import cn.lt.core.service.FoodService;
@Controller
public class FoodController {
@Autowired
private FoodService foodService;
@RequestMapping(value="/index", method=RequestMethod.GET)
public String index(Model model){
List<Food> foods = null;
foods = foodService.findAllFood();
model.addAttribute("foods",foods);
return "index";
}
@RequestMapping(value = "/addFood" ,method = RequestMethod.POST)
public String sendMail(Model model,String name ,String price,String msg,
HttpServletRequest request, HttpServletResponse response) {
int success =0;
Food food = new Food();
food.setMsg(msg);
food.setName(name);
food.setPrice(price);
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
food.setDate(df.format(date));
if (foodService.addFood(food)) {
success=1;
}
try {
response.getWriter().write("{\"success\":"+success+"}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:index";
}
@RequestMapping(value="/delete", method=RequestMethod.GET)
public String del(int id){
foodService.delFood(id);
return "redirect:index";
}
@RequestMapping(value="/findFoodByName.action", method=RequestMethod.GET)
public String findFoodByid(String name,Model model){
Food food=null;
System.out.println(name);
List<Food> foods = new ArrayList<Food>();
food = foodService.findFoodByName(name);
if (food!=null) {
foods.add(food);
}else {
foods = foodService.findAllFood();
}
System.out.println(foods);
model.addAttribute("foods",foods);
return "index";
}
//
// @RequestMapping(value="/findFoodByid", method=RequestMethod.GET)
// public String editFoodByid(int id,Model model){
// Food food=null;
// food = foodService.finFoodById(id);
// model.addAttribute("food",food);
// return "editFood";
// }
@RequestMapping(value="/editFood", method=RequestMethod.GET)
public String editUser(int param ,String name ,String price,String msg,int id,Model model){
Food food=new Food();
try {
if(param == 0){
food = foodService.findFoodById(id);
model.addAttribute("food",food);
return "editFood";
}else if(param == 1){
food.setId(id+"");
food.setMsg(msg);
food.setName(name);
food.setPrice(price);
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
food.setDate(df.format(date));
System.out.println(food);
Boolean aBoolean = foodService.updateFood(food);
System.out.println(aBoolean);
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:index";
}
}
7、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript" src="js/bootstrap.bundle.js"></script>
<script type="text/javascript" src="js/bootstrap.bundle.min.js"></script>
<title>食堂管理系统</title>
<meta charset="UTF-8">
<script type="text/javascript">
$(function(){
$('#submit').click(sendMessage);
//为输入框绑定事件
function sendMessage() {
var dataString = $('#cform').serialize();
$.post(
"${pageContext.request.contextPath}/addFood",
dataString,
function(data){
var isExist = data.success;
//3、根据返回的isExist动态的显示信息
var usernameInfo = "";
if(success==1){
usernameInfo = "成功";
$("#usernameInfo").css("color","green");
}else{
usernameInfo = "失败"
$("#usernameInfo").css("color","red");
}
$("#usernameInfo").html(usernameInfo);
},
"json"
);
}
});
</script>
</head>
<body>
<h1 style="text-align:center">食堂管理系统</h1>
<form action="${pageContext.request.contextPath}/findFoodByName.action" method="get">
菜品名称:<input type="text" name="name" id="name" placeholder="输入菜品名称搜索">
<input type="submit" value="搜索">
</form>
<table class="table table-bordered table-hover" align="center">
<thead>
<tr bgcolor="#ff0">
<th width="5%">编号</th>
<th width="10%">菜品名称</th>
<th width="10%">价格</th>
<th width="25%">备注</th>
<th width="15%">时间</th>
<th width="10%">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="food" items="${foods}">
<tr>
<td>${food.id}</td>
<td>${food.name}</td>
<td>${food.price}</td>
<td>${food.msg}</td>
<td>${food.date}</td>
<td><a href="${pageContext.request.contextPath}/editFood.action?param=0&id=${food.id}">编辑</a>
<a href="${pageContext.request.contextPath}/delete.action?id=${food.id}">删除</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<br/>
<div align="center">
<br/><br/>
<p >添加菜品</p>
<form id="cform" action="addFood.action" method="post">
菜品名称:<input type="text" name="name">
价格:<input type="text" name="price">
备注:<input type="text" name="msg">
<span id="usernameInfo"></span>
<input id="submit" type="submit" value="提交"> <input type="reset" value="重置">
</form>
</div>
</body>
</html>
8、editFood.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>修改菜品信息</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="SSH">
</head>
<body>
编辑菜品信息
<form action="editFood.action" method="get">
ID:<input type="text" name="id" value="${food.id}" readonly="readonly"><br/>
菜品名称:<input type="text" name="name" value="${food.name}"><br/>
菜品价格:<input type="text" name="price" value="${food.price}"><br/>
菜品备注:<input type="text" name="msg" value="${food.msg}"><br/>
<input type="hidden" name="param" value="1"/>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
9、数据库.sql
# Host: localhost (Version 5.7.9-log)
# Date: 2018-07-29 11:41:35
# Generator: MySQL-Front 6.0 (Build 2.20)
#
# Structure for table "food"
#
DROP TABLE IF EXISTS `food`;
CREATE TABLE `food` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`price` varchar(255) DEFAULT NULL,
`msg` varchar(255) DEFAULT NULL,
`date` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
#
# Data for table "food"
#
INSERT INTO `food` VALUES (1,'鱼香肉','15元','好吃','2018年07月29日 10:05:41'),(2,'宫保鸡丁','15元','食堂阿姨推荐','2018年06月11日 00:59:31'),(3,'地三鲜','10元','好吃不上火','2018年06月11日 01:02:37');
10、页面效果
简单的增删改,查询可以模糊查询。