Spring MVC annotation and file upload

Catalog:

Annotation of spring MVC

File upload (upload image and display)

I. annotations

Add @ Controller before the class to indicate that the class is a Controller
Add @ RequestMapping("/index") before the handleRequest method to indicate that the path / index will be mapped to the method

Change the previous blog to annotate:

Basic configuration and view orientation of spring MVC

1. Modify springmvc-servlet.xml

Remove the mapping related configuration, because the annotation method has been used
increase
<context:component-scan base-package="controller" />
Indicates to scan the class annotated with @ Controller from the package Controller

2. Modify IndexController

@Controller
public class IndexController {
    @RequestMapping("/index")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("message", "Hello Spring MVC");
        return mav;
    }
}

There is no need to implement the Controller interface

II. File upload

1. Configure web.xml to allow access to jpg files

<?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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.4">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
  </servlet-mapping>
</web-app>

2. Configure springmvc-servlet.xml to open support for upload function

<?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-3.0.xsd
    http://www.springframework.org/schema/context         
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <context:component-scan base-package="controller" />
    <bean id="irViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

</beans>

3. upload.jsp file upload page

<form action="uploadImage" method="post" enctype="multipart/form-data">
  //Choose a picture:<input type="file" name="image" accept="image/*" /> <br>
  <input type="submit" value="upload">
</form>

4. Prepare the UploadedImageFile to encapsulate the field image of MultipartFile type, which is used to accept the page injection

package pojo;

import org.springframework.web.multipart.MultipartFile;

public class UploadedImageFile {
    MultipartFile image;
 
    public MultipartFile getImage() {
        return image;
    }
 
    public void setImage(MultipartFile image) {
        this.image = image;
    }
 
}

Be careful:

The field image here must be the same as the image in upload.jsp
<input type="file" name="image" accept="image/*" />
Bring into correspondence with

5. UploadController upload controller

package controller;

import java.io.File;
import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.lang.xwork.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import pojo.UploadedImageFile;
 
@Controller
public class UploadController {
 
    @RequestMapping("/uploadImage")
    public ModelAndView upload(HttpServletRequest request, UploadedImageFile file)
            throws IllegalStateException, IOException {
        //Random number is used to name the image to prevent the original file from being overwritten by the same file name
        String name = RandomStringUtils.randomAlphanumeric(10);
        String newFileName = name + ".jpg";
        //Obtain web Directory image Directory to store uploaded files
        File newFile = new File(request.getServletContext().getRealPath("/image"), newFileName);
        newFile.getParentFile().mkdirs();
        //Copy file
        file.getImage().transferTo(newFile);
        //Pass the generated random file name to the view for display
        ModelAndView mav = new ModelAndView("showUploadedFile");
        mav.addObject("imageName", newFileName);
        return mav;
    }
}

6. Display image showUploadedFile.jsp

Note: create a new jsp file in the page directory

<img src="image/${imageName}"/>

Tags: Java xml Spring JSP

Posted on Sat, 09 Nov 2019 11:29:44 -0800 by Stasonis