springmvc实现文件上传&&书本管理CRUD

今天小编给大家分享文件上传,和对书本管理进行新增、修改、删除、查询。

效果展示

首页

新增 

修改

 

一、书本管理CRUD 

1.开发前必做的配置

1.1 导入pom.xml文件依赖

实现CRUDspringmvc的jar包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>

 jstl标签库与c标签导入依赖

<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
</dependency>
防止Spring内存溢出监听器 
<listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>

 中文编码处理

随后小编为大家提供的web.xml,在文章最后部分,将入项目并在web.xml中配置,以便于处理中文编码。

<!-- 中文乱码处理 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--web.xml 3.0的新特性,是否支持异步-->
        <async-supported>true</async-supported>
        <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>

开发之前必须要写一个springmvc配置文件,文章最后会附上完整的sringmvc.xml文件

springmvc.xml有以下要点:

1.扫描指定类与包,use-default-filter表示只扫描该类
<context:component-scan base-package="com.zking" use-default-filters="false">

2.ViewResolver表示控制器读取显示项目目标位置, prefix:项目路径名前部分 suffix:项目路径名后部分

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
    <property name="viewClass"
              value="org.springframework.web.servlet.view.JstlView"></property>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

2.以下是后台实现代码

以下注解:

//生成set,get和toStirng方法
@Data
//表示无参构造器
@NoArgsConstructor
//表示有参构造器
@AllArgsConstructor

@Repository:表示它是数据访问层

@Service:表示它是业务逻辑层

model层

 mapper层

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zking.mybatis.mapper.Ibookmapper">
    <insert id="addBooks">
        insert into t_book(bname,price,type,info)
        values(#{bName},#{price},#{type},#{info})
    </insert>

    <update id="editBooks">
   update t_book set bName=#{bName},price=#{price},type=#{type},info=#{info}
        where bid =#{bid}
    </update>

    <delete id="delBooks">
    delete from t_book where bid=#{bid}
    </delete>

    <select id="listBook" resultType="com.zking.mybatis.model.Book">
        select bid,bname bName,price,type,info from t_book
        <where>
            <if test="bName != null and bName !=''">
                and bname like concat('%',#{bName},'%')
            </if>
        </where>
    </select>

    <select id="cxdg" resultType="com.zking.mybatis.model.Book">
        select bid,bname bName,price,type,info from t_book where bid=#{bid}
    </select>
</mapper>

Connllert层

以下注解:

  • @Controller:该注解在springmvc中用于标记一个控制器,类似的注解还有@RestController:相当于@ResponseBody + @Controller合在一起的作用。
  • @RequestMapping:该用于标记请求路径,在有些参考资料中也称之为服务端点。该注释可以用在方法上也可以用在类上。

新增页面

 修改页面

 删除页面

编写一个简单的controller

@Controller
public class BookController {

    @Autowired
    private Ibookservice service;

    @RequestMapping("listBook")
    public String listBook(Book book, Model model){
        List<Book> bookList = service.listBook(book);
        model.addAttribute("listBook",bookList);
        return "book/index";
    }

    @RequestMapping("addBook")
    public String addBook(){
        return "book/add";
    }

    @RequestMapping("addsBook")
    public String addsBook(Book book){
        service.addBooks(book);
        return "redirect:/listBook";
    }

    @RequestMapping("opendel")
    public String delBook(Book book){
        service.delBooks(book);
        return "redirect:/listBook";
    }

    @RequestMapping("updbook")
    public String updBook(Book book,Model model){
        Book book1 = service.cxdg(book);
        model.addAttribute("book",book1);
        return "book/update";
    }

    @RequestMapping("updsbook")
    public String updsBook(Book book){
        service.editBooks(book);
        return "redirect:/listBook";
    }

}

service层

@Service
public class Bookserviceimpl implements Ibookservice{

    @Autowired
    private Ibookmapper bookmapper;

    @Override
    public List<Book> listBook(Book book){
        return  bookmapper.listBook(book);
    }

    @Override
    public void addBooks(Book book) {
        bookmapper.addBooks(book);
    }

    @Override
    public void editBooks(Book book) {
        bookmapper.editBooks(book);
    }

    @Override
    public void delBooks(Book book) {
        bookmapper.delBooks(book);
    }

    @Override
    public Book cxdg(Book book) {
        return bookmapper.cxdg(book);
    }
}

3.以下是前台实现代码 

index

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>书本首页</title>
</head>
<body>
<div style="text-align: center">

        <h2>小欣书本首页</h2>
<form action="<%=request.getContextPath()%>/listBook" method="get">
    <label>书本名称:</label>
    <input type="text" name="BName">
    <input type="submit" value="查询" >
    <a href="<%=request.getContextPath()%>/addBook">添加</a>
</form>
<table border="1" width="100%">
    <thead>
    <tr>
        <th>ID</th>
        <th>名称</th>
        <th>价格</th>
        <th>类型</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${listBook}" var="b">
        <tr>
            <td>${b.bid}</td>
            <td>${b.BName}</td>
            <td>${b.price}</td>
            <td>${b.type}</td>
            <td>${b.info}</td>
            <td>
                <a href="<%=request.getContextPath()%>/opendel?bid=${b.bid}">删除</a>
                <a href="<%=request.getContextPath()%>/updbook?bid=${b.bid}">修改</a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
</div>
</body>
</html>

add

update

最...

后小遍给大家 

附上完整的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: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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <!--<context:component-scan base-package="com.zking.zf"/>-->

    <!--1) use-dafault-filters="false"的情况下,根据表达式包含(include-filter)或排除(exclude-filter)指定包-->
    <context:component-scan base-package="com.zking" use-default-filters="false">
        <!--<context:include-filter type="regex" expression=".+\.controller\..*"/>-->
        <!--<context:exclude-filter type="regex" expression=".+\.controller2\..*"/>-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
	<!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--3) ViewResolver     prefix:项目路径名前部分     suffix:项目路径名后部分  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--4) 单独处理图片、样式、js等资源 -->
    <mvc:resources location="/static/" mapping="/static/**" cache-period="31536000"/>

</beans>

  附上完整的web文件

<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和web项目集成start -->
    <!-- spring上下文配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext*.xml</param-value>
    </context-param>
    <!-- 读取Spring上下文的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring和web项目集成end -->

    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- 中文乱码处理 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--web.xml 3.0的新特性,是否支持异步-->
        <async-supported>true</async-supported>
        <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>

    <!-- Spring MVC servlet -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/spring-mvc.xml</param-value>
        </init-param>
        <!--表示容器启动时就加载该servlet-->
        <load-on-startup>1</load-on-startup>
        <!--web.xml 3.0的新特性,是否支持异步-->
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

二、文件上传、下载 

1、编写数据库生成模型

后面编写mapper层,会对t_book表进行修改操作

后面编写mapper层,会对t_book_file表进行新增操作

 

t_book_file数据库

create table t_book_file
(
  file_id varchar(32) primary key comment '文件ID',
  real_name varchar(50) not null comment '文件名称',
  content_type varchar(50) not null comment '文件类型',
  url varchar(256) not null comment '文件路径'
);

2.在pom.xml文件中导入依赖的包:

代码如下 

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

3. 配置文件上传解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
  </bean>

4..编写mapper层

    int addUploadRecord(BookFile bookFile);

    int updatBook(Book book);

    BookFile loadBookFile(BookFile bookFile);
<insert id="addUploadRecord">
        insert into t_book_file(file_id, real_name, content_type, url)
        values(#{fileId}, #{realName},#{contentType},#{url})
    </insert>

  <update id="updatBook">
        update t_book set file_id = #{FileId} where bid = #{bid}
    </update>

 <select id="loadBookFile" resultType="com.zking.spring.model.BookFile">
        select file_id fileId,real_name realName, content_type contentType, url
        from t_book_file where file_id=#{fileId}
    </select>

5.编写controller控制器

@Controller
public class UoloadController {
    //设置文件上传地址
    private final  String UPLOAD_PATH="/upload";

    @Autowired
    private IBookservice bookservice;

    @RequestMapping("/openUploadPage")
    public String openUploadPage(Book book, Model model,HttpServletRequest req){
        //获取index页面传来的id对象
        String bid = req.getParameter("id");
        model.addAttribute("bid",Integer.valueOf(bid));
        return "Book/upload";//跳转到文件上传页面(修改方法)
    }

    @RequestMapping("/upload")
    public  String upload(MultipartFile img, HttpServletRequest req) throws IOException {
        /*MultipartFile img 上传图片路径*/
        //获取虚拟图片名字
        String fname = img.getOriginalFilename();
        //生成随机字符串
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取相对路径
        String path = UPLOAD_PATH + File.separatorChar + fname;
        //获取绝对路径(将相对路径放到绝对路径下)
        String realPath = req.getServletContext().getRealPath(path);
        //获取文件目标方法
        File targetFile = new File(realPath);
        //保存文件
        img.transferTo(targetFile);

        //更新文件(修改t_book表数据)
        String bid = req.getParameter("bid");
        Book book=new Book();
        book.setBid(Integer.parseInt(bid));
        book.setFileId(uuid);
        //修改方法
        bookservice.updatBook(book);

        //添加到t_book_file表
        String contentType = img.getContentType();
        BookFile bookFile = new BookFile();
        bookFile.setFileId(uuid);
        bookFile.setRealName(fname);
        bookFile.setContentType(contentType);
        bookFile.setUrl(path);
        //新增方法
        bookservice.addUploadRecord(bookFile);

        return  "redirect:/listBook";//跳转到index页面
    }

upload.jsp文件上传

 

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>图片上传</h2>

<form action="<%=request.getContextPath()%>/upload" enctype="multipart/form-data" method="post">
    <input type="hidden" name="bid" value="${bid}">
    <input type="file" name="img">
    <input type="submit" value="上传">

</form>
</body>
</html>

6.上传成功后验证

上传完后进行查询,如果数据库出现这些数据说明上传成功

t_book表与t_file表关联属性file_id 

t_book_file表新增的数据 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值