ssm框架整合(idea版,带源码)

目录

 

前言

环境

源码下载

实现的目标

ssm整合

 1.搭建环境,创建maven项目

2.在pom.xml中添加依赖,导入jar包

3.编写spring及springmvc的配置文件

 4.在web.xml中加载两个配置文件

5.通过mybatis插件生成pojo及mapper

6.修改po层和mapper实现一对多,多对一关系

7.编写前端页面add.jsp

8.启动项目 

 添加上传图片回显功能


前言

Spring、SpringMVC、MyBatis简称为ssm。ssm是后端开发人员的必备技能,使用的人也比较多。所以今天做一下整合,希望可以对小白有点帮助,大佬们自行无视。

环境

idea 2018.2

jdk  1.8

tomcat 8.0

mysql 5.6

maven 3.3.9

源码下载

百度网盘 :链接  提取码:x9yr

实现的目标

ssm整合,图片上传以及回显(ajax实现),新增图书功能实现。

效果图:

数据库表如下:

book_info

book_type 

ssm整合

 1.搭建环境,创建maven项目

完善目录结构

 具体做法

2.在pom.xml中添加依赖,导入jar包

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.2.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

<!-- 试图解析器使用https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.2.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>4.2.4.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.ow2.asm</groupId>
  <artifactId>asm</artifactId>
  <version>4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.7.1</version>
</dependency>

<!--mysql驱动包 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.26</version>
</dependency>

<!--mybatis核心包 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.3.0</version>
</dependency>
<!-- mybaits与spring整合到一起的包 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.2.2</version>
</dependency>
<dependency>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-core</artifactId>
  <version>1.3.2</version>
</dependency>
<!--数据库连接池的jar-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.12</version>
</dependency>
<!-- 日志文件管理包 -->
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.12</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.7.12</version>
</dependency>

<!--文件上传 https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>
<!-- json:https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.47</version>
</dependency>
<!-- 分页工具pagehelper:https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
<dependency>
  <groupId>com.github.jsqlparser</groupId>
  <artifactId>jsqlparser</artifactId>
  <version>0.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.0.0</version>
</dependency>

强制发布到tomcat上

<resources>
  <resource>
    <directory>src/main/java</directory>
    <includes>
      <include>**/*.xml</include>
      <include>**/*.properties</include>
    </includes>
    <filtering>false</filtering>
  </resource>
  <resource>
    <directory>src/main/resources</directory>
    <includes>
      <include>**/*.xml</include>
      <include>**/*.properties</include>
    </includes>
    <filtering>false</filtering>
  </resource>
</resources>

添加mybatis-generator 插件自动生成pojo层和dao层代码

<plugin>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-maven-plugin</artifactId>
  <version>1.3.2</version>
  <configuration>
    <!--配置文件的位置-->
    <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
    <verbose>true</verbose>
    <overwrite>true</overwrite>
  </configuration>
  <executions>
    <execution>
      <id>Generate MyBatis Artifacts</id>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>

</plugin>

在resources里添加 log4j.properties 配置文件,打印日志用的(不需要引用,自动识别,名称不能改变,否则无法识别)

### 级别,目的地  ###
log4j.rootLogger=debug, stdout,logfile
### 控制台  ###
log4j.appender.stdout.charset=utf-8
log4j.appender.stdout.encoding=utf-8
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

### 文件 ###

log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=log4j.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %F %p %m%n

添加数据库连接配置文件   db.properties 自行修改数据库名

jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://127.0.0.1:3306/db_book?useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=root

mysql8将第二条改为

jdbc_url=jdbc:mysql://127.0.0.1:3306/db_book?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=UTC

3.编写spring及springmvc的配置文件

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
    <!-- 1.引入db.properties -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 2.开启spring ioc注解及扫描 -->
    <context:annotation-config />
    <context:component-scan base-package="cn.sdut.ssm" />
    <!--3.开启aop注解-->
    <aop:aspectj-autoproxy/>
    <!-- 4.配置连接池 druid -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <!--可以自动加载驱动,所以可以不用引入-->
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <!-- 数据源初始化自动创建10个连接 -->
        <property name="initialSize" value="10" />
        <property name="maxActive" value="20" />
        <property name="minIdle" value="0" />
    </bean>
    <!-- 5.配置sqlsessionfactroy -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 5.1配置数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 5.2加载mapper文件 -->
        <property name="mapperLocations" value="classpath:cn/sdut/ssm/dao/*.xml" />
        <property name="typeAliasesPackage" value="cn.sdut.ssm.po" />
        <!--5.3 分页工具pagehelper的配置-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
    <!-- 6.配置扫描器dao层接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--6.1 将映射文件与接口建立关联 -->
        <property name="basePackage" value="cn.sdut.ssm.dao" />
        <!-- 6.2此处配置的是value 防止读取不到db.properties配置文件中的信息 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
    <!-- 7.配置事务 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 7开启事务的注解 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

路径可能会报红,没事,一会生成代码后就好了

<?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-3.0.xsd
            http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <!--1.静态资源处理器 location属性必须放到前面,mapping放后面 -->
    <mvc:resources location="/resource/" mapping="/resource/**" />

    <!--2.添加springmvc扫描器 -->
    <context:component-scan base-package="cn.sdut.ssm"/>

    <!--3.开启spring mvc注解 -->
    <mvc:annotation-driven/>

    <!--4.文件上传 -->
    <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <property name="defaultEncoding" value="utf-8"/> <!-- 默认编码 (ISO-8859-1) -->
        <property name="maxInMemorySize" value="10240"/> <!-- 最大内存大小 (10240)-->
        <property name="uploadTempDir" value="/resource/upload/"/> <!-- 上传后的目录名 -->
        <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) -->
    </bean>

    <!--5.全局日期转换器 -->
    <bean id="formattingConversionServiceFactoryBean"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean id="dateConverter" class="cn.sdut.ssm.utils.DateConverter"></bean>
            </list>
        </property>
    </bean>

    <!--6.进行注册 -->
    <mvc:annotation-driven conversion-service="formattingConversionServiceFactoryBean" />

    <!--7.配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <!-- 配置前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 配置后缀 -->
        <property name="suffix" value=".jsp" />
        <!-- 使用jstl的配置 -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
    </bean>

</beans>

建立如下工具类和resource和upload文件夹

public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        if (date!=null){
            try {
                return dateFormat.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

 4.在web.xml中加载两个配置文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--  启动spring监听器,加载spring核心配置文件 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--配置前端核心控制器DispatcherServlet,加载springmvc的核心配置文件-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- utf-8解决中文乱码 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--错误页面,可以自定义一个error.jsp-->
  <error-page>
    <error-code>404</error-code>
    <location>/error.jsp</location>
  </error-page>

</web-app>

如果报错的话,可以调整一下右下角的检查等级,调低一点就可以了

5.通过mybatis插件生成pojo及mapper

mybatis-generator-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--1mysql 连接数据库jar 这里选择自己本地位置-->
    <classPathEntry location="E:/idea/.m2/repository/mysql/mysql-connector-java/5.1.29/mysql-connector-java-5.1.29.jar" />
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 2是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--3数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/db_book"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
           NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 4targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="cn.sdut.ssm.po"
                            targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 5targetProject:mapper映射文件生成的位置
           如果maven工程只是单独的一个工程,targetProject="src/main/java"
           若果maven工程是分模块的工程,targetProject="所属模块的名称",例如:
           targetProject="ecps-manager-mapper",下同-->
        <sqlMapGenerator targetPackage="cn.sdut.ssm.dao"
                         targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- 6targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cn.sdut.ssm.dao"
                             targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 7指定数据库表 -->
        <table  tableName="book_info"
                enableCountByExample="false"
                enableDeleteByExample="false"
                enableSelectByExample="true"
                enableUpdateByExample="false"
        >
            <property name="modelOnly" value="false" />
        </table>
        <table
                tableName="book_type"
                enableCountByExample="false"
                enableDeleteByExample="false"
                enableSelectByExample="true"
                enableUpdateByExample="false"
        >
            <property name="modelOnly" value="false" />
        </table>
    </context>
</generatorConfiguration>

点击右上角的edit configuration

点击右上角的'+'号,创建代码生成器  ,执行命令:mybatis-generator:generate -e 

开启自动生成 

成功如图所示

6.修改po层和mapper实现一对多,多对一关系

一对多关系的改动

BookType

 

BookTypeMapper 

由于两个表中都有id,所以需要加上表名 

 多对一类似,这里就不在多赘述了,不懂得可以参考源码,也可以参考我以前的博客

7.编写前端页面add.jsp

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2019/12/4
  Time: 11:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false" %><%--允许使用el表达式--%>
<%@ 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">
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.js"></script>
    <title>新增书籍</title>
    <style type="text/css">
        #body {
            margin: 0px auto;
            width: 800px;
            height: 600px;
        }
    </style>
</head>
<body>
<div id="body">
    <div style="margin: 0px auto; width: 500px;">
        <form action="" method="post" enctype="multipart/form-data" id="imgf">
            <table border="1px" style="text-align: center;">
                <tr>
                    <td>图书名称</td>
                    <td><input name="bookname"></td>
                </tr>
                <tr>
                    <td>图书分类</td>
                    <td style="text-align: left;">
                        <select name="booktype">
                        <c:forEach items="${bookTypes}" var="bookType">
                            <option value="${bookType.id }">${bookType.booktypename}</option>

                        </c:forEach>
                    </select></td>
                </tr>
                <tr>
                    <td>作者</td>
                    <td><input name="author"></td>
                </tr>
                <tr>
                    <td>出版社</td>
                    <td><input name="press"></td>
                </tr>
                <tr>
                    <td>出版时间</td>
                    <td><input name="publishdate"></td>
                </tr>
                <tr>
                    <td>图片上传</td>
                    <td><img id="img" src="" width="100px" height="80px"><!-- 显示图片的 -->
                        <input name="fileImage" type="file" onchange="uploadImage();">
                        <input type="hidden" name="path" id="pic"  >
                    </td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="提交" onclick="onSumbit()"> <input
                            type="button" value="取消"></td>

                </tr>
            </table>
        </form>
    </div>


</div>
</body>
<script type="text/javascript">
    function uploadImage() {
        //编写ajax
        var obj={
            url:"imageupload.do",
            dataType:"json",
            type:"post",
            success:function(data){
                $("#img").attr("src",data.imagePath);
                $("#pic").attr("value",data.imagePath);
            }
        };
        //提交form
        $("#imgf").ajaxSubmit(obj);

    };
    function onSumbit() {
        console.log(imgf);
        var obj={
            url:"addBook.do",
            dataType:"json",
            type:"post",
            success:function(data){
                console.log(imgf);
            }
        };
        $("#imgf").ajaxSubmit(obj);
    }

</script>
</html>

 因为是使用ajax,所以需要引入js文件,

 编写BookAddController

//开启事务
@Transactional
@Controller
public class BookAddController {

    //自动注入
    @Autowired
    private BookTypeService bookTypeService;
    @Autowired
    private BookInfoService bookInfoService;

    //查询书籍类型
    @RequestMapping("toAdd.do")
    public String toAdd(ModelMap map){
        List<BookType> bookTypes = bookTypeService.selectByExample(new BookTypeExample());
        System.out.println(bookTypes);
        map.put("bookTypes",bookTypes);
        return "add";
    }

    //添加数据
    @RequestMapping("addBook.do")
    public void addBook(BookInfo bookInfo,@RequestParam("booktype") String booktype){

        bookInfo.setBooktypeid(Integer.parseInt(booktype));
        bookInfoService.insert(bookInfo);
    }


}

编写service层

将Mapper接口复制到service层,改名为service,并编写实现类

BookInfoService 复制的是BookInfo接口

public interface BookInfoService {
    int deleteByPrimaryKey(Integer id);

    int insert(BookInfo record);

    int insertSelective(BookInfo record);

    List<BookInfo> selectByExample(BookInfoExample example);

    BookInfo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(BookInfo record);

    int updateByPrimaryKey(BookInfo record);
}

 BookInfoServiceImpl

@Service
public class BookInfoServiceImpl implements BookInfoService {

    @Autowired
    private BookInfoMapper bookInfoService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return bookInfoService.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(BookInfo record) {
        return bookInfoService.insert(record);
    }

    @Override
    public int insertSelective(BookInfo record) {
        return bookInfoService.insertSelective(record);
    }

    @Override
    public List<BookInfo> selectByExample(BookInfoExample example) {
        return bookInfoService.selectByExample(example);
    }

    @Override
    public BookInfo selectByPrimaryKey(Integer id) {
        return bookInfoService.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(BookInfo record) {
        return bookInfoService.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(BookInfo record) {
        return bookInfoService.updateByPrimaryKey(record);
    }
}

bookType类似

8.启动项目 

编写一个test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script>
    location.href="toAdd.do";
</script>
</body>
</html>

运行test.jsp

测试一下

添加成功

 添加上传图片回显功能

前端代码在add.jsp中已经编写完毕了,这里理一下思路。先利用ajax上传图片到服务器上(onchange的时候上传),上传成功了,则返回一个url,并将url赋值给显示的img和隐藏域的pic。这样就可以实现图片的回显了。

后端代码  ImageUploadController

@Transactional
@Controller
public class ImageUploadController implements ServletContextAware {
    /**
     * @RequestParam("fileImage")  fileImage要与页面中 name一致
     * @param fileImage
     * @return
     */

    private ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext arg0) {
        this.servletContext = arg0;
    }

    @RequestMapping("/imageupload.do")
    @ResponseBody
    public String imageUpload(@RequestParam("fileImage") CommonsMultipartFile fileImage) {
        // 获取上传图片的位置
        String path = servletContext.getRealPath("/resource/upload/");
        System.out.println("上传的路径为:" + path);
        // 获取文件名称
        String name = fileImage.getOriginalFilename();
        // 创建file对象 写入
        File file = new File(path, name);
        try {
            fileImage.getFileItem().write(file);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 将上传的图片路径以json的方式返回客户端
        String imagePath = "/resource/upload/" + name;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("imagePath", imagePath);
        // 将对象转为json格式
        String json = jsonObject.toJSONString();
        System.out.println("json:"+json);
        return json;
    }


}

实现效果

成功了,接下来你可以继续这个完善这个小项目。

百度网盘 :链接  提取码:x9yr

码字不易,如果觉得还不错,不妨给作者个关注或者点个赞也好,当然有错也欢迎指出。

=====================================================================

其他功能的实现:博客

  • 28
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值