最近搞了一下Maven依赖管理工具,今天更新一篇把Maven工具运用到SSM项目的博客(其实是为了水一篇文章 /捂脸/捂脸)。
阅读此博客需要一定的SSM框架(Spring、SpringMVC、Mybatis框架),以及Maven工具的知识,最好跟着做一遍操作。
注意:这里演示的是将mapper(dao)、service、web三层分为三个功能独立的模块。
一、创建根项目
1、创建项目maven_ssm_parent
删除src
目录
2、在pom.xml中添加依赖
<!-- key-value指定形式 -->
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
<springmvc.version>5.0.2.RELEASE</springmvc.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<!-- 锁定ssm三大框架的版本 -->
<dependencyManagement>
<dependencies>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springmvc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Mybatis 和 mybatis 与 spring 的整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- MySql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!-- druid 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springmvc.version}</version>
</dependency>
<!-- spring 相关 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<!-- spring 相关 事务相关 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<!-- junit 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<!-- 配置tomcat插件、jdk版本 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
二、创建mapper子模块(也称dao层)
1、添加maven_ssm_mapper
子模块
2、编写Java代码
①Product
实体类
package cn.hestyle.demo.entity;
import java.io.Serializable;
import java.util.Date;
/**
* description: Product实体类
*
* @author hestyle
* @version 1.0
* @className ssm_demo_01->Product
* @date 2020-01-30 10:30
**/
public class Product implements Serializable {
private Integer id;
/**商品名*/
private String name;
/**商品价格*/
private Double price;
/**商品库存数量*/
private Integer number;
/**商品简介*/
private String info;
/**商品照片路径*/
private String picturePath;
/**商品创建时间*/
private Date createdTime;
public Product() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", number=" + number +
", info='" + info + '\'' +
", picturePath='" + picturePath + '\'' +
", createdTime=" + createdTime +
'}';
}
}
②ProductMapper
接口类
package cn.hestyle.demo.mapper;
import cn.hestyle.demo.entity.Product;
import java.util.List;
/**
* description: ProductMapper接口类,相当于IProductDao接口类
*
* @author hestyle
* @version 1.0
* @className ssm_demo_01->ProductMapper
* @date 2020-01-30 10:36
**/
public interface ProductMapper {
/**
* 保存product
* @param product 待保存的product实体对象
* @return 受影响的行数
*/
public Integer save(Product product);
/**
* 更新product
* @param product 待更新的product实体对象
* @return 受影响的行数
*/
public Integer update(Product product);
/**
* 通过id删除product
* @param id 待删除的product实体对象id
* @return 受影响的行数
*/
public Integer deleteById(Integer id);
/**
* 通过id查找product
* @param id 待删除的product实体对象id
* @return 查找到的实体对象
*/
public Product findById(Integer id);
/**
* 查找所有product
* @return Product list
*/
public List<Product> findAll();
}
3、编写配置文件
①、数据库配置文件db.properties
# MySQL数据库驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
# ssm_demo_01数据库名称
jdbc.url=jdbc:mysql://localhost:3306/ssm_demo_01
# 连接数据库的账号、密码
jdbc.username=root
jdbc.password=123456
建表建库的脚本,拿到mysql图形化界面管理工具去执行
# 创建ssm_demo_01数据库
DROP DATABASE IF EXISTS `ssm_demo_01`;
CREATE DATABASE `ssm_demo_01`;
USE `ssm_demo_01`;
# 创建t_product表
CREATE TABLE `t_product`(
`id` int PRIMARY KEY auto_increment,
`name` VARCHAR(32) COMMENT '产品名称',
`price` double COMMENT '产品价格',
`number` int COMMENT '库存数量',
`info` VARCHAR(200) COMMENT '产品简介',
`picture_path` VARCHAR(100) COMMENT '产品照片路径',
`created_time` date COMMENT '产品创建时间'
);
# 插入几条测试数据
INSERT INTO `t_product`(`name`,`price`,`number`,`info`,`picture_path`,`created_time`)
VALUES('电脑','5000.5','50','性能吊打苹果!',NULL, now()),('手机','2000.9','20','性价比第一!',NULL, now()),('平板','32000.9','40','性能宇宙第一!',NULL, now());
②、mapper层spring配置文件applicationContext-dao.xml
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 1.加载db配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.配置Druid数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="1"/>
<property name="maxActive" value="10"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="removeAbandonedTimeout" value="5000"/>
</bean>
<!-- 3.让spring管理sqlsessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 指定映射文件位置 -->
<property name="mapperLocations" value="classpath*:mappers/*.xml"/>
</bean>
<!-- 4.配置mapper扫描器.批量扫描创建代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.hestyle.demo.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
</bean>
</beans>
③、mapper
映射文件(Mybatis)
<?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">
<!--
namespace:命名空间,它的作用就是对SQL进行分类化管理,可以理解为SQL隔离
注意:使用mapper代理开发时,namespace有特殊且重要的作用
-->
<mapper namespace="cn.hestyle.demo.mapper.ProductMapper">
<!--
保存product对象, public Integer save(Product product);
[id]:statement的id,要求在命名空间内唯一
keyProperty="id" useGeneratedKeys="true"用于设置自动增长标识(id字段自动增长)
[parameterType]:入参的java类型
-->
<insert id="save" keyProperty="id" useGeneratedKeys="true" parameterType="cn.hestyle.demo.entity.Product">
INSERT INTO `t_product`(
`name`, `price`, `number`, `info`, `picture_path`, `created_time`
) VALUES (
#{name},#{price},#{number},#{info},#{picturePath},#{createdTime}
)
</insert>
<!--
更新product对象, public Integer update(Product product);
注意created_time不用更新,可以在表中增加一个modify_time字段,trim的作用是删除最后一个逗号
-->
<update id="update" parameterType="cn.hestyle.demo.entity.Product">
UPDATE `t_product`
<trim prefix="set" suffixOverrides=",">
<if test="name != null">
`name` = #{name},
</if>
<if test="price != null">
`price` = #{price},
</if>
<if test="number != null">
`number` = #{number},
</if>
<if test="info != null">
`info` = #{info},
</if>
<if test="picturePath != null">
`picture_path` = #{picturePath},
</if>
</trim>
WHERE id = #{id}
</update>
<!--
通过id删除product对象,public Integer deleteById(Integer id);
注意这里可以不用真的删除,可以在表中增加一个is_del字段记录是否删除
-->
<delete id="deleteById" parameterType="java.lang.Integer">
DELETE FROM `t_product`
WHERE id = #{id}
</delete>
<!--
通过id查找Product表, public Product findById(Integer id);
由于表中的picture_path、created_time字段与Product实体类中的picturePath、createdTime属性不对应,所以需要手动指定映射关系
-->
<select id="findById" parameterType="java.lang.Integer" resultType="cn.hestyle.demo.entity.Product">
SELECT `id`, `name`, `price`, `number`, `info`, `picture_path` picturePath, `created_time` createdTime
FROM `t_product`
WHERE id = #{id}
</select>
<!--
查找product表所有记录,public List<Product> findAll();
由于表中的picture_path、created_time字段与Product实体类中的picturePath、createdTime属性不对应,所以需要手动指定映射关系
虽然指定的返回类型是Product,不过这里可能会查到多条数据,因此会自动转化成list
-->
<select id="findAll" resultType="cn.hestyle.demo.entity.Product">
SELECT `id`, `name`, `price`, `number`, `info`, `picture_path` picturePath, `created_time` createdTime
FROM `t_product`
</select>
</mapper>
三、创建service子模块(也称service层)
1、添加maven_ssm_service
子模块
2、将mapper层导入service依赖中
<dependencies>
<dependency>
<groupId>cn.hestyle</groupId>
<artifactId>maven_ssm_mapper</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
3、编写Java代码
①IProductService
接口类
package cn.hestyle.demo.service;
import cn.hestyle.demo.entity.Product;
import java.util.List;
/**
* description: IProductService接口类
*
* @author hestyle
* @version 1.0
* @className ssm_demo_01->IProductService
* @date 2020-01-30 11:10
**/
public interface IProductService {
/**
* 保存product
* @param product 待保存的product实体对象
* @return 受影响的行数
*/
public Integer save(Product product);
/**
* 更新product
* @param product 待更新的product实体对象
* @return 受影响的行数
*/
public Integer update(Product product);
/**
* 通过id删除product
* @param id 待删除的product实体对象id
* @return 受影响的行数
*/
public Integer deleteById(Integer id);
/**
* 通过id查找product
* @param id 待删除的product实体对象id
* @return 查找到的实体对象
*/
public Product findById(Integer id);
/**
* 查找所有product
* @return Product list
*/
public List<Product> findAll();
}
②ProductServiceImpl
实现类
4、编写配置文件
①service层spring配置文件applicationContext-service.xml
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 6.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 7.开启事务注解-->
<tx:annotation-driven></tx:annotation-driven>
<context:component-scan base-package="cn.hestyle.demo.service"/>
</beans>
四、创建web子模块
1、添加maven_ssm_web
子模块
2、添加service子模块依赖
<?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>cn.hestyle</groupId>
<artifactId>maven_ssm_web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<!-- web层依赖service层 -->
<groupId>cn.hestyle</groupId>
<artifactId>maven_ssm_service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- springmvc处理上传文件依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</project>
3、编写Java代码
①、新建src/main/java
文件夹
②、新建ProductController
类
package cn.hestyle.demo.web.controller;
import cn.hestyle.demo.entity.Product;
import cn.hestyle.demo.service.IProductService;
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.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* description: ProductController控制器
*
* @author hestyle
* @version 1.0
* @className ssm_demo_01->ProductController
* @date 2020-01-30 11:19
**/
@Controller
@RequestMapping("product")
public class ProductController {
@Autowired
private IProductService productService;
@RequestMapping("add.do")
public String add() {
//跳转到/product/add.jsp页面
return "/product/add";
}
@RequestMapping("save.do")
public String save(Product product) {
System.err.println("保存 " + product);
product.setCreatedTime(new Date());
productService.save(product);
//保存product后,重定向到listAll
return "redirect:listAll.do";
}
@RequestMapping("edit.do")
public String edit(Integer id, Model model) {
//通过model传入product到/product/edit.jsp页面
Product product = productService.findById(id);
System.err.println("通过id = " + id + "查找 " + product);
model.addAttribute("product", product);
return "/product/edit";
}
@RequestMapping("update.do")
public String update(Product product) {
System.err.println("更新" + product);
productService.update(product);
//保存更新后,重定向到/product/listAll.do
return "redirect:listAll.do";
}
@RequestMapping("delete.do")
public String delete(Integer id) {
System.err.println("通过id = " + id + "删除");
productService.deleteById(id);
//删除product后,重定向到listAll
return "redirect:listAll.do";
}
@RequestMapping("detail.do")
public String detail(Integer id, Model model) {
//通过model传入product到/product/detail.jsp页面
Product product = productService.findById(id);
System.err.println("通过id = " + id + "查找 " + product);
model.addAttribute("product", product);
return "/product/detail";
}
@RequestMapping("listAll.do")
public String listAll(Model model) {
//通过model传入productList到/product/listAll.jsp页面
List<Product> productList = productService.findAll();
System.err.println("查找所有product " + productList);
model.addAttribute("productList", productList);
return "/product/listAll";
}
@RequestMapping("uploadPicture.do")
public void uploadPicture(MultipartFile pictureFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("contentType", "text/json,charset=utf-8");
// 1、判断文件是否为空,空则返回失败页面
if (pictureFile.isEmpty()) {
response.getWriter().write("{\"code\":500,\"msg\":\"文件为空!\"}");
return;
}
// 2、获取文件存储路径(绝对路径)
String path = request.getServletContext().getRealPath("/picture/product");
// 获取原文件扩展名
String[] tempStrings = pictureFile.getOriginalFilename().split("\\.");
String suffix = tempStrings[tempStrings.length - 1].toLowerCase();
if (!"png".equals(suffix) && !"jpg".equals(suffix) && !"jpeg".equals(suffix) ) {
response.getWriter().write("{\"code\":500,\"msg\":\"只允许上传png、jpg、jpeg格式的文件!\"}");
return;
}
String fileName = UUID.randomUUID().toString() + "." + suffix;
// 3、创建文件实例
File filePath = new File(path, fileName);
// 如果文件目录不存在,创建目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
System.err.println("创建文件" + filePath.getAbsolutePath());
// 4、写入文件
pictureFile.transferTo(filePath);
// 5、把文件存放的项目相对路径返回
response.getWriter().write("{\"code\":200,\"msg\":\"/picture/product/" + fileName + "\"}");
}
}
4、导入JQuery
库
5、编写前端页面
①add.jsp
页面
<%--
Created by IntelliJ IDEA.
User: hestyle
Date: 2020/1/30
Time: 11:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加产品</title>
<script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script>
function upload() {
//从id=pictureFile的input标签获取选中的文件,然后组成form,提交到uploadPicture.do
var pictureForm = new FormData();
pictureForm.append("pictureFile", document.getElementById("pictureFile").files[0]);
$.ajax({
"url" : "${pageContext.request.contextPath}/product/uploadPicture.do",
"data" : pictureForm,
"type" : "POST",
"contentType": false,/*上传文件必须要的*/
"processData": false,/*上传文件必须要的*/
"dataType" : "json",
"success" : function (json) {
if (json.code === 200) {
//如果提交成功,则把返回的上传到服务器图片路径设置到picturePath标签
$("input[name='picturePath']").val(json.msg);
} else {
alert(json.msg);
$("input[name='picturePath']").val("");
}
},
"error" :function () {
alert("出错!");
}
});
}
</script>
</head>
<body>
<!-- 以post请求方式,发送请求给product/save.do -->
<form action="${pageContext.request.contextPath}/product/save.do" method="post">
<table border="1">
<tr>
<td>产品名</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>产品价格</td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>库存数量</td>
<td><input type="text" name="number"></td>
</tr>
<tr>
<td>产品简介</td>
<td><textarea name="info"></textarea></td>
</tr>
<tr>
<td>产品照片<input type="text" name="picturePath" value="" hidden></td>
<!-- 当选择的照片发生了变化,调用upload()方法,上传图片到服务器 -->
<td><input type="file" id="pictureFile" onchange="upload()" accept=".jpg, .jpeg, .png"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="添加" align="center"></td>
</tr>
</table>
</form>
</body>
</html>
②detail.jsp
页面
<%--
Created by IntelliJ IDEA.
User: hestyle
Date: 2020/1/30
Time: 15:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>产品详情</title>
</head>
<body>
<table border="1">
<tr>
<td>产品编号</td>
<td><input type="text" name="name" readonly value="${product.id}"></td>
</tr>
<tr>
<td>产品名称</td>
<td><input type="text" name="name" readonly value="${product.name}"></td>
</tr>
<tr>
<td>产品价格</td>
<td><input type="text" name="price" readonly value="${product.price}"></td>
</tr>
<tr>
<td>库存数量</td>
<td><input type="text" name="number" readonly value="${product.number}"></td>
</tr>
<tr>
<td>产品简介</td>
<td><textarea name="info" cols="20" rows="5" readonly>${product.info}</textarea></td>
</tr>
<tr>
<td>产品照片</td>
<td><img src="${pageContext.request.contextPath}/${product.picturePath}" width="80px" height="80px"></td>
</tr>
<tr>
<td>创建时间</td>
<td>${product.createdTime}</td>
</tr>
</table>
</body>
</html>
③edit.jsp
页面
<%--
Created by IntelliJ IDEA.
User: hestyle
Date: 2020/1/30
Time: 15:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>产品详情</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/product/update.do">
<table border="1">
<tr>
<td>产品编号</td>
<td><input type="text" name="id" value="${product.id}" readonly></td>
</tr>
<tr>
<td>产品名称</td>
<td><input type="text" name="name" value="${product.name}"></td>
</tr>
<tr>
<td>产品价格</td>
<td><input type="text" name="price" value="${product.price}"></td>
</tr>
<tr>
<td>库存数量</td>
<td><input type="text" name="number" value="${product.number}"></td>
</tr>
<tr>
<td>产品简介</td>
<td><textarea name="info" cols="20" rows="5">${product.info}</textarea></td>
</tr>
<tr>
<td>产品照片</td>
<td><img src="${pageContext.request.contextPath}/${product.picturePath}" width="80px" height="80px"></td>
</tr>
<tr>
<td rowspan="2" align="center"><input type="submit" value="保存"></td>
</tr>
</table>
</form>
</body>
</html>
④listAll.jsp
页面
<%--
Created by IntelliJ IDEA.
User: hestyle
Date: 2020/1/30
Time: 11:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="jstl" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>所有产品列表</title>
</head>
<body>
<table border="1">
<tr>
<td>产品编号</td>
<td>产品名称</td>
<td>产品价格</td>
<td>库存数量</td>
<td>产品简介</td>
<td>产品照片</td>
<td>创建时间</td>
<td>相关操作</td>
</tr>
<!-- 需要在导入jstl.jar依赖,并且在顶端导入jstl的uri才能使用forEach标签 -->
<jstl:forEach items="${productList}" var="product">
<tr>
<td>${product.id}</td>
<td><a href="${pageContext.request.contextPath}/product/detail.do?id=${product.id}">${product.name}</a></td>
<td>${product.price}</td>
<td>${product.number}</td>
<td>${product.info}</td>
<td><img src="${pageContext.request.contextPath}/${product.picturePath}" width="50px" height="50px"></td>
<td>${product.createdTime}</td>
<td>
<a href="${pageContext.request.contextPath}/product/edit.do?id=${product.id}">编辑</a>
 <a href="${pageContext.request.contextPath}/product/delete.do?id=${product.id}">删除</a>
</td>
</tr>
</jstl:forEach>
</table>
</body>
</html>
6、编写配置文件
①、新建resources
文件夹
②、添加web层spring配置文件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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/aop
http://www.springframework.org/schema/aop/spring-aop.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">
<!-- 直接导入mapper、service层spring配置文件 -->
<import resource="classpath:applicationContext-dao.xml"/>
<import resource="classpath:applicationContext-service.xml"/>
</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: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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 1.配置注解扫描位置 -->
<context:component-scan base-package="cn.hestyle.demo.web.controller" />
<!-- 2.配置注解处理映射-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!--3.配置适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
</bean>
<!-- 4.配置springmvc视图解析器 视图解析器解析的视频路径为:前缀 + 后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 5.配置springmvc文件处理 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传图片文件的大小 单位为Byte 5M=1024*1024*5 -->
<property name="maxUploadSize" value="5242880"/>
</bean>
</beans>
④、日志输出文件log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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
⑤修改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">
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- 1、配置spring mvc DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 3.0的spring mvc 默认加载WEB-INF下的dispatcher-servlet.xml文件 3.2的spring mvc
加载DispatcherServlet-servlet.xml文件 -->
<init-param>
<!-- 修改黑底spring mvc加载的配置文件路径 -->
<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>*.do</url-pattern>
</servlet-mapping>
<!-- 2、spring的配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 3、配置编码过滤器(防止中文乱码) -->
<filter>
<filter-name>EncodingFilter</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>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
五、启动项目
成功启动
地址一:https://pan.baidu.com/s/1z9zjQbIAPyr4NoNPYRo82w 提取码: erhb
地址二:https://pan.baidu.com/s/1PhnMNpQXnChJE86WvPz5lw 提取码: h16v
地址三:https://pan.baidu.com/s/1Wh9xBNWsFwkwi3Byt9Puqg 提取码: sntp
Spring、SpringMVC、Mybatis框架整合(IDEA)(附Demo)
Maven工具之创建第一个项目
Maven工具之快速入门(此篇绝对足够!)
以上就是Maven工具之分模块构造SSM项目(附Demo源码)主要内容,主要是演示操作过程,喜欢的可以点个赞哟~