本文主要是介绍简易版的SSM框架maven项目实现CRUD【增Create、查Retrieve、改Update、删Delete】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、SSM项目【Spring+Springmvc+MyBatis】
1.创建maven项目
create maven project.
下一步 next
继续 下一步next,Catalog选择你的maven安装路径的archetype-catalog.xml,尽量不要选All Catalogs,不要选All Catalogs,不要选All Catalogs。重要的事情说三遍。 【虽然我也看其他人选的这个,结果测试也没报错,但是我仍然不建议选它】
Filter 中填 org.apache.maven.然后会出现
然后选择最下面的这一条 maven-archetype-webapp 1.0,选中,然后next
Group Id 是你的公司名,com.你的公司名【例如 你公司是百度,com.baidu】
Artifact Id是你的项目名称,随便,我这里是book_ssm
Version 是你的版本,我这里选1.0【0.01也可以,我习惯1.0】,
然后Finished,
然后项目可能会报错,就像
此时只需做一件事,找到webapp文件下的index.jsp,并打开它,
打开的index.jsp如下:
然后,全选Ctrl+A, 删除Backspace ,最后保存Ctrl+S
空文件,啥都没。
2.添加一些必要的文件夹。
**********在src下的main文件下添加一个名为java的文件夹,步骤如下:
右击项目,new一个Folder文件夹,找到src,鼠标选中main文件夹,在下面的Folder name写上 java ,然后Finish。
*****************在src文件夹下建立test文件夹,在这个test文件夹下建一个java文件夹供测试类使用。步骤与上同。
右击项目,new一个Folder文件夹,找到src,鼠标选中src文件夹,在下面的Folder name写上 test ,然后Finish。
右击项目,new一个Folder文件夹,找到src,鼠标选中src文件夹下的test文件夹,在下面的Folder name写上 java,然后Finish。
3.添加依赖。
打开poml.xml文件,在dependencies标签内添加如下代码,并保存。
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>javax.websocket</groupId><artifactId>javax.websocket-api</artifactId><version>1.0</version></dependency><!--druid--><!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.2</version></dependency><!--mybatis-spring适配器 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><!--mysql数据库驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2</version></dependency><!-- 文件上传 --><dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!--log4j日志包 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- mybatis ORM框架 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><dependency><groupId>javax.annotation</groupId><artifactId>javax.annotation-api</artifactId><version>1.2</version></dependency><dependency><groupId>javax.transaction</groupId><artifactId>javax.transaction-api</artifactId><version>1.2</version></dependency>
<!-- spring配置 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.3.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>4.3.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.3.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.5.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-core</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-ldap</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-acl</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-cas</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-taglibs</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.3.5.RELEASE</version></dependency>
保存后,可看到如下图,jar包已添加完毕【该依赖需要你电脑有网的情况下才生效,需要下载,没网的电脑就老老实实用你的动态web项目吧(Dynamic Web Project)】
4.找到src/main/java文件夹
左键单击选中,new一个包package,名字一般是(com.baidu.bookstore.domain)
并在该包下建一个类(class),名为Book,并让该Book类序列化,implements Serializable,其实Serializable是一个空接口,没有什么具体内容,它的目的只是简单的标识一个类的对象可以被序列化。
添加Book类属性,bookid String类型,bookname String类型,bookprice double类型,bookimg String 类型,并构建它们的set与get方法。
package com.baidu.book.domain;import java.io.Serializable;@Component
public class Book implements Serializable{/*** */private static final long serialVersionUID = 1L;private String bookid;private String bookname;private double bookprice;private String bookimg;public String getBookid() {return bookid;}public void setBookid(String bookid) {this.bookid = bookid;}public String getBookname() {return bookname;}public void setBookname(String bookname) {this.bookname = bookname;}public double getBookprice() {return bookprice;}public void setBookprice(double bookprice) {this.bookprice = bookprice;}public String getBookimg() {return bookimg;}public void setBookimg(String bookimg) {this.bookimg = bookimg;}}
开始写持久层,
在domain同级创建一个包package,包名为com.baidu.book.mapper,在该包下创建一个接口BookMapper,内有实现方法,如下代码:
package com.baidu.book.mapper;import java.util.List;import com.baidu.book.domain.Book;public interface BookMapper {//分页查询public List<Book> getPageBooks(int index);//删除书籍public int deleteBook(String bookid);//添加书籍public int saveBook(Book book);//修改书籍public int updateBook(Book book);//获得书籍数量总页面public int getTotalRecord();//通过书籍编号查看书籍详情public Book getBookById(String bookid);}
我们需要将接口中的方法一一实现,接口又不能像类一样new,只能写配置文件,相当于将接口实例化
所以在src/main/resource文件下创建一个xml配置文件,由于该配置文件是将持久层的接口实例化,故起名BookMapper.xml
内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace:要实现的的接口id:要实现的方法名字#里面的单词一定是JAVABEAN里面的属性,parameterType,是这个方法里面的小括号 里面写的 -->
<mapper namespace="com.baidu.book.mapper.BookMapper"><!-- 添加书籍 --><insert id="saveBook" parameterType="Book">insert into book
<!-- prefix:在trim标签内sql语句加上前缀。
suffix:在trim标签内sql语句加上后缀。
suffixOverrides:指定去除多余的后缀内容,如:suffixOverrides=",",去除trim标签内sql语句多余的后缀","。
prefixOverrides:指定去除多余的前缀内容 --><trim prefix="(" suffix=")" suffixOverrides=","><if test="bookname != null">bookname,</if><if test="bookprice != 0">bookprice,</if><if test="bookimg != null">bookimg</if></trim>values<trim prefix="(" suffix=")" suffixOverrides=","><if test="bookname != null">#{bookname},</if><if test="bookprice != 0">#{bookprice},</if><if test="bookimg != null">#{bookimg}</if></trim></insert><!-- 删除书籍 --><delete id="deleteBook" parameterType="String" >delete frombookwherebookid = #{bookid}</delete><!-- 修改书籍 --><update id="updateBook" parameterType="Book">update book
<!-- set标签与trim标签类似,可以去除多余的,或者()等等 --><set><if test="bookname != null">bookname = #{bookname},</if><if test="bookprice != 0">bookprice = #{bookprice},</if><if test="bookimg != null" >bookimg = #{bookimg}</if></set>wherebookid = #{bookid}</update><resultMap type="Book" id="book"><id column="bookid" property="bookid" javaType="String" jdbcType="VARCHAR" /><result column="bookname" property="bookname" javaType="String" jdbcType="VARCHAR"/><result column="bookprice" property="bookprice" javaType="float" jdbcType="FLOAT"/><result column="bookimg" property="bookimg" javaType="String" jdbcType="VARCHAR"/></resultMap><!-- 分页查询 --><select id="getPageBooks" parameterType="int" resultType="book">select bookid,bookname,bookprice,bookimgfrombook limit #{index},3</select><!-- 根据书籍编号查找书籍详情 --><select id="getBookById" parameterType="String" resultType="book">select bookid,bookname,bookprice,bookimgfrom bookwherebookid = #{bookid}</select><!-- 获得书籍数量总页面 --><select id="getTotalRecord" resultType="int">select count(*) from book</select></mapper>
可以看到增删改查,基本都是SQL语句,insert 、delete、update、select标签内,id是你的BookMapper接口里面的方法名;
parameterType【从单词就可以看出来,这是括号里面的参数类型】
标签内写SQL语句。
select与增删改略有不同,查找的数据需要放进一个Map容器,并从该容器中读取
该容器名为resultMap,id是他的名字,一般是类名(首字母小写),type也是它的类名,不过首字母要大写。
内有主键id,即数据库中的主键bookid,其他属性,以result标签包揽。
无论是主键id,还是一般属性result ,标签内都有属性值,column【数据库里面的列名,即表的列名】、property【javaBean里面的属性名,与数据库表的列名一一对应】、javaType【javaBean里面的属性】、jdbcType【数据库里面的属性】。
由于实现CRUD离不开数据库,持久层调用SessionFactory,需要配置xml文件,获取session.
在src/main/resource文件下创建一个xml配置文件,名为application,文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns: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-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!-- 开启扫描 扫描范围是com.baidu.book这个文件夹下的所有包 ,*代表所有 --><context:component-scan base-package="com.baidu.book.*" /><!-- 数据连接池 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="805230" /></bean><!-- 不需要定义SqlSessionFactory,注意configLocation当您使用MapperFactoryBean --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 自动扫描domain目录, 省掉Configuration.xml里的手工配置 --><property name="typeAliasesPackage" value="com.baidu.book.domain" /> <!-- 以类名当别名 --><property name="dataSource" ref="dataSource" /><!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> --><property name="mapperLocations" value="classpath:BookMapper.xml" /></bean><!-- 扫描映射器 Mapper 持久层实例化--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- Mapper接口所在包名,Spring会自动查找其下的Mapper --><property name="basePackage" value="com.baidu.book.mapper" /><!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> --></bean><!-- 页面上传时需要用到的 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 设定默认编码 --><!-- <property name="defaultEncoding" value="UTF-8" /> --><property name="maxUploadSize" value="102400000"></property><!-- 文件上传最大的大小字节 --><!-- <property name="maxInMemorySize" value="4096" /> --></bean><!-- 事务处理 --><!-- 事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!-- 开启事务注解 --><tx:annotation-driven transaction-manager="transactionManager" /></beans>
创建业务层(服务层)
在domain同级创建一个包package,包名为com.baidu.book.service,在该包下创建一个接口BookService,内有实现方法,如下代码:
package com.baidu.book.service;import java.util.List;import com.baidu.book.domain.Book;public interface BookService {//分页查询public List<Book> getPageBooks(int page);//删除书籍public void deleteBookById(String bookid);//添加书籍public void addBook(Book book);//修改书籍public void updateBook(Book book);//根据书籍编号查找书籍详情public Book getBookById(String bookid);//获得书籍数量总页数public int getTotalPage();}
实现这些方法,需要再创建一个包package,包名为com.baidu.book.service.impl,在该包下创建一个接口BookService,内有实现方法,如下代码:
package com.baidu.book.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import com.baidu.book.domain.Book;
import com.baidu.book.mapper.BookMapper;
import com.baidu.book.service.BookService;// 此处实例化接口bookService
@Service("bookService")
public class BookServiceimpl implements BookService{@Autowiredprivate BookMapper bookMapper;@Overridepublic List<Book> getPageBooks(int page) {int index = (page-1)*3;return bookMapper.getPageBooks(index);}@Transactional@Overridepublic void deleteBookById(String bookid) {bookMapper.deleteBook(bookid);}@Transactional@Overridepublic void addBook(Book book) {bookMapper.saveBook(book);}@Transactional@Overridepublic void updateBook(Book book) {bookMapper.updateBook(book);}@Overridepublic Book getBookById(String bookid) {return bookMapper.getBookById(bookid);}@Overridepublic int getTotalPage() {int totalSize = bookMapper.getTotalRecord();if(totalSize % 3 ==0){return totalSize / 3;}else{return totalSize / 3 + 1 ;}}}
DI依赖注入 dependency依赖 IOC控制反转 autowired即是将bookMapper实例化;
BookMapper bookMapper = new BookMapperimpl();实际上BookMapperimpl是不存在的。
创建控制层,需要再创建一个包package,包名为com.baidu.book.controller,在该包下创建一个servlet,名为BookController,servlet主要作用是,jsp页面传值到控制层,接受页面传来的数据,,如下代码:
package com.baidu.book.controller;import java.io.FileOutputStream;import javax.servlet.http.HttpServletRequest;import org.apache.log4j.Logger;
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.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;import com.baidu.book.domain.Book;
import com.baidu.book.service.BookService;
import com.baidu.book.util.ChineseEncoding;
import com.baidu.book.util.FileNameUtil;@Controller
@RequestMapping("/book")
public class BookController {// private Logger logger = Logger.getLogger(this.getClass());private String newFileName = "";private Book book = null;@Autowiredprivate BookService bookService;@RequestMapping(value="/upload",method=RequestMethod.POST)public void upload(HttpServletRequest req) throws Exception {MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;MultipartFile file = mreq.getFile("tupian");String fileName = file.getOriginalFilename();newFileName = "upload/" + FileNameUtil.getNewFileName(fileName);//E:/java/repository/Book_sm/src/main/webappString serverPath = req.getSession().getServletContext().getRealPath("/");System.out.println("保存路径:"+serverPath);//输出流,图片FileOutputStream fos = new FileOutputStream("E:/java/repository/Book_sm/src/main/webapp/"+newFileName);fos.write(file.getBytes());fos.flush();fos.close();}@RequestMapping(value="/saveBook",method=RequestMethod.POST)public String saveBook(HttpServletRequest req,Book book) throws Exception{upload(req);book.setBookname(ChineseEncoding.changeStr(book.getBookname()));book.setBookimg(newFileName);bookService.addBook(book);return "redirect:/book/page.action";}@RequestMapping("/delete")public String Delete(HttpServletRequest req,Book book) {bookService.deleteBookById(book.getBookid());return "redirect:/book/page.action";}@RequestMapping("/updateBook")public String updateBook(HttpServletRequest req,Book book) throws Exception {upload(req);book.setBookname(ChineseEncoding.changeStr(book.getBookname()));book.setBookimg(newFileName);bookService.updateBook(book);return "redirect:/book/page.action";}@RequestMapping("/page")public String page(HttpServletRequest req,ModelMap map) {int pageIndex = 1;if(req.getParameter("pageIndex") != null){pageIndex = Integer.parseInt(req.getParameter("pageIndex"));}map.addAttribute("pageIndex", pageIndex);map.addAttribute("books", bookService.getPageBooks(pageIndex));map.addAttribute("totalPage", bookService.getTotalPage());return "index";}}
JSP调用控制层,需要new一个控制层对象,但不在代码中出现,需要对控制层扫描,并开启注解,这时需要创建一个开启扫描控制层的xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns: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-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"><context:component-scan base-package="com.baidu.book.controller" /><!-- 开启MVC注解 --><mvc:annotation-driven /><!-- 设置spring:页面转发的路径前缀prefix,后缀suffix --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/" /><!-- 在根目录找 --><property name="suffix" value=".jsp" /><!-- 文件后缀为jsp --></bean></beans>
5.书写jsp页面
一,显示页面,进去可默认分页显示数据库中的内容,其实是调用了控制层的page方法,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>分页显示</title>
<style type="text/css">table tr td img{width:80px;height:100px;}
</style>
<script type="text/javascript">function gogo(){window.location = "page.action?pageIndex="+document.getElementsByName("pageIndex")[0].value;}</script>
</head>
<body><table border="1" width="80%" style="margin:0 auto; text-align:center;"><tr><td>编号</td><td>书名</td><td>价格</td><td>图片</td><td>操作</td></tr><c:forEach var="book" items="${books}"><tr><td>${book.bookid}</td><td>${book.bookname}</td><td>${book.bookprice}</td><td><img src="<%=basePath %>${book.bookimg}"/></td><td><a href="delete.action?bookid=${book.bookid}">删除</a><a href="<%=basePath %>updateBook.jsp?bookid=${book.bookid}&bookname=${book.bookname}&bookprice=${book.bookprice}&bookimg=${book.bookimg}">修改</a></td><tr></c:forEach><tr><td colspan="5"><c:if test="${pageIndex <= 1}">[上一页]</c:if><c:if test="${pageIndex > 1}"><a href='<%=basePath %>book/page.action?pageIndex=${pageIndex-1}'/> [上一页] </a></c:if><script >for(var i = 0;i<'${totalPage}';i++){document.write("<a href='<%=basePath %>book/page.action?pageIndex="+(i+1)+"'>[" + (i+1)+"]</a>"+"  ")}</script><c:if test="${pageIndex < totalPage}"><a href='<%=basePath %>book/page.action?pageIndex=${pageIndex+1}'/>[下一页]</a></c:if><c:if test="${pageIndex >= totalPage}">[下一页]</c:if>共${totalPage}页,当前第${pageIndex}页跳转至<input type="text" name="pageIndex" value="${pageIndex}" style="text-align:center;color:#666;"/>页<input type="button" value="跳转" onclick="gogo()"/><a href="<%=basePath %>addBook.jsp">添加一行</a></td></tr></table>
</body>
</html>
接下来是添加页面addBook.jsp,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!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>
<script type="text/javascript" src="js/jquery-1.7.js"></script>
<script type="text/javascript">$(function(){$("#picture").change(function(){var filePath = $(this).val(), //获取到input的value,里面是文件的路径fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式if( !fileFormat.match(/.png|.jpg|.jpeg|.gif/) ) {error_prompt_alert('上传错误,文件格式必须为:png/jpg/jpeg/gif');return; }$('#pic').attr('src',src);$("#pic").css({"width":"80px","height":"60px"});})})
</script>
</head>
<body><form action="book/saveBook.action" method="post" enctype="multipart/form-data"><table border="1" width="80%" style="margin:0 auto;text-align:center;"><tr><td>名称</td><td><input type="text" name="bookname"></td></tr><tr><td>价格</td><td><input type="text" name="bookprice"></td></tr><tr><td>图片</td><td><input type="file" name="tupian" id="picture"/><img id="pic" /></td></tr><tr><td colspan="2"><input type="submit" value="确认添加"></td></tr></table></form>
</body>
</html>
页面传到servlet的值可能会出现乱码,需要建一个类专门转换乱码的。
所以在创建一个package,名为com.baidu.book.util,包内创建一个类ChineseEncoding,内容如下:
package com.baidu.book.util;import java.io.UnsupportedEncodingException;public class ChineseEncoding {public static String changeStr(String input) {try {input = new String(input.getBytes("iso-8859-1"),"utf-8");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}return input;}}
在该包下,再创建一个类,主要是接受页面上传的文件,并起名,代码如下:
package com.baidu.book.util;import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;public class FileNameUtil {public static String getNewFileName(String filename) {Calendar calendar = Calendar.getInstance();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String fileName = sdf.format(calendar.getTime());String suffix = filename.substring(filename.lastIndexOf("."));return fileName + suffix;}}
接下来是修改页面update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改页面</title>
<script type="text/javascript" src="js/jquery-1.7.js"></script>
<script type="text/javascript">$(function(){$("#picture").change(function(){var filePath = $(this).val(), //获取到input的value,里面是文件的路径fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式if( !fileFormat.match(/.png|.jpg|.jpeg|.gif/) ) {error_prompt_alert('上传错误,文件格式必须为:png/jpg/jpeg/gif');return; }$('#pic').attr('src',src);$("#pic").css({"width":"80px","height":"60px"});})})
</script>
</head>
<body><form action="book/updateBook.action" method="post" enctype="multipart/form-data"><table border="1" width="80%" style="margin:0 auto; text-align:center;"><tr><td>编号</td><td><input type="text" value="${param.bookid }" name="bookid"/></td></tr><tr><td>名称</td><td><input type="text" value="${param.bookname }" name="bookname"/></td></tr><tr><td>价格</td> <td><input type="text" value="${param.bookprice }" name="bookprice"/></td></tr><tr><td>图片</td><td><input type="file" value="${param.bookimg }" name="tupian" id="picture"/><img src="<%=basePath %>${param.bookimg}" id="pic" /></td></tr><tr><td colspan="2"><input type="submit" value="确认修改"/></td></tr></table></form>
</body>
</html>
最后一个是详情页面,就是在index.jsp页面,操作一列中,删除、修改、详情【我没有写详情】详情就是book的具体属性。代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>书籍详情</title>
</head>
<body><table><tr><td>编号</td><td>${param.bookid}</td></tr><tr><td>名称</td><td>${param.bookname } /></td></tr><tr><td>价格</td> <td>${param.bookprice } /></td></tr><tr><td>图片</td><td><img src="<%=basePath %>${param.bookimg}" /></td></tr><tr><td colspan="2"><input type="submit" value="确认修改"/></td></tr></table>
</body>
</html>
最后,在webapp文件夹下的WEB-INF文件夹下的web.xml文件中开启扫描注解
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"><display-name>book_ssm</display-name><welcome-file-list><welcome-file>book/page.action</welcome-file></welcome-file-list><!-- 载入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><!-- 载入springmvc文件 --><servlet><servlet-name>DispatchServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>DispatchServlet</servlet-name><url-pattern>*.action</url-pattern><!-- 此处所有请求都由SPRINGMVC处理 --></servlet-mapping></web-app>
至此,简易项目告一段落,如果运行报了bug,请仔细检查,是不是路径的问题。
在下新手一个,有什么问题可以讨论一下,相互学习。。。谢了,
这篇关于简易版的SSM框架maven项目实现CRUD【增Create、查Retrieve、改Update、删Delete】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!