ssm整合的增删改查

时间:2021-07-04 16:33:17

最近学了ssm框架,就简单写了一个mybatis+spring+springmvc的整合增删改查。

先建一个web项目

1.工程结构:

ssm整合的增删改查

ssm整合的增删改查

2.所需要的jar包:

ssm整合的增删改查

ssm整合的增删改查

3.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 开始spring的注解形式 -->
<context:annotation-config></context:annotation-config>
<!--告诉spring去哪里扫描 -->
<context:component-scan base-package="com"></context:component-scan>
<mvc:default-servlet-handler />
<!--配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///shop?characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 加载mybatis文件 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--指定mapperxml 文件的位置 -->
<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
<!-- 指定数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置别名 -->
<property name="typeAliasesPackage" value="com.ssm.model"></property>
</bean>
<!--mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- basePackage:指定sql映射文件/接口所在的包(自动扫描)dao -->
<property name="basePackage" value="com.ssm.mapper"></property>
</bean>
</beans>

4.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: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-4.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
   <!-- 注解驱动 -->
   <mvc:annotation-driven/>
   <!--扫描springmvc的注解  -->
   <context:component-scan base-package="com.ssm.controller"/>
   <!--开始springmvc的注解形式  -->
   
   <mvc:default-servlet-handler/>


    <!-- 配置spring mvc的视图解析器  -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <!--配置前缀  -->
     <property name="prefix" value="/"></property>
     <!--配置后缀  -->
     <property name="suffix" value=".jsp"></property>
   </bean>

</beans>

5.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>ssmproduct</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 指定spring applicationContext.xml 配置文件路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- spring监听 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  
  
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定spring mvc.xml 配置文件路径-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>     
      <url-pattern>/</url-pattern>    
  </servlet-mapping> 
</web-app>

6.实体类(Product)(ProductType)

public class Product {
private int pid;
private String proName;
private int saleCount;
private String image;
private double salePrice;
private String decript;
private int sortId;
private ProductType productType;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public int getSaleCount() {
return saleCount;
}
public void setSaleCount(int saleCount) {
this.saleCount = saleCount;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getSalePrice() {
return salePrice;
}
public void setSalePrice(double salePrice) {
this.salePrice = salePrice;
}
public String getDecript() {
return decript;
}
public void setDecript(String decript) {
this.decript = decript;
}
public int getSortId() {
return sortId;
}
public void setSortId(int sortId) {
this.sortId = sortId;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}

}

public class ProductType {
private int id;
private String typeName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}

}

7.Dao层

public interface ProductDao {
// 查询
public List<Product> listAll(Map map);
// 添加
public void save(Product product);
public Product getById(int pid);
// 修改
public void update(Product product);
// 删除
public void delete(int pid);

}

public interface ProductTypeDao {
//  查询类型
public List<ProductType> listAll();
public ProductType getById(int id);
}

8.mapper.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="com.ssm.mapper.ProductDao">
<insert id="save" parameterType="Product">
insert into product(proName,saleCount,image,salePrice,decript,sortId,typeId)
values(#{proName},#{saleCount},#{image},#{salePrice},#{decript},#{sortId},#{productType.id})
</insert>
<resultMap type="Product" id="ProductMap">
<result column="pid" property="pid" />
<result column="proName" property="proName" />
<result column="saleCount" property="saleCount" />
<result column="image" property="image" />
<result column="salePrice" property="salePrice" />
<result column="decript" property="decript" />
<result column="sortId" property="sortId" />
<association property="productType" column="typeId"
select="com.ssm.mapper.ProductTypeDao.getById"></association>
</resultMap>
<select id="listAll" resultMap="ProductMap" parameterType="java.util.Map">
select * from product
<where>
<if test="pname!=null">
and proName like  '%${pname}%'
</if>
</where>
</select>
<delete id="delete" parameterType="int">
delete   from product where pid=#{pid}
</delete>
<update id="update" parameterType="product">
update product set proName=#{proName},saleCount=#{saleCount},image=#{image},
salePrice=#{salePrice},decript=#{decript},sortId=#{sortId},typeId=#{productType.id}
where pid=#{pid}
</update>
<select id="getById" parameterType="int" resultMap="ProductMap">
   select * from product where pid=#{value}
</select>

</mapper>


<?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="com.ssm.mapper.ProductTypeDao">
<select id="getById" parameterType="int" resultType="ProductType">
select * from producttype where id=#{id}
</select>
<select id="listAll" resultType="ProductType">
select * from producttype
</select>

</mapper>

9.service层
public interface ProductService {   
//   查询
public List<Product> listAll(Map map);
//   添加
public void save(Product product);
public Product getById(int pid);
//   修改
public void update(Product product);
//   删除
public void delete(int pid);

}

public interface ProuctTypeService {
        public List<ProductType> listAll();
        public ProductType getById(int id);

}

10.Impl层

@Service
public class ProductServiceImpl implements ProductService{


@Autowired
private ProductDao ProductDao;  
@Override
public List<Product> listAll(Map map) {
List<Product> list=ProductDao.listAll(map);
return list;
}


@Override
public void save(Product product) {
ProductDao.save(product);


}


@Override
public Product getById(int pid) {
Product product=ProductDao.getById(pid);
return product;
}


@Override
public void update(Product product) {
ProductDao.update(product);


}
@Override
public void delete(int pid) {
ProductDao.delete(pid);
}

}

@Service
public class ProuctTypeServiceImpl implements ProuctTypeService{
    
@Autowired
private ProductTypeDao ProductTypeDao;
@Override
public List<ProductType> listAll() {
List<ProductType> list=ProductTypeDao.listAll();
return list;
}
@Override
public ProductType getById(int id) {
ProductType productType=ProductTypeDao.getById(id);
return productType;
}
}

11.controller层

@Controller
@RequestMapping("/product")
public class ProductController {
        
  @Autowired
  private ProductService ProductService;
  @Autowired
  private ProuctTypeService prouctTypeService;
  /*
   * 查询
   */
  @RequestMapping("/productlist")
       public ModelAndView listproduct(HttpServletRequest request) {
 ModelAndView mv=new ModelAndView();
 Map map=new HashMap<>();
 map=initMap(request, map);
 List<Product> list=ProductService.listAll(map);
 mv.addObject("list", list);
 mv.setViewName("productlist");
 return mv;
}
  
  
   private Map initMap(HttpServletRequest request,Map map) {
    String pname=request.getParameter("pname");
    map.put("pname", pname);
return map;
}
  
  
  /*
   * 删除
   */
  @RequestMapping("/delete")
  public String delete(int pid) {
 ProductService.delete(pid); 
 return "redirect:productlist";
}  
  /*
   * 添加
   */
  @RequestMapping("/addproduct")
  public String addproduct(Product product,int tid) {
  ProductType productType=new ProductType();
  productType.setId(tid);
  product.setProductType(productType); 
  ProductService.save(product);
  return "redirect:productlist";
}
  
  /*
   * 添加跳转
   */
  @RequestMapping("/toadd")
  public String toadd() {
 return "addProduct";
}
  /*
   * 商品类型查询
   */
  @RequestMapping("/listType")
  public ModelAndView listproType() {
 ModelAndView mv=new ModelAndView();
 List<ProductType> listType=prouctTypeService.listAll();
 mv.addObject("listType", listType);
 mv.setViewName("addProduct");
 return mv;
}
  
  /*
   * 修改 文本框复制
   */
  @RequestMapping("/toupdate")
  public ModelAndView toupdate(int pid) {
 ModelAndView mv=new ModelAndView();
 Product product=ProductService.getById(pid);
 List<ProductType> listType=prouctTypeService.listAll();
 mv.addObject("product", product);
 mv.addObject("listType", listType);
 mv.setViewName("addProduct");
 return mv;
}
  
  /*
   * 修改
   */
  @RequestMapping("/updateproduct")
  public String updatepro(Product product,int tid) {
ProductType productType=new ProductType();
productType.setId(tid);
product.setProductType(productType);
ProductService.update(product);
return "redirect:productlist";
}

12. jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品显示</title>
     <link rel="stylesheet" type="text/css" href="/ssmproduct/css/bootstrap.css"/>
     <script src="/ssmproduct/js/jquery.js" type="text/javascript" charset="utf-8"></script>
     <script src="/ssmproduct/js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
 
     <link rel="stylesheet" type="text/css" href="/ssmproduct/css/bootstrap-table.css"/>
     <script src="/ssmproduct/js/bootstrap-table.js" type="text/javascript" charset="utf-8"></script>
     <script src="/ssmproduct/js/bootstrap-table-zh-CN.js" type="text/javascript" charset="utf-8"></script>
</head>
<style type="text/css">
h2{
text-align: center;
}

#ptid{
width: 200px;
}
#qname{
width: 440px;
}
#search_btn{
width: 100px;
}
#container{
text-align: center;
}
#tab1{
width: 1000px;
text-align: center;
margin: 10px auto;
border: 1px solid gainsboro;
}
</style>
       <script type="text/jscript">
         function listype() {
          document.forms[0].action="/ssmproduct/product/listType";
          document.forms[0].submit();
         }
         
         function toseach() {
          document.forms[0].action="/ssmproduct/product/productlist";
            document.forms[0].submit();
  }
      </script> 
   
<body>
 <h2>商品展示</h2>
<div id="container">
   <form action="/ssmproduct/product/toadd" method="post" class="form-inline">
   <div class="form-group">
        <input type="button" onclick="listype()" class="btn btn-default" value="添加"/>
        </div>
        <div class="form-group">
<label for="exampleInputEmail1" for="qname">商品名称:</label>
        <input type="text" class="form-control" name="pname" id="pname" placeholder="请输入商品名称">
        </div>
   <%-- <div class="form-group">
<label for="exampleInputEmail3">商品类型:</label>
      <select name="tid" id="tid" class="form-control">
       <option value="-1">请选择</option>
       <c:forEach items="${typeList }" var="t">
       <option value="${t.id }">${t.typeName }</option>
       </c:forEach>
      </select>
      </div> --%>
        <button type="button" id="search_btn" onclick="toseach()" class="btn btn-default" value="查询">查询</button>
      <br><br> 
      <table class="table" border="1" width="100%" id="tab1" cellspacing="0" cellpadding="5">
              <tr>
              <td>商品编号</td>
              <td>商品名称</td>
              <td>销售数量</td>
              <td>商品图片</td>  
              <td>销售价格</td>
              <td>商品详情</td>
              <td>商品类型</td>
              <td>操      作</td>
              </tr>
              <c:forEach items="${list }" var="pro" varStatus="stat">
                <tr>
              <td>${stat.index+1 }</td>
              <td>${pro.proName }</td>
              <td>${pro.saleCount }</td>
              <td>${pro.image }</td>
              <td>${pro.salePrice }</td>
              <td>${pro.decript}</td>          
              <td>${pro.productType.typeName }</td>
              <td><a href="/ssmproduct/product/delete?pid=${pro.pid }">删除</a><a href="/ssmproduct/product/toupdate?pid=${pro.pid }">编辑</a></td>
              </tr>
              </c:forEach>
        </table>
         <%-- <a href="/ProductServlet?method=list&page=${page }&flag=up" class="btn-default form-control">上一页</a>
         <a href="/ProductServlet?method=list&page=${page }&flag=down" class="btn-default form-control">下一页</a> --%>
     </form>
     </div> 
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品操作</title>
    <link rel="stylesheet" type="text/css" href="/ssmproduct/css/bootstrap.css"/>
     <script src="/ssmproduct/js/jquery.js" type="text/javascript" charset="utf-8"></script>
     <script src="/ssmproduct/js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
 
     <link rel="stylesheet" type="text/css" href="/ssmproduct/css/bootstrap-table.css"/>
     <script src="/ssmproduct/js/bootstrap-table.js" type="text/javascript" charset="utf-8"></script>
     <script src="/ssmproduct/js/bootstrap-table-zh-CN.js" type="text/javascript" charset="utf-8"></script>
</head>
<style type="text/css">
h3{
text-align: center;
}

#ptid{
width: 200px;
}
#qname{
width: 440px;
}
#search_btn{
width: 100px;
}
#container{
text-align: center;
}
#tab1{
width: 1000px;
text-align: center;
margin: 10px auto;
border: 1px solid gainsboro;
}
#tid{
  width: 177px
}
</style>
<script type="text/javascript">


  function addpro() {
  document.forms[0].action="/ssmproduct/product/addproduct";
          document.forms[0].submit();  
}
  function updatepro() {
  document.forms[0].action="/ssmproduct/product/updateproduct";
      document.forms[0].submit();
}

</script>

<body>
<h3>商品操作</h3>
<div id="container">
   <form action="" method="post" class="form-inline">
        <c:if test="${product.pid !=null }">
         <input type="hidden" class="form-control" name="pid" id="pid" value="${product.pid }">
        </c:if>
   <div class="form-group">
<label for="exampleInputEmail1" for="qname">商品名称:</label>
        <input type="text" class="form-control" name="proName" id="proName" value="${product.proName }" placeholder="请输入商品名称"> <br>
   </div>
   <br><br>
   <div class="form-group">
<label for="exampleInputEmail1" for="qname">商品数量:</label>
        <input type="text" class="form-control" name="saleCount" id="saleCount" value="${product.saleCount }" placeholder="请输入商品数量"> 
   </div>
   <br><br>
   <div class="form-group">
<label for="exampleInputEmail1" for="qname">商品图片:</label>
        <input type="text" class="form-control" name="image" id="image" value="${product.image }" placeholder="请输入商品图片"> 
   </div>
   <br><br>
   <div class="form-group">
<label for="exampleInputEmail1" for="qname">销售价格 :</label>
        <input type="text" class="form-control" name="salePrice" id="salePrice" value="${product.salePrice }" placeholder="请输入商品价格"> 
   </div>
   <br><br>
   <div class="form-group">
<label for="exampleInputEmail1" for="qname">商品详情 :</label>
        <input type="text" class="form-control" name="decript" id="decript" value="${product.decript }" placeholder="请输入商品详情"> 
   </div>
   <br><br>
   <div class="form-group">
<label for="exampleInputEmail1" for="qname">商品排序 :</label>
        <input type="text" class="form-control" name="sortId" id="sortId" value="${product.sortId }" placeholder="请输入商品排序"> 
   </div>
   <br><br>
   <div class="form-group">
   <label for="exampleInputEmail1" for="qname">商品类型 :</label>  
       <select name="tid" class="form-control" id="tid">
            <option value="-1">请选择</option>
            <c:forEach items="${listType }" var="t">
            <option value="${t.id }">${t.typeName }</option>
            </c:forEach>
         </select><br>
   </div>
   <br><br>
        <button type="button" value="添加" class="btn btn-default" onclick="addpro()">添加</button>
        <button type="button" value="编辑" class="btn btn-default" onclick="updatepro()">编辑</button>
     </form>
     </div> 
     
     <script type="text/javascript">
     $(function(){
    $("#tid").val("${product.productType.id }");
     });
    /*  document.getElementById("tid").value = "${product.productType.id }"; */
     </script>
</body>
</html>