javamvc配置,增删改查,文件上传下载。

简介: 【10月更文挑战第4天】javamvc配置,增删改查,文件上传下载。

大的方向:mybatis是用于操作数据库的也就是dao层,
spring是用于整合mybatis连接,和处理service层,业务层
springmvc用于操作controller层(servilet层)接触前端用户。

SSM配置情况

Mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <package name="com.study.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/study/dao/BookMapper.xml" />
    </mappers>
</configuration>

日志功能

设置日志,这里使用的默认的STDOUT_LOGGING,
格式如下:

<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

设置别名

两种方式一种如每一个在包 com.study.pojo 中的 Java Bean,去包里找注解@Alias(""),如果找到了别名就是里面的,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。
另一种: <typeAlias type="com.study.pojo.User" alias="User"/>这种直接给这个类设置好别名了。
格式如下:

<typeAliases>
    <package name="com.study.pojo"/>
    <typeAlias type="com.study.pojo.User" alias="User"/>
</typeAliases>

映射注入

写一dao层的类,就需要在这里面加入。
注入映射接口,引入资源有三种方式,一种类映射, xml映射,包映射,
使用类映射和包映射需要配置文件名称和接口名称一致,并且位于同一目录下
而xml映射需要相对路径一致, 使用相对于类路径的资源引用。
格式如下:

<mappers>
    <mapper resource="com/study/dao/BookMapper.xml" />
    <mapper class="com.study.dao.BookMapper" />
    <package name="com.study.dao"/>
</mappers>

Spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  https://www.springframework.org/schema/context/spring-context.xsd">
  <!-- 配置整合mybatis -->
  <!-- 1.关联数据库文件 -->
  <!--    加载数据库相关文件-->
  <context:property-placeholder location="classpath:database.properties"/>
  <!-- 2.数据库连接池 -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!-- 配置连接池属性 -->
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
  </bean>
  <!-- 3.配置SqlSessionFactory对象 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 注入数据库连接池 -->
    <property name="dataSource" ref="dataSource"/>
    <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
  </bean>
  <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
  <!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 注入sqlSessionFactory -->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!-- 给出需要扫描Dao接口包 -->
    <property name="basePackage" value="com.study.dao"/>
  </bean>
</beans>

关联数据库文件

取出用于数据库连接池

数据库连接池

通过连接数据库,需要账户密码等
数据库连接池有很多:dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)

配置SqlSessionFactory对象

单例模式,为了创建SqlSession对象来操作数据库。而 SqlSession 是执行持久化操作的会话对象。通过 SqlSession,我们可以执行映射的 SQL 语句。
其中配置数据库连接池,并配置MyBaties全局配置文件,关联到mybatis文件。

配置扫描Dao接口包,动态实现Dao接口注入到spring容器中

加上这个目的是为了动态注入

Spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

<!--    1.扫描service相关的bean-->
    <context:component-scan base-package="com.study.service"/>
<!--    2.BookServiceImpl 注入到IOC容器中-->
    <bean id="BookServiceImpl" class="com.study.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

扫描service相关的bean

将service实体类注入IOC容器中,(代理)

配置事务管理器

Spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--    配置springmvc-->
<!--    1.开启springmvc注解驱动-->
    <mvc:annotation-driven/>
<!--    2.静态资源默认serlet配置-->
    <mvc:default-servlet-handler/>

<!--    3.配置jsp显示viewResolver视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--        这一个目前没有接触到!!!!-->
<!--        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

<!--    4. 扫描web相关的bean-->
    <context:component-scan base-package="com.study.controller" />
</beans>

开启springmvc注解驱动

静态资源默认servlet配置

配置jsp显示viewResolver视图解析器

解析时,加上前后缀

扫描web相关的bean

就是扫描controller层的文件中的@Controller注解,如果类中有@Controller就是交给springmvc代理了。

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->   
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

注册DispatcherServlet并设置servlet-mapping

过滤器及映射

Session过期时间(可以不设置)

整合总的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    整合-->
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-config.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

SSM整合记录-增删改查

主要就是编写controller层

@Controller
@RequestMapping("/book")
public class BookController {
   

    //自动注入依赖,自动装配
    //对Aurowired更精准化的注入
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allbook")
    public String allBook(Model model) {
   
        List<Books> books = bookService.queryBookByName();
        model.addAttribute("list", books);
        return "allbook";
    }

    //跳转到添加页面
    @RequestMapping("/add")
    public String addBook() {
   
        return "add";
    }

    @RequestMapping("/addBook")
    public String addBooks(Books book) {
   
        System.out.println(book);
        bookService.addBook(book);
        return "redirect:/book/allbook"; //重定向到
    }

    //跳转到修改界面
    @RequestMapping("/toUpData")
    public String  toUpData(int id,Model model) {
   
        Books books = bookService.queryBookById(id);
        model.addAttribute("book",books);
        return "updata";
    }

    // 修改书籍
    @RequestMapping("/upData")
    public String updateBook(Books book,Model model) {
   
        System.out.println(book);
        bookService.updateBook(book);
        Books books = bookService.queryBookById(book.getBookID());
        model.addAttribute("books",books);
        return "redirect:/book/allbook";
    }

    //删除书籍
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
   
        bookService.deleteBook(id);
        return "redirect:/book/allbook";
    }


    //查询名字
    @RequestMapping("/queryBook")
    public String queryBookName(String queryBookName,Model model) {
   
        Books book = bookService.queryBookByBookName(queryBookName);
        ArrayList<Books> books = new ArrayList<>();
        books.add(book);
        System.out.println(books);
        model.addAttribute("list", books);
        return "allbook";
    }

    @RequestMapping("/queryName")
    public String queryName(String queryBookName,Model model) {
   
        List<Books> books = bookService.queryName(queryBookName);
        model.addAttribute("list", books);
        return "allbook";
    }

}

前端jsp页面。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表 —— 显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/add">新增</a>
        </div>
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allbook">显示所有书籍</a>
        </div>
        <div class="col-md-4 column">
            <form class="form-inline" action="${pageContext.request.contextPath}/book/queryName" method="post" style="float: right">
                <input type="text" name="queryBookName" class="form-control" placeholder="输入查询书名" required>
                <input type="submit" value="查询" class="btn btn-primary">
            </form>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名字</th>
                    <th>书籍数量</th>
                    <th>书籍详情</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="book" items="${requestScope.get('list')}">
                    <tr>
                        <td>${book.getBookID()}</td>
                        <td>${book.getBookName()}</td>
                        <td>${book.getBookCounts()}</td>
                        <td>${book.getDetail()}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpData?id=${book.getBookID()}">更改</a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

这里主要说一下对应关系的问题,
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>那这个举例,点击这个按钮会跳转到/book/del这个界面,并且携带者${book.getBookID()这个信息。
下面@RequestMapping("/del/{bookId}")这个表示进入这个界面需要走下面这个函数,首先带来了一个bookId,那么我们在执行时可以通过id而进行数据库中的操作删除。然后重定向,注意这里是重定向。不是转发不是转发不是转发!!!!!!。

//删除书籍
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
   
        bookService.deleteBook(id);
        return "redirect:/book/allbook";
    }

model.addAttribute("list",books);这个是java后端返回给前端的信息,返回的是json键值对信息,前端调用直接用${requestScope.get('list')}可以拿到。

springmvc-文件上传下载

首先前端表单要有要求,为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data,只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;
对表单中的enctype属性做个详细的说明:
● application/x-www=form-urlencoded:默认方式,只处理表单域中的value属性值,采用这种编码方式的表单会将表单域中的值处理成URL编码方式。
● multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
● text/plain: 除了把空格转换为"+"号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。

<form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload">
  </form>

文件上传

首先导入依赖包:

<!--文件上传-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

并配置bean:在springmvc中配置

<!--文件上传配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

主要用的方法:
● String getOriginalFilename():获取上传文件的原名
● InputStream getInputStream():获取文件流
● void transferTo(File dest):将上传文件保存到一个目录文件中

Controller层:

@Controller
public class FileController {
   
    //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
    //批量上传CommonsMultipartFile则为数组即可
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
   
        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();
        //如果文件名为空,直接回到首页!
        if ("".equals(uploadFileName)){
   
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名 : "+uploadFileName);
        //上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        //如果路径不存在,创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
   
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址:"+realPath);
        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = Files.newOutputStream(new File(realPath, uploadFileName).toPath()); //文件输出流
        //读取写出
        int len=0;
        byte[] buffer = new byte[1024];
        while ((len=is.read(buffer))!=-1){
   
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return "redirect:/index.jsp";
    }
}

另一种方式:采用file.Transto来保存上传的文件:

@RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
   
        //上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
   
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址"+path);
        //通过CommonMultipartFile的方法直接写文件
        file.transferTo(new File(realPath, Objects.requireNonNull(file.getOriginalFilename())));
        return "redirect:/index.jsp";
    }

文件下载:

步骤:

  1. 设置 response 响应头
  2. 读取文件 — InputStream
  3. 写出文件 — OutputStream
  4. 执行操作
  5. 关闭流 (先开后关)

    @RequestMapping("/download")
     public String fileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
         
         //要下载的图片地址
         String path = request.getSession().getServletContext().getRealPath("/upload");
         String image = "1.png";
         //设置response响应头
         response.reset();//设置页面不缓存,清空buffer
         response.setCharacterEncoding("utf-8");//字符编码
         response.setContentType("multipart/form-data");//二进制传输数据
         //设置响应头
         response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(image, "UTF-8"));
    
         File file = new File(path, image);
    
         //读取文件-输入流
         InputStream in = new FileInputStream(file);
         //写入文件 输出流
         OutputStream out = response.getOutputStream();
         byte[] buffer = new byte[1024];
         int index=0;
         //执行写入操作
         while ((index=in.read(buffer))!=-1){
         
             out.write(buffer,0,index);
             out.flush();
         }
         in.close();
         out.close();
         return "ok";
    
     }
    
目录
相关文章
|
4天前
|
编解码 Java 程序员
写代码还有专业的编程显示器?
写代码已经十个年头了, 一直都是习惯直接用一台Mac电脑写代码 偶尔接一个显示器, 但是可能因为公司配的显示器不怎么样, 还要接转接头 搞得桌面杂乱无章,分辨率也低,感觉屏幕还是Mac自带的看着舒服
|
6天前
|
存储 缓存 关系型数据库
MySQL事务日志-Redo Log工作原理分析
事务的隔离性和原子性分别通过锁和事务日志实现,而持久性则依赖于事务日志中的`Redo Log`。在MySQL中,`Redo Log`确保已提交事务的数据能持久保存,即使系统崩溃也能通过重做日志恢复数据。其工作原理是记录数据在内存中的更改,待事务提交时写入磁盘。此外,`Redo Log`采用简单的物理日志格式和高效的顺序IO,确保快速提交。通过不同的落盘策略,可在性能和安全性之间做出权衡。
1551 7
|
1月前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
9天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
639 25
|
6天前
|
存储 SQL 关系型数据库
彻底搞懂InnoDB的MVCC多版本并发控制
本文详细介绍了InnoDB存储引擎中的两种并发控制方法:MVCC(多版本并发控制)和LBCC(基于锁的并发控制)。MVCC通过记录版本信息和使用快照读取机制,实现了高并发下的读写操作,而LBCC则通过加锁机制控制并发访问。文章深入探讨了MVCC的工作原理,包括插入、删除、修改流程及查询过程中的快照读取机制。通过多个案例演示了不同隔离级别下MVCC的具体表现,并解释了事务ID的分配和管理方式。最后,对比了四种隔离级别的性能特点,帮助读者理解如何根据具体需求选择合适的隔离级别以优化数据库性能。
209 3
|
1天前
|
Java 开发者
【编程进阶知识】《Java 文件复制魔法:FileReader/FileWriter 的奇妙之旅》
本文深入探讨了如何使用 Java 中的 FileReader 和 FileWriter 进行文件复制操作,包括按字符和字符数组复制。通过详细讲解、代码示例和流程图,帮助读者掌握这一重要技能,提升 Java 编程能力。适合初学者和进阶开发者阅读。
100 60
|
13天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
615 5
|
12天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
2天前
vue3+Ts 二次封装ElementUI form表单
【10月更文挑战第8天】
107 56
|
25天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。