SSM的简例实现
这是项目完整代码的链接地址
[https://download.csdn.net/download/m0_46308149/12961224]源码地址
SSM介绍
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。关于spring、springMVC、mybatis一些具体内容大家可以查看其他博主的博客进行了解,在这里我不一一介绍
jdk版本是1.8
数据库是5.5.36
数据库软件是Navicat 15.0
Tomcat是15.0
Idea的版本是2019.3.2
目录列表
首先创建一个新项目,选择Maven,不用做任何选中操作,直接点击Next
选中GOOD,然后右键选择Add Framework Support…
选中Web Application,创建一个动态的web工程
创建数据库
在Navicat中点击新建查询,将下面的代码复制粘贴,然后运行即可
/*!40101 SET NAMES utf8 */;/*!40101 SET SQL_MODE=''*/;create database if not exists `ssm_shop`;USE `ssm_shop`;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*Table structure for table `brand` */CREATE TABLE `brand` (`id` int(11) NOT NULL AUTO_INCREMENT,`brand_name` varchar(32) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;/*Data for the table `brand` */insert into `brand`(`id`,`brand_name`) values (1,'李宁'),(2,'耐克');/*Table structure for table `brand_cate` */CREATE TABLE `brand_cate` (`id` int(11) NOT NULL AUTO_INCREMENT,`bid` int(11) DEFAULT NULL,`cid` int(11) DEFAULT NULL,PRIMARY KEY (`id`),KEY `FK_brand_cate` (`bid`),KEY `FK_brand_cate2` (`cid`),CONSTRAINT `FK_brand_cate` FOREIGN KEY (`bid`) REFERENCES `brand` (`id`),CONSTRAINT `FK_brand_cate2` FOREIGN KEY (`cid`) REFERENCES `cate` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;/*Data for the table `brand_cate` */insert into `brand_cate`(`id`,`bid`,`cid`) values (1,1,1),(2,1,2),(3,2,1),(4,2,2);/*Table structure for table `cate` */CREATE TABLE `cate` (`id` int(11) NOT NULL AUTO_INCREMENT,`cat_name` varchar(64) DEFAULT NULL,`cat_desc` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;/*Data for the table `cate` */insert into `cate`(`id`,`cat_name`,`cat_desc`) values (1,'服装','穿的'),(2,'运动器材','健身');/*Table structure for table `goods` */CREATE TABLE `goods` (`id` int(11) NOT NULL AUTO_INCREMENT,`goods_name` varchar(64) DEFAULT NULL,`goods_desc` varchar(255) DEFAULT NULL,`price` double DEFAULT NULL,`cat_id` int(11) DEFAULT NULL,`brand_id` int(11) DEFAULT NULL,`kcl` int(11) DEFAULT NULL,PRIMARY KEY (`id`),KEY `FK_goods` (`brand_id`),KEY `FK_goods2` (`cat_id`),CONSTRAINT `FK_goods` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`),CONSTRAINT `FK_goods2` FOREIGN KEY (`cat_id`) REFERENCES `cate` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;/*Data for the table `goods` */insert into `goods`(`id`,`goods_name`,`goods_desc`,`price`,`cat_id`,`brand_id`,`kcl`) values (1,'李宁跑鞋','跑步',999,1,1,1010),(2,'篮球','锻炼',300,2,2,1000),(3,'耐克球衣','打球专用',999,1,2,NULL);/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
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.ygkj</groupId><artifactId>GOODS</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.1.RELEASE</version></dependency><!-- <dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency>--><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.1.RELEASE</version></dependency><!-- mybatis核心包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><!-- mybatis/spring包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.2</version></dependency><!-- 导入java ee jar 包 --><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version></dependency><!-- 导入Mysql数据库链接jar包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.28</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.5</version></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.53</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.5</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.5</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.5</version></dependency></dependencies></project>
配置日志文件
在resources文件下创建log4j.properties
#
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
# 1. WARN (the least serious)
# 2. DEBUG
# 3. INFO
# 4. ERROR
# 5. FATAL (the most serious)log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%nlog4j.rootLogger=DEBUG, stdout
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.apache.struts2.dispatcher.ServletDispatcherResult=DEBUG
log4j.logger.org.ecside.core.TableModel=DEBUG# OpenSymphony Stuff
log4j.logger.com.opensymphony=WARN
log4j.logger.org.apache.struts2=WARN# Spring Stuff
log4j.logger.org.springframework=WARN
log4j.logger.org.enhydra.jdbc.xapool=WARN
log4j.logger.org.objectweb.jotm=WARN
log4j.logger.com.hangyjx.component.codetable=WARNlog4j.logger.com.hangyjx.core.dao.ibatis.ReflectUtil=WARN
log4j.logger.com.ibatis=WARN
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=WARN
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=WARN
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=WARN
log4j.logger.org.objectweb.carol.util.configuration.ConfigurationRepository=WARN
log4j.logger.com.ibatis.common.beans.ClassInfo=FATAL log4j.logger.com.hangyjx.common.sjdr.XxdrConfig=WARN
log4j.logger.org.ecside.core.TableModelUtils=WARN
log4j.logger.org.apache.struts2.config.Settings=ERROR
log4j.logger.org.directwebremoting=WARN
log4j.logger.freemarker.cache=WARN
log4j.logger.org.apache.commons.beanutils=WARN
com.hangyjx.core.dao.ibatis.LimitSqlExecutor=WARN
# Print only messages of level ERROR or above in the package noModule.
log4j.logger.noModule=WARN
配置数据源信息
在resources文件下创建db.properties
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ssm_shop
db.username=root
db.password=password
spring核心配置文件
beas.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:c="http://www.springframework.org/schema/c"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsd"><!--开启扫描包--><!--开启spring注解,扫描spring注解所在的包 --><context:component-scan base-package="com.ygkj"/><!--引入配置文件--><context:property-placeholder location="classpath:db.properties"/><!--配置数据源信息--><bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="${db.driver}"/><property name="url" value="${db.url}"/><property name="username" value="${db.username}"/><property name="password" value="${db.password}"/></bean><!--配置 mybatis 所需要的会话工厂--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--引入数据源--><property name="dataSource" ref="basicDataSource"/><!--mybatis 所需要的映射文件--><property name="mapperLocations" value="classpath:com/ygkj/mapper/*.xml"/></bean><!--mybatis 扫描器的配置--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--value mapper接口的包路径--><!--开启mybatis的扫描包,并且把包下面所有的接口创建每个接口所有的自己的实例对象--><!--扫描持久层的接口 并且通过代理模式创建出代理对象 交由spring容器管理--><property name="basePackage" value="com.ygkj.mapper"/></bean></beans>
springMVC配置文件
springmvc.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:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"><!--开启扫描包--><!--spring会自动扫描base-package下的子包或者包下的java文件,然后将有注解@Component @Controller@Service等的类,则把这些类注册为bean--><context:component-scan base-package="com.ygkj"/><!--过滤静态资源--><mvc:default-servlet-handler/><!--开启MVC注解的支持--><mvc:annotation-driven/><!--配置MVC视图解析器--><bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!--设置前缀--><property name="prefix" value="/jsp/"/><!--设置后缀--><property name="suffix" value=".jsp"></property></bean></beans>
web.xml配置文件
<?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"><!--配置mvc核心总控制器--><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--绑定mvc核心容器--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><!--设置启动级别--><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!--绑定spring核心容器--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:beans.xml</param-value></context-param><!--配置一个监听器 让项目启动的时候就加载spring核心容器--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--编码拦截器--><filter><filter-name>characterEncodingFilter</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><!--规范web项目的字符编码--><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>
根据数据库中的表创建实体类
1、创建实体类Goods(商品类)
package com.ygkj.pojo;import java.io.Serializable;public class Goods implements Serializable {private Integer gid;private String GoodsName;private String GoodDesc;private double price;// 分类的idprivate Integer catId;// 品牌的idprivate Integer brandId;// 库存量private Integer kcl;// 品牌实体类的引用private Brand brand;// 类别实体类的引用private Cate cate;public Goods(Integer gid, String goodsName, String goodDesc, double price, Integer catId, Integer brandId, Integer kcl, Brand brand, Cate cate) {this.gid = gid;GoodsName = goodsName;GoodDesc = goodDesc;this.price = price;this.catId = catId;this.brandId = brandId;this.kcl = kcl;this.brand = brand;this.cate = cate;}public Goods() {}public Integer getGid() {return gid;}public void setGid(Integer gid) {this.gid = gid;}public String getGoodsName() {return GoodsName;}public void setGoodsName(String goodsName) {GoodsName = goodsName;}public String getGoodDesc() {return GoodDesc;}public void setGoodDesc(String goodDesc) {GoodDesc = goodDesc;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public Integer getCatId() {return catId;}public void setCatId(Integer catId) {this.catId = catId;}public Integer getBrandId() {return brandId;}public void setBrandId(Integer brandId) {this.brandId = brandId;}public Integer getKcl() {return kcl;}public void setKcl(Integer kcl) {this.kcl = kcl;}public Brand getBrand() {return brand;}public void setBrand(Brand brand) {this.brand = brand;}public Cate getCate() {return cate;}public void setCate(Cate cate) {this.cate = cate;}@Overridepublic String toString() {return "Goods{" +"gid=" + gid +", GoodsName='" + GoodsName + '\'' +", GoodDesc='" + GoodDesc + '\'' +", price=" + price +", catId=" + catId +", brandId=" + brandId +", kcl=" + kcl +", brand=" + brand +", cate=" + cate +'}';}
}
2、创建实体类Brand(品牌类)
package com.ygkj.pojo;public class Brand {private Integer bid;private String brandName;public Brand(Integer bid, String brandName) {this.bid = bid;this.brandName = brandName;}public Brand() {}public Integer getBid() {return bid;}public void setBid(Integer bid) {this.bid = bid;}public String getBrandName() {return brandName;}public void setBrandName(String brandName) {this.brandName = brandName;}@Overridepublic String toString() {return "Brand{" +"bid=" + bid +", brandName='" + brandName + '\'' +'}';}
}
3、创建实体类Cate(分类类)
package com.ygkj.pojo;public class Cate {private Integer cid;private String catName;private String catDesc;public Cate(Integer cid, String catName, String catDesc) {this.cid = cid;this.catName = catName;this.catDesc = catDesc;}public Cate() {}public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getCatName() {return catName;}public void setCatName(String catName) {this.catName = catName;}public String getCatDesc() {return catDesc;}public void setCatDesc(String catDesc) {this.catDesc = catDesc;}@Overridepublic String toString() {return "Cate{" +"cid=" + cid +", catName='" + catName + '\'' +", catDesc='" + catDesc + '\'' +'}';}
}
控制层
创建GoodsController类
package com.ygkj.controller;import com.ygkj.pojo.Brand;
import com.ygkj.pojo.Cate;
import com.ygkj.pojo.Goods;
import com.ygkj.service.GoodsService;
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.ResponseBody;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;@Controller
@RequestMapping("/goods") //用于地址映射
public class GoodsController {@Autowiredprivate GoodsService goodsService;/*** 查询所有商品信息* @return*/@RequestMapping("/list")public String getList(Model model){List<Goods> goodsList = goodsService.getList();List<Brand> brandList = goodsService.findAllByBrand();List<Cate> cateList = goodsService.findAllByCate();model.addAttribute("goodsList",goodsList);model.addAttribute("brandList",brandList);model.addAttribute("cateList",cateList);return "list";}/*** 查询所有品牌信息* @return* @ResponseBody 让当前视图失效,并且以json格式向当前视图传递数据*/@RequestMapping("/listBrand")@ResponseBodypublic List<Brand> findAllByBrand(){// 查询品牌List<Brand> brandList = goodsService.findAllByBrand();return brandList;}/*** 查询所有类别信息* @return*/@RequestMapping("/listCate")public String findAllByCate(Model model){List<Cate> goodsList = goodsService.findAllByCate();model.addAttribute("goodsList",goodsList);return "list";}/*** 修改库存量* @return*/@RequestMapping("/updateKc")public String updateKc(Goods goods, HttpServletResponse httpServletResponse){// 执行修改库存量的方法Integer num = goodsService.updateKc(goods);try {if (num > 0){System.out.println("库存修改成功");httpServletResponse.getWriter().print("true");}else {System.out.println("库存修改失败");httpServletResponse.getWriter().print("false");} } catch (IOException e) {e.printStackTrace();}return null;}/*** 执行商品上架操作* 1.如果商品在数据库中存在的话,库存加一* 2.如果不存在,就添加* @return*/@RequestMapping("/toAdd")public String toAdd(Goods goods,HttpServletResponse httpServletResponse){if (goods != null){Integer num = goodsService.toAdd(goods);try {if (num == 1){// 执行保存操作成功给前端响应的数据httpServletResponse.getWriter().print("1");}else if (num ==2){// 执行修改库存操作成功给前端响应的数据httpServletResponse.getWriter().print("2");}} catch (IOException e) {e.printStackTrace();}}return null;}@RequestMapping("/toDelete")public String toDelete(Integer gid, HttpServletResponse httpServletResponse){Integer num = goodsService.toDelete(gid);try {if (num == 1){httpServletResponse.getWriter().print("true");}else {httpServletResponse.getWriter().print("false");}} catch (IOException e) {e.printStackTrace();}return null;}/*** 查询所有类别的信息* @param gid* @return*/@RequestMapping("/showGoodsByGid")@ResponseBodypublic Goods showGoodsByGid(Integer gid){Goods goods = goodsService.showGoodsByGid(gid);// 以json的数据格式响应给ajaxreturn goods;}/*** 修改商品信息* @param goods* @return*/@RequestMapping("/toUpdate")public String toUpdate(Goods goods, HttpServletResponse httpServletResponse){Integer num = goodsService.toUpdate(goods);try {if (num == 1){httpServletResponse.getWriter().print("true");}else {httpServletResponse.getWriter().print("true");}} catch (IOException e) {e.printStackTrace();}return null;}}
业务逻辑层
业务逻辑层接口
package com.ygkj.service;import com.ygkj.pojo.Brand;
import com.ygkj.pojo.Cate;
import com.ygkj.pojo.Goods;import java.util.List;public interface GoodsService {List<Goods> getList();List<Brand> findAllByBrand();List<Cate> findAllByCate();Integer updateKc(Goods goods);Integer toAdd(Goods goods);Integer toDelete(Integer gid);Goods showGoodsByGid(Integer gid);Integer toUpdate(Goods goods);
}
业务逻辑层的实现类
package com.ygkj.service.impl;import com.ygkj.mapper.BrandMapper;
import com.ygkj.mapper.CateMapper;
import com.ygkj.mapper.GoodsMapper;
import com.ygkj.pojo.Brand;
import com.ygkj.pojo.Cate;
import com.ygkj.pojo.Goods;
import com.ygkj.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;//业务层@Service
public class GoodsServiceImpl implements GoodsService {@Autowiredprivate GoodsMapper goodsMapper;@Autowiredprivate BrandMapper brandMapper;@Autowiredprivate CateMapper cateMapper;public List<Goods> getList() {List<Goods> goodsList = goodsMapper.getList();return goodsList;}/*** 查询所有品牌* @return*/public List<Brand> findAllByBrand() {return brandMapper.findAllByBrand();}public List<Cate> findAllByCate() {return cateMapper.findAllByCate();}/*修改库存*/public Integer updateKc(Goods goods) {return goodsMapper.updateKc(goods);}/*执行添加操作*/public Integer toAdd(Goods goods) {/** 去数据库查询当前商品是否存在* */Goods g1 = goodsMapper.findGoodsByName(goods);int flag = 0;if (g1 == null){// 执行添加flag = goodsMapper.toAdd(goods);}else {// 商品存在 根据商品名称获取对应的主键idInteger gid = goodsMapper.findNameById(goods);// 根据id执行修改库存操作int num = goodsMapper.updateKcByGid(gid);if (num == 1){// 修改成功,响应一个flag给前端flag = 2;}}return flag;}/*** 商品下架* @param gid* @return*/public Integer toDelete(Integer gid) {return goodsMapper.toDelete(gid);}/*** 回显商品信息* @param gid* @return*/public Goods showGoodsByGid(Integer gid) {return goodsMapper.showGoodsByGid(gid);}/*** 修改商品信息* @param goods* @return*/public Integer toUpdate(Goods goods) {return goodsMapper.toUpdate(goods);}
}
持久层
1、GoodsMapper
package com.ygkj.mapper;//持久层//这个注解可加可不加,这个注解只是起到一个表示的作用
//这个接口的实现类对象是通过动态代理的形式创建出来的import com.ygkj.pojo.Goods;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface GoodsMapper {/*** 查询所有商品信息* @return*/List<Goods> getList();/*** 修改库存* @param goods* @return*/Integer updateKc(Goods goods);/*** 执行添加操作* @param goods* @return*/Integer toAdd(Goods goods);Goods findGoodsByName(Goods goods);/*** 根据id查找当前商品是否存在* @param goods* @return*/Integer findNameById(Goods goods);/*** 根据id修改库存* @param gid* @return*/Integer updateKcByGid(Integer gid);/*** 商品下架* @param gid* @return*/Integer toDelete(Integer gid);Goods showGoodsByGid(Integer gid);/*** 修改商品信息* @param goods* @return*/Integer toUpdate(Goods goods);}
2、BrandMapper
package com.ygkj.mapper;import com.ygkj.pojo.Brand;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface BrandMapper {/*** 查询所有品牌信息* @return*/List<Brand> findAllByBrand();}
3、CateMapper
package com.ygkj.mapper;import com.ygkj.pojo.Cate;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface CateMapper {/*** 查询所有类别信息* @return*/List<Cate> findAllByCate();
}
前端页面
list.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><%/*获取到web端的绝对路径 映射到工程的web文件夹*/String path = request.getContextPath();
%>
<link rel="stylesheet" href="<%=path%>/css/css.css">
<%--//导入js控件--%>
<script src="../js/jquery-1.7.2.js"></script><script type="text/javascript">/*跳转add界面*/function toAdd() {//跳转add界面location.href="<%=path%>/jsp/add.jsp"}//减库存function minKc(gid,kcl) {//当前库存量-1kcl = kcl - 1;//根据ajax修改数据库中的数据$.ajax({//请求的地址url:"<%=path%>/goods/updateKc",//提交的类型type:"post",//请求的数据data:{kcl:kcl,gid:gid},success:function(obj){if (obj){location.href = "<%=path%>/goods/list"}else{alert("数据库更新失败")}},//返回值类型dataType:"json"})}//加库存function maxKc(gid,kcl) {//当前库存量+1kcl = Number(kcl) + Number(1);//根据ajax修改数据库中的数据$.ajax({//请求的地址url:"<%=path%>/goods/updateKc",//提交的类型type:"post",//请求的数据data:{kcl:kcl,gid:gid},//请求成功之后的回调函数success:function(obj){if (obj){location.href="<%=path%>/goods/list"}else {alert("库存修改失败")}},//返回值类型dataType:"json"})}function toDelete(gid) {$.ajax({url:"<%=path%>/goods/toDelete",type:"post",data:{gid:gid},success:function (obj) {if (obj){alert("商品已下架")location.href="<%=path%>/goods/list";}else {alert("商品下架失败")}},dataType:"json"})}/*跳转到修改界面*/function toUpdate(gid) {//跳转修改界面location.href = "<%=path%>/jsp/update.jsp?gid="+gid;}</script><body><h1 style="font-size: 30px" align="center">商品列表界面</h1><table border="1px"><tr><td colspan="10" align="center"><input type="button" value="商品上架" onclick="toAdd()"/><input type="button" value="批量删除"/><input type="button" value="全选"/><input type="button" value="全不选"/><input type="button" value="反选"/></td></tr><tr><th>商品名称</th><th>商品描述</th><th>价格</th><th>分类</th><th>品牌</th><th>库存量</th><th>操作</th></tr><c:forEach items="${goodsList}" var="good"><tr><td>${good.goodsName}</td><td>${good.goodDesc}</td><td>${good.price}</td><td><c:forEach items="${cateList}" var="cate"><c:if test="${cate.cid == good.catId}"><%--显示分类--%>${cate.catName}</c:if></c:forEach></td><td><c:forEach items="${brandList}" var="brand"><c:if test="${brand.bid == good.brandId}"><%--显示品牌--%>${brand.brandName}</c:if></c:forEach></td><td><input type="button" value="-" onclick="minKc(${good.gid},${good.kcl})"><input id="kcl" type="text" value="${good.kcl}"><input type="button" value="+" onclick="maxKc(${good.gid},${good.kcl})"></td><td><input type="button" value="信息修改" onclick="toUpdate(${good.gid})"><input type="button" value="商品下架" onclick="toDelete(${good.gid})"></td></tr></c:forEach></table></body>
</html>
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><%String path = request.getContextPath();
%>
<%--导入css样式--%>
<link rel="stylesheet" href="<%=path%>/css/css.css">
<%--//导入js控件--%>
<script src="../js/jquery-1.7.2.js"></script><script type="text/javascript">//文本就绪函数$(function () {//通过ajax异步的去请求数据 完成品牌下拉框的追加$.ajax({//请求的地址url:"<%=path%>/goods/listBrand",//请求的方式type:"post",//请求到后端的数据 可以不写success:function (obj) {//请求成功之后返回的回调函数for (var i in obj) {$("#bid").append("<option value='"+obj[i].bid+"'>"+obj[i].brandName+"</option>")}},//预期服务器返回的数据类型dataType:"json"})})//执行保存的操作function add() {$.ajax({//请求的地址url:"<%=path%>/goods/toAdd",//请求的方式type:"post",// 请求到后端的数据//data:$("form").serialize() 表单序列化data:$("form").serialize(),//请求成功之后返回的回调函数success:function (obj) {if (obj == "1"){alert("商品上架成功")location.href="<%=path%>/goods/list";}else if (obj == "2"){alert("该商品目前已上架,已成功修改库存,有问题请联系管理员或客服")location.href="<%=path%>/goods/list";}},//预期服务器返回的数据类型dataType:"json"})}</script><body><h1 style="font-size: 30px" align="center">商品上架</h1><form><table align="center"><tr><td>商品名称</td><td><input type="text" name="GoodsName"/></td></tr><tr><td>价格</td><td><input type="text" name="price"/></td></tr><tr><td>分类</td><td><input type="radio" name="catId" value="1"/>服装<input type="radio" name="catId" value="2"/>运动器材<input type="radio" name="catId" value="3"/>电子产品</td><tr><tr><td>商品描述</td><td><textarea name="GoodDesc"></textarea></td></tr><tr><td>所属品牌</td><td><select id="bid" name="brandId"><option>---请选择---</option></select></td></tr><tr><th>库存量</th><td><input type="text" name="kcl"></td><tr><td colspan="12" align="center"><input type="button" value="保存" onclick="add()"></td></tr></table>
</form></body>
</html>
update.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><%String path = request.getContextPath();
%>
<%--导入css样式--%>
<link rel="stylesheet" href="<%=path%>/css/css.css">
<%--//导入js控件--%>
<script src="../js/jquery-1.7.2.js"></script><script type="text/javascript">/*文本就绪函数*/$(function () {//通过ajax异步的去请求数据 完成品牌下拉框的追加$.ajax({//请求的地址url: "<%=path%>/goods/listBrand",//请求的方式type: "post",//请求到后端的数据 可以不写//请求成功之后返回的回调函数success:function (obj) {for (var i in obj){$("#bid").append("<option value='"+obj[i].bid+"'>"+obj[i].brandName+"</option>")}},//预期服务器返回的数据类型dataType: "json"})// 完成商品信息的回显// 1. 接收主键id param用于页面与页面之间数据的传输var gid = ${param.gid}// 2. 根据ajax完成商品信息的回显$.ajax({url:"<%=path%>/goods/showGoodsByGid",type:"post",data:{gid:gid},success:function (obj) {// obj是一个以字符串存在的对象// 回显商品名称$("[name = 'GoodsName']").val(obj.goodsName)//设置商品描述的文本内容,根据html()方法,设置文本域的文本内容$("[name = 'GoodDesc']").html(obj.goodDesc)//回显价格$("[name = 'price']").val(obj.price)//类别的回显$("[name = 'catId'][value='"+obj.catId+"']").prop("checked",true)//回显品牌$("[name = 'brandId']").val(obj.brandId)//回显库存量$("[name = 'kcl']").val(obj.kcl)},dataType:"json"})})// 3.执行修改的操作function update() {$.ajax({// 请求的路径url:"<%=path%>/goods/toUpdate",// 请求的方式type:"post",// 请求到后端的数据// $("form").serialize() 表单序列化 {GoodsName: 手机}data:$("form").serialize(),// 请求成功之后返回的回调函数success:function (obj) {if (obj){alert("商品信息修改成功")location.href="<%=path%>/goods/list";}else {alert("商品信息修改异常")location.href="<%=path%>/jsp/update.jsp";}},// 预期服务器返回的数据类型dataType:"json"})}</script><body><h1 style="font-size: 30px" align="center">修改商品信息</h1><form><table align="center"><input type="hidden" name="gid" value="${param.gid}"><tr><td>商品名称</td><td><input type="text" name="GoodsName"></td></tr><tr><td>价格</td><td><input type="text" name="price"></td></tr><tr><td>分类</td><td><input type="radio" name="catId" value="1">服装<input type="radio" name="catId" value="2">运动器材<input type="radio" name="catId" value="3">电子产品</td><tr><tr><td>商品描述</td><td><textarea name="GoodDesc"></textarea></td></tr><tr><td>所需品牌</td><td><select id="bid" name="brandId"><option>---请选择---</option></select></td></tr><tr><td>库存量</td><td><input type="text" name="kcl"></td><tr><td colspan="12" align="center"><input type="button" value="修改" onclick="update()"></td></tr></table></form></body>
</html>
CSS样式
@charset "UTF-8";form {margin: 0px;
}img {border: medium none;margin: 0;padding: 0;
} /* img elements 图片元素 */
/** 设置默认字体 **/
body,button,input,select,textarea {font-size: 12px;font: 12px/1.5 ’宋体’, Arial, tahoma, Srial, helvetica, sans-serif;
}h1,h2,h3,h4,h5,h6 {font-size: 100%;
}em {font-style: normal;
}
/** 重置列表元素 **/
ul,ol {list-style: none;
}
/** 重置超链接元素 **/
a {text-decoration: none;color: #4f4f4f;
}a:hover {text-decoration: underline;color: #F40;
}
/** 重置图片元素 **/
img {border: 0px;margin-bottom: -7px;
}body {width: 80%;margin: 40px auto;font-family: 'trebuchet MS', 'Lucida sans', Arial;font-size: 14px;color: #444;background: url(../css/img/body1.jpg);background-repeat: no-repeat;background-size: 100% auto;/* background: #F5F5F5; */
}table {border: solid #ccc 1px;-webkit-border-radius: 6px;border-radius: 6px;/* -webkit-box-shadow: 0 1px 1px #ccc;box-shadow: 0 1px 1px #ccc; */-webkit-box-shadow: 0px 2px 1px 5px rgba(242, 242, 242, 0.1);box-shadow: 5px 20px 30px 30px rgba(242, 242, 242, 0.1);width: 100%;
}table thead th {background:url(../css/img/zebratable.png);background-repeat:no-repeat;background-position: 0px center;
}table tr {background: #D5EAF0;-webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, .8) inset;box-shadow: 0 1px 0 rgba(255, 255, 255, .8) inset;
}table tr:nth-child(even) {background: #D7E1C5;-webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, .8) inset;box-shadow: 0 1px 0 rgba(255, 255, 255, .8) inset;
}table td,table th {border-left: 1px solid #ccc;border-top: 1px solid #ccc;padding: 10px;text-align: center;
}table th {background-color: #66a9bd;background-image: -moz-linear-gradient(top, #dce9f9, #66a9bd);-webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, .8) inset;box-shadow: 0 1px 0 rgba(255, 255, 255, .8) inset;border-top: none;text-shadow: 0 1px 0 rgba(255, 255, 255, .5);
}table td:first-child,table th:first-child {border-left: none;
}table th:first-child {-webkit-border-radius: 6px 0 0 0;border-radius: 6px 0 0 0;
}table th:last-child {-webkit-border-radius: 0 6px 0 0;border-radius: 0 6px 0 0;
}table th:only-child {-webkit-border-radius: 6px 6px 0 0;border-radius: 6px 6px 0 0;
}table tr:last-child td:first-child {-webkit-border-radius: 0 0 0 6px;border-radius: 0 0 0 6px;
}table tr:last-child td:last-child {-webkit-border-radius: 0 0 6px 0;border-radius: 0 0 6px 0;
}input[type="button"],input[type="submit"],input[type="reset"] {border: solid #ccc 1px;-webkit-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 0 1px 1px #ccc;box-shadow: 0 1px 1px #ccc;background: #B0CC7F;margin: 0 2px 0;
}input[type="text"],input[type="password"] {border: solid #ccc 2px;-webkit-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 0 1px 1px #ccc;box-shadow: 0 1px 1px #ccc;background: #efefef;margin: 0 2px 0;text-indent: 5px;
}
select {width:200px;border: solid #ccc 2px;-webkit-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 0 1px 1px #ccc;background: #efefef;margin: 0 2px 0;text-indent: 5px;
}
option {width:180px;border: solid #ccc 2px;-webkit-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 0 1px 1px #ccc;background: #efefef;margin: 0 2px 0;text-indent: 5px;
}input[name="page.now"] {border: solid #ccc 1px;-webkit-border-radius: 6px;border-radius: 6px;-webkit-box-shadow: 0 1px 1px #ccc;box-shadow: 0px 0px 0px #CEB754;background: #D5EAF0;margin: 0px 10px 0px 0px;padding-bottom: 0px;padding-top: 5px; width: 24px; line-height:10px; height: 12xp;
}
还有jQuery控件 jquery-1.7.2.js,只是由于博客的字数的限制问题不能发出来
Tomcate启动前配置
在WEB-INF文件夹下创建lib文件夹