Spring MVC: forwarding and redirection, image file upload, Jason

Posted by ruben- on Tue, 10 Dec 2019 23:46:04 +0100

Be careful:

Project: war and project: war expanded

They are not the same. idea runs the project: war expanded

 

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

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


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.7</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.7</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.7</version>
        </dependency>

Required dependencies:

Commons file upload: file upload

jackson.core: three jackson packages

 

web.xml, Springmvc.xml, as configured in the previous issue

 

package com.hc.controller;

import com.hc.entity.Point;
import com.hc.entity.Student;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FirstController {

    @RequestMapping("load")
    public String load(MultipartFile file,HttpServletRequest request){

//        System.out.println("name \ t"+file.getOriginalFilename());
//        System.out.println("size \ t"+file.getSize());
//        System.out.println("name\t"+file.getName());
//
//        System.out.println("file path \ t"+request.getRealPath("/images"));
//+System.currentTimeMillis()
        String path=request.getRealPath("/images");
        File f=new File(path+"/"+file.getOriginalFilename());
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    @RequestMapping("point")
    public String point(Point point){
        System.out.println(point);
        return "success";
    }

    @RequestMapping("first")
    public String first(HttpServletRequest request){
        request.setAttribute("id",12);
        return "forward:forWard.action";
    }

    @RequestMapping("forWard")
    public String forWard(HttpServletRequest request){
        System.out.println("forWard\t"+request.getAttribute("id"));
        return "success";
    }


    @ResponseBody
    @RequestMapping("json")
    public Map<String,Object> json(){
        Map<String,Object> map=new HashMap<>();

        List<Student> studentList=new ArrayList<>();
        studentList.add(new Student("word","female",12));
        studentList.add(new Student("still","male",32));

        map.put("size",studentList.size());
        map.put("students",studentList);
        return map;
    }

}

 

1.forward: can forward data

Forwarding: data can be forwarded to the page without change of address

Redirect: skip to another page without transferring data, and the address will change to the target page.

 

2.ResponseBody: automatic conversion

More convenient than fastjson

Data in json format

{"size":2,"students":[{"stuId":0,"stuName":"word","stuSex":"female","stuAge":12},{"stuId":0,"stuName":"still","stuSex":"male","stuAge":32}]}

 

3. Collect date data of util

user:

import java.util.Date;

public class Users {
    private String uname;
    private String upwd;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

}

Turn on the DateTimeFormat annotation on the attributes that need special collection for entity classes

<mvc:annotation-driven></mvc:annotation-driven>

Configuring annotation driver in spring MVC

 

4. Collect coordinates

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

<form action="/load.action" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="load">
</form>



first

<a href="/first.action">success</a>

<form action="/point.action" method="post">
    <input type="text" name="point">
    <input type="submit" value="ok">
</form>


</body>
</html>

Coordinate format: (2, 3)

First, customize the converter

package com.hc.controller;

import com.hc.entity.Point;
import org.springframework.core.convert.converter.Converter;

public class PointConverter implements Converter<String,Point> {
    @Override
    public Point convert(String s) {
        String[] strings=s.split("-");
        int x=Integer.parseInt(strings[0]);
        int y=Integer.parseInt(strings[1]);
        Point point=new Point(x,y);
        return point;
    }
}

Build a point object with properties x and y

Configure a custom converter

<bean id="converters" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <bean class="com.hc.controller.PointConverter"></bean>
        </property>
    </bean>

    <mvc:annotation-driven conversion-service="converters"></mvc:annotation-driven>

Split by - in the middle

For example: 667-87, it will be formatted as (667, 87)

Encapsulate tostring method in point class, the effect will be obvious

 

5. Picture upload

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="2097152"></property>
    </bean>

Set the default encoding to UTF-8

The maximum upload size is: 1024 * 1024 * 2 = 2097152 2M

<form action="/load.action" method="post" enctype="multipart/form-data">
form upload method is POST

The name of the selection box is the same as the variable name of the MultipartFile parameter of the controller method

 

file.getOriginalFilename(): picture name

If you need System.currentTimeMillis(), add a time stamp.

Because if a file with the same name is uploaded, the existing one will be overwritten.

 

file.getSize(): picture size

request.getRealPath("/images"): get the path of images on the server

try catch: Alt + ENTER

 

 

 

 

Topics: Mobile Java JSON Spring xml