SSM上传文件(增、改、查)

目录

一、在页面查询中出图片

二、增加

1.在controller文件夹中找到增加写下列代码

 2.在增加的JSP代码中填写下列代码

3.写对出来是下面这样的

三、修改

1.在controller文件夹中找到修改写下列代码

2.在修改JSP中写入下列代码(一定要记得在form标签里面上加   method="post"                                                  enctype="multipart/form-data")

3.修改成功后就是下面的效果了

         四、完成上面的步骤,上传就完成了

五、下面是配置文件的内容,如果大家有和我不一样有错误的可以进行修改

1.先看一下有哪些配置文件

 2. application.xml文件内容

3.log4j2.xml文件内容

4.mybatis.xml文件内容

5.springmvc.xml文件夹内容


一、在页面查询中出图片

1.创建一个名叫uploadfiles的文件夹(用于存放照片)

2.在 JSP查询页面中写入这个(显示图片)

二、增加

1.在controller文件夹中找到增加写下列代码

@RequestMapping("/add")
    public String add(Books books, HttpServletRequest request, HttpServletResponse response) throws IOException {
        return "add.jsp";
    }
    @RequestMapping("/adds")
//    MultipartFile后面是自己定义的图片名
    public String addbooks(Books books, MultipartFile tupian, HttpServletRequest request){
        String fileType = tupian.getOriginalFilename();
        int index = fileType.lastIndexOf(".");
        fileType = fileType.substring(index);
        String path = request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfiles");
        long filename = System.currentTimeMillis();
        File file = new File(path+"\\"+filename+fileType);
        try {
            tupian.transferTo(file);
        }catch (IOException e){
            e.printStackTrace();
        }
//        setType是bean里面图片的名字
        books.setType(filename+fileType);
        System.out.println("DEBUG————》》》"+books);
        booksService.add(books);

        return "redirect:/books/list"; //重定向到list实现页面的复用
    }

 2.在增加的JSP代码中填写下列代码

3.写对出来是下面这样的

三、修改

1.在controller文件夹中找到修改写下列代码

  @RequestMapping("/updateid")
//    MultipartFile 后面是自己定义的图片名
    public String updateid(Books books,MultipartFile xiugaizhaopian,HttpServletRequest request){
        String fileType=xiugaizhaopian.getOriginalFilename();
        int index=fileType.lastIndexOf(".");
        fileType=fileType.substring(index);
        String path=request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfiles");
        long filename=System.currentTimeMillis();//获取当前时间时间戳
        File file=new File(path+"\\"+filename+fileType);
        try {
            xiugaizhaopian.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
//      setType是实体类里面图片的名字
        books.setType(filename+fileType);

        booksService.update(books);
//       自己查询的地址
        return "redirect:/books/list";
    }

2.在修改JSP中写入下列代码(一定要记得在form标签里面上加   method="post"                                                  enctype="multipart/form-data")

<head>
    <title>修改用户</title>
</head>
<body>
<form action="/books/updateid"  method="post"  enctype="multipart/form-data">
    <h1>修改用户</h1><hr />
    <table class="table table-condensed table-striped">
        <tbody>
        <input hidden="hidden" type="text" id="id" name="id" value=${lists.id} >
        <tr>
            <td>
                图书名称
            </td>
            <td>
                <input type="text" value=${lists.name} name="name">
            </td>
        </tr>
        <tr>
            <td>
                图书作者
            </td>
            <td>
                <input type="text" value=${lists.author} name="author">
            </td>
        </tr>
        <tr>
            <td>
                图片
            </td>
            <td>
<%--                xiugaizhaopian名字是controller文件夹中定义的图片名--%>
                <input  type="file" name="xiugaizhaopian">
            </td>
        </tr>
        </tbody>
    </table>
    <input type="submit" value="提交" />
</form>

</body>
</html>

3.修改成功后就是下面的效果了

 四、完成上面的步骤,上传就完成了

   有想看分页的去我主页找smm分页

五、下面是配置文件的内容,如果大家有和我不一样有错误的可以进行修改

1.先看一下有哪些配置文件

 2. application.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:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
" >
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username1}"></property>
        <property name="password" value="${pwd}"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
     </bean>

    <!-- 专门扫描mapper接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xinxi2.mapper"></property>
    </bean>

    <!-- 扫描@component的 -->
    <context:component-scan base-package="com.xinxi2"></context:component-scan>

    <!-- 数据源事务管理器 ioc,指定管理的数据源 -->

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" autowire="byName" >
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 事务管理器增强,配置方法的事务传播机制 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="servicePointcut"
                      expression="execution(* com.xinxi2.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"></aop:advisor>
    </aop:config>
</beans>

3.log4j2.xml文件内容

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="Console"/>
        </Root>
        <Logger name="org.springframework.jdbc.core" level="debug"/>
        <Logger name="org.springframework.jdbc.core.StatementCreatorUtils" level="trace"/>
    </Loggers>
</Configuration>

4.mybatis.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="LOG4J"/>
    </settings>


    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

5.springmvc.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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <context:component-scan base-package="com.xinxi2.controller,com.xinxi2.service"></context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <!-- Date的日期转换器 -->
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 配置多视图解析器 -->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 是否启用参数支持,默认为true(支持),即xxx?format=json、xml等形式。 -->
        <property name="favorParameter" value="true" />
        <!-- favorPathExtension:是否支持扩展名,默认为true(支持),扩展名指xxx.json、xxx.xml等形式 -->
        <property name="favorPathExtension" value="true" />
        <!-- 默认ContentType -->
        <property name="defaultContentType" value="application/json" />
        <!-- 配置映射关系 -->
        <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用  -->
        <property name= "mediaTypes">
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            </value>
        </property>
    </bean>
    <!-- VIEW解析定义。内容协商视图解析器;根据contentNegotiationManager使用的不同mediaTypes决定不同的 view进行响应  默认使用json-->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

        <!-- 内容协商管理器 用于决定media type -->
        <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
        <!-- 默认视图 解析 -->
        <property name="defaultViews">
            <list>
                <bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView">
                    <property name="charset" value="UTF-8"/>
                </bean>
            </list>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/"/>
                    <property name="suffix" value=""/>
                </bean>
            </list>
        </property>
    </bean>

    <!-- 解决静态资源的加载问题 -->
    <mvc:resources mapping="/staticabc/**" location="/static/"></mvc:resources>



    <!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>


</beans>

六、大家有不会的有bug可以私信我,再或者我这个代码有问题的欢迎来私信我

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SSM是指Spring+SpringMVC+MyBatis,是一个JavaWeb开发框架。下面我将为您介绍SSM框架中的文件上传下载和操作。 文件上传下载: 1.上传文件 (1)在SpringMVC的配置文件中添加multipartResolver ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> ``` (2)在Controller中添加上传文件处理方法 ``` @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) { if (!file.isEmpty()) { try { String fileName = file.getOriginalFilename(); String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; File dest = new File(filePath + fileName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } file.transferTo(dest); return "success"; } catch (Exception e) { e.printStackTrace(); } } return "error"; } ``` 2.下载文件 (1)在Controller中添加下载文件处理方法 ``` @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletRequest request, HttpServletResponse response) { String fileName = "xxx.jpg"; //文件名 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; File file = new File(filePath + fileName); if (file.exists()) { response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` : 1.加数据 (1)在Mapper中添加insert方法 ``` public void insert(User user); ``` (2)在Service中添加insert方法 ``` public void insert(User user) { userMapper.insert(user); } ``` (3)在Controller中添加insert处理方法 ``` @RequestMapping(value = "/insert", method = RequestMethod.POST) public String insert(User user) { userService.insert(user); return "success"; } ``` 2.删除数据 (1)在Mapper中添加delete方法 ``` public void delete(int id); ``` (2)在Service中添加delete方法 ``` public void delete(int id) { userMapper.delete(id); } ``` (3)在Controller中添加delete处理方法 ``` @RequestMapping(value = "/delete", method = RequestMethod.GET) public String delete(int id) { userService.delete(id); return "success"; } ``` 3.修数据 (1)在Mapper中添加update方法 ``` public void update(User user); ``` (2)在Service中添加update方法 ``` public void update(User user) { userMapper.update(user); } ``` (3)在Controller中添加update处理方法 ``` @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(User user) { userService.update(user); return "success"; } ``` 4.询数据 (1)在Mapper中添加select方法 ``` public List<User> selectAll(); ``` (2)在Service中添加selectAll方法 ``` public List<User> selectAll() { return userMapper.selectAll(); } ``` (3)在Controller中添加selectAll处理方法 ``` @RequestMapping(value = "/selectAll", method = RequestMethod.GET) public String selectAll(Model model) { List<User> userList = userService.selectAll(); model.addAttribute("userList", userList); return "userList"; } ``` PS:以上代码仅供参考,具体实现需要根据具体业务需求进行修
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值