SSM簡易專案(增刪改查)
阿新 • • 發佈:2019-01-27
本專案是一個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
目錄
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、頁面效果
簡單的增刪改,查詢可以模糊查詢。