工具:jdk1.8 idea Tomcat MySQL Navicat
以图书管理系统为列
1.pom文件
<?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.vp</groupId> <artifactId>ssm01</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm01 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- 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/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <!--配置德鲁伊的数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</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> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!--配置mybatis需要的依赖包--> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.17.1-GA</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!-- <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.8</version> <scope>test</scope> </dependency>--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- spring jar--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.4.RELEASE</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm --> <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.8.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.4.RELEASE</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> <finalName>springmvc02</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <!--允许移动生成的文件--> <verbose>true</verbose> <!--允许覆盖生成的文件--> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </project> |
2.在resources文件下导入如下
generatorconfig.xm
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://www.mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动 改动1 --> <classPathEntry location="D:\LocalWarehouse\mysql\mysql-connector-java\5.1.6\mysql-connector-java-5.1.6.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true" /> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/db0309" userId="root" password="root"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="cn.vp.entity" targetProject="src/main/java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="true" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成映射文件的包名和位置 --> <sqlMapGenerator targetPackage="cn.vp.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.vp.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成哪些表 --> <!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 --> <table tableName="book_info" domainObjectName="BookInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> <table tableName="book_type" domainObjectName="BookType" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration> |
applicationContext.xm
<?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 "> <context:property-placeholder location="classpath:jdbc.properties"/> <context:annotation-config/> <context:component-scan base-package="cn.vp"/> <bean id="druidDataSource" 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}"/> <property name="initialSize" value="5"></property> <property name="maxActive" value="20"></property> <property name="minIdle" value="2"></property> <property name="maxWait" value="5000"></property> </bean> <!-- 配置sqlsessionfactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="druidDataSource"/> <!-- 加载xml文件--> <property name="mapperLocations" value="classpath:cn/vp/mapper/*.xml"></property> <!-- 给类取别名mybayis--> <property name="typeAliasesPackage" value="cn.vp"/> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql reasonable=true </value> </property> </bean> </array> </property> </bean> <!-- 将接口与xml文件建立关系--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.vp.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="druidDataSource"></property> </bean> <tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven> <beans> |
springmvcservlet.xm
<?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"> <!-- 添加springmvc扫描器 只扫描扫描 @Controller注解 --> <context:component-scan base-package="cn.vp.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--开启Springmvc注解--> <mvc:annotation-driven /> <mvc:annotation-driven conversion-service="conversionService2" /> <!-- 配置视图解析器 --> <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> <mvc:resources location="/upload/" mapping="/upload/**" /> <!-- 文件上传 --> <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="/upload/"/> <!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) --> <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) --> </bean> <!--配置全局日期转换器--> <bean id="conversionService2" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="cn.vp.utils.DateConvertUtil" /> </list> </property> </bean> </beans> |
jdbc.properties
log4j.properties
spring-tx-3.0.xsd
3.web.xlm配置
<?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_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 启动spring监听器 --> <listener> <!--<description>Spring 监听器</description>--> <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> <!-- 加载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:springmvcservlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> </web-app> |
4.在webapp下创建js文件与upload文件
js文件导入两个包:jquery.form.js jquery-1.8.3.js
upload文件用于图片的地址
5.以ajax实现图片上传及保存的实现
add.jsp(添加页面)
<%-- Created by IntelliJ IDEA. User: zhangpengfei Date: 2018/4/11 Time: 17:24 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style type="text/css"> #body { margin: 0px auto; width: 800px; height: 600px; } </style> <script type="text/javascript" src="/js/jquery-1.8.3.js"></script> <script type="text/javascript" src="/js/jquery.form.js"></script> <script type="text/javascript"> function uploadImage() { //编写ajax var obj={ url:"imageupload.htm", dataType:"json", type:"post", success:function(data){ $("#img").show(); $("#img").attr("src",data.imagePath); $("#pic").attr("value",data.imagePath); }, error:function () { alert("失败"); } }; //提交form $("#imm").ajaxSubmit(obj); } </script> </head> <body> <div id="body"> <div style="margin: 0px auto; width: 500px;"> <%--<form action="" method="post">--%> <form id="imm" action="addBook.htm" method="post" enctype="multipart/form-data" > <table border="1px" style="text-align: center;"> <tr> <td>图书编号</td> <td><input name="code" ></td> </tr> <tr> <td>图书名称</td> <td><input name="name"></td> </tr> <tr> <td>图书分类</td> <td style="text-align: left;"> <select name="type.id"> <c:forEach items="${types}" var="type"> <option value="${type.id }">${type.typeName}</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 type="date" name="date"></td> </tr> <tr> <td>是否借出</td> <td><input name="borrow"></td> </tr> <tr> <td>图片上传</td> <td> <img width="50dp" height="50dp" id="img" src=""> <!-- 显示图片的 --> <input name="fileImage" type="file" οnchange="uploadImage();"> <input type="hidden" name="path" id="pic" > </td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"> <input type="button" value="取消"></td> </tr> <%--<tr>--%> <%--<td>图片上传</td>--%> <%--<td><img id="img" src=""><input type="file"></td>--%> <%--</tr>--%> <%--<tr>--%> <%--<td colspan="2"><input type="submit" value="提交"> <input--%> <%--type="button" value="取消"></td>--%> <%--</tr>--%> </table> </form> </div> </div> </body> </html> |
list.jsp(显示主页面)
<%-- Created by IntelliJ IDEA. User: zhangpengfei Date: 2018/4/12 Time: 19:00 To change this template use File | Settings | File Templates. --%> <%--<%@ page contentType="text/html;charset=UTF-8" language="java" %>--%> <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>Title</title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript" src="js/jquery.form.js"></script> <%--ajax提交查询表单--%> <script type="text/javascript"> function loadBook(data) { //将tbody清空 $("#bookbody").html(""); //动态的将获取的数据添加到table $(data.bookinfos.list).each(function () { var borrow= this.borrow==0?'未借阅':'已借阅'; $("#bookbody").append('<tr>\n' + ' <td><input type="checkbox" name="id" value="'+this.id+'"></td>\n' + ' <td>'+this.code+'</td>\n' + ' <td>'+this.type.typeName+'</td>\n' + ' <td>'+this.name+'</td>\n' + ' <td>'+this.author+'</td>\n' + ' <td>'+this.press+'</td>\n' + ' <td><img style="height: 50px;width: 50px" src="'+this.path+'"></td>\n' + ' <td>'+borrow+'</td>\n' + ' <td><a href="/detail.htm?id='+this.id+'">详情</a></td>\n' + ' <td><a href="/delete.htm?id='+this.id+'">删除</a></td>\n' + ' <td><a href="/queryByBookID.htm?id='+this.id+'">修改</a></td>\n' + ' </tr>'); }); //清空脚部 $("#bookfoot").html(""); $("#bookfoot").append(' <tr>\n' + ' <td colspan="11">\n' + ' <a href="javascript:queryBooks(1);">首页</a> <a href="javascript:queryBooks('+(data.bookinfos.pageNum-1)+');">上一页</a>\n' + ' <a href="javascript:queryBooks('+(data.bookinfos.pageNum+1)+');">下一页</a>\n' + ' <a href="javascript:queryBooks('+(data.bookinfos.pages)+');">末页</a>\n' + ' '+data.bookinfos.pageNum+'/'+data.bookinfos.pages+'页\n' + ' </td>\n' + ' </tr>'); } function queryBooks(pageno) { //给表单 id为 pageno 的标签赋值 $("#pageno").attr("value",pageno); var obj={ url:"ajaxQuery.htm", dataType:"json", type:"post", success:function (data) { loadBook(data); } }; //jqeury.from ajax提交表单 $("#query").ajaxSubmit(obj); } function changecheckBox(choose) { //获取table中所有的单选按钮s $("input[name='id']").attr("checked",choose); } function deleteAll() { alert("进入ajax"); //ajax提交 tabale中的表单 var obj={ url:"ajaxDelete.htm", type:"post", dataType:"json", success:function (data) { loadBook(data); } } $("#delete").ajaxSubmit(obj); } </script> </head> <body οnlοad="queryBooks(1);"> <center> <h2>图书管理系统</h2> <hr> <form method="post" id="query"> 图书类型 <select name="type"> <option value="0">全部</option> <c:forEach items="${types}" var="type"> <option value="${type.id }">${type.typeName}</option> </c:forEach> </select> 图书名称<input name="bookname"> 是否借阅<select name="borrow"> <option value="-1">请选择</option> <option value="0">未借阅</option> <option value="1">已借阅</option> </select> <input type="hidden" name="now" id="pageno"> <input type="button" οnclick="queryBooks(1);" value="查询"> </form> <a href="/add.jsp">新增</a> <button οnclick="deleteAll();">批量删除</button> <form id="delete" action="" method="post"> <table border="1"> <thead></thead> <tr> <td><input type="checkbox" οnclick="changecheckBox(this.checked);"></td> <td>图书编号</td> <td>图书分类</td> <td>图书名称</td> <td>作者</td> <td>出版社</td> <td/>图片</td> <td>操作</td> <td>详情</td> <td>删除</td> <td>修改</td> </tr> <tbody id="bookbody"> </tbody> <tfoot id="bookfoot"> </tfoot> </table> </form> </center> </body> </html> |
detail.jsp(详情)
<%-- Created by IntelliJ IDEA. User: zhangpengfei Date: 2018/4/14 Time: 15:25 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <html> <head> <title>详情</title> </head> <body> <table border="1px" style="text-align: center;"> <tr> <td>图书编号</td> <td>${bookinfo.code }</td> </tr> <tr> <td>图书名称</td> <td>${bookinfo.name }</td> </tr> <tr> <td>图书分类</td> <td >${bookinfo.type.typeName }</td> </tr> <tr> <td>作者</td> <td>${bookinfo.author }</td> </tr> <tr> <td>出版社</td> <td>${bookinfo.press }</td> </tr> <tr> <td>出版时间</td> <td><fmt:formatDate value="${bookinfo.date }" pattern="yyyy-MM-dd"/> </td> </tr> <tr> <td>图片</td> <td><img style="height: 50px;width: 50px" src="${bookinfo.path}"></td> </tr> <tr> <td colspan="2"> <a href="/index.jsp;">返回首页</a> </td> </tr> </table> </body> </html> |
editBookInfo.jsp
<%-- Created by IntelliJ IDEA. User: zhangpengfei Date: 2018/4/14 Time: 17:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <html> <head> <title>修改</title> <style type="text/css"> #body { margin: 0px auto; width: 800px; height: 600px; } </style> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript" src="js/jquery.form.js"></script> <script> function upLoadImage() { //编写ajax var obj={ url:"imageupload.htm", dataType:"json", type:"post", success:function(data){ $("#img").show(); $("#img").attr("src",data.imagePath); $("#pic").attr("value",data.imagePath); }, error:function () { alert("失败"); } }; //提交form $("#imm").ajaxSubmit(obj); } </script> </head> <body> <div id="body"> <div style="margin: 0px auto; width: 500px;"> <form id="bookAdd" action="/editBook.htm" method="post" enctype="multipart/form-data"> <table border="1px" style="text-align: center;"> <tr> <td>图书编号</td> <td><input name="code" value="${bookInfoss.code}" readonly></td> </tr> <tr> <td>图书名称</td> <td><input name="name" value="${bookInfoss.name}" ></td> </tr> <tr> <td>图书分类</td> <td style="text-align: left;"> <select name="type.id"> <c:forEach items="${types}" var="bookTy"> <option <c:if test="${bookInfoss.type.id==bookTy.id}">selected</c:if> value="${bookTy.id }">${bookTy.typeName}</option> </c:forEach> </select></td> </tr> <tr> <td>作者</td> <td><input name="author" value="${bookInfoss.author}"></td> </tr> <tr> <td>出版社</td> <td><input name="press" value="${bookInfoss.press}"></td> </tr> <tr> <td>出版时间</td> <td><input name="date" value="<fmt:formatDate value="${bookInfoss.date}" pattern="yyyy-MM-dd" />"></td> </tr> <tr> <td>图片上传</td> <td><img width="100px" height="100px" id="img" src="${bookInfoss.path}"><input name="imges" type="file" οnchange="upLoadImage();"> <input type="hidden" name="path" value="${bookInfoss.path}"> </td> </tr> <tr> <td colspan="2"> <input type="hidden" name="id" value="${bookInfoss.id}"> <input type="submit" value="提交"> <input type="button" value="取消"></td> </tr> </table> </form> </div> </div> </body> </html> |
controller
BookInfoController.java
package cn.vp.controller; import cn.vp.entity.BookInfo; import cn.vp.service.BookInfoService; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.ServletContext; import java.io.File; import java.util.List; @Controller public class BookInfoController implements ServletContextAware { @Autowired private BookInfoService bookInfoService; private ServletContext servletContext; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @RequestMapping( value = "/editBook.htm") public String editBoonInfo(BookInfo bookInfoss){ System.out.println(bookInfoss.getPath()); //将图片的 第一个 / 去掉 String path = bookInfoss.getPath(); bookInfoss.setPath( path.substring(1)); //调用修改的方法 int i = bookInfoService.updateBookInfo(bookInfoss); System.err.println("受影响行数:"+i); return "list"; } /** * 根据图书id查询 图书信息 * @param bookInfoId 图书id * @return 图书对象 */ @RequestMapping(value = "/queryByBookID.htm") public String queryById(@RequestParam("id")Integer bookInfoId, ModelMap map){ BookInfo bookInfo = bookInfoService.queryById(bookInfoId); map.put("bookInfoss",bookInfo); return "forward:/editBookInfo.jsp"; } /**批删 * @param id * @return */ @RequestMapping(value = "/ajaxDelete.htm") public String deleteBookByids(String[] id) { System.err.println("进来了deletebookbyids方法"); for (String id1 : id) { System.out.println(id); } //调用service的批删方法 int i = bookInfoService.deleteByIds(id); System.out.println("删除了"+i+"条记录"); //deleteAll is not defined return "forward:/ajaxQuery.htm"; } /** * 详情 * * @param id * @return 跳转到详情 */ @RequestMapping("/detail.htm") public String detail(ModelMap map,Integer id) { BookInfo bookInfo = bookInfoService.queryById(id); System.out.println(bookInfo); map.put("bookinfo",bookInfo); return "detail"; } /** * 删除 * * @param id * @return 跳转到查询 */ @RequestMapping("/delete.htm") public String delete(Integer id) { int delete = bookInfoService.delete(id); System.out.println(delete); return "list"; } /**查询及分页 * @param type * @param bookname * @param borrow * @param now * @return */ @RequestMapping(value ="/ajaxQuery.htm",produces={"application/json;","text/html;charset=UTF-8;"}) @ResponseBody //指明返回json格式的编码格式 public String ajaxQuery(String type, String bookname, String borrow,Integer now) { System.err.println("进入到controller"); PageHelper.startPage(now, 3); //1.调用业务逻辑层 List<BookInfo> query = bookInfoService.query(type, bookname, borrow); PageInfo<BookInfo> PageInfo = new PageInfo<>(query); //2.将获取的数据封装为Json JSONObject jsonObject = new JSONObject(); jsonObject.put("bookinfos", PageInfo); String s = JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd"); System.err.println(s); return s; } /** * 新增 * * @param bookInfo * @return 跳转到查询 */ @RequestMapping("/addBook.htm") public String addBook(BookInfo bookInfo) { System.err.println(bookInfo); int i = bookInfoService.insert(bookInfo); if (i > 0) { System.out.println("新增成功"); } else { System.out.println("失败..."); } return "list"; } /**图片上传 * @RequestParam("fileImage") fileImage要与页面中 name一致 * @param fileImage * @return */ @RequestMapping("imageupload.htm") @ResponseBody public String imageUpload(@RequestParam("fileImage") CommonsMultipartFile fileImage) { // 获取上传图片的位置 String path = servletContext.getRealPath("/upload/"); System.err.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 = "/upload/" + name; JSONObject jsonObject = new JSONObject(); jsonObject.put("imagePath", imagePath); // 将对象转为json格式 String json = jsonObject.toJSONString(); System.err.println("json:"+json); return json; } } |
BookTypeController.java
package cn.vp.controller; import cn.vp.entity.BookType; import cn.vp.service.BookTypeService; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.ServletContext; import java.io.File; import java.util.List; @SessionAttributes({"types"}) @Controller public class BookTypeController implements ServletContextAware { @Autowired private BookTypeService bookTypeService; private ServletContext servletContext; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @RequestMapping("add.htm") public String goAdd(ModelMap map) { System.out.println("进入跳转到add.jsp页面..."); List<BookType> types = bookTypeService.queryAllType(); map.put("types", types); return "add"; } } |
另外service层可自行写与Controller匹配
dao层 entity层 可利用generater自动生成