SpringMVC study five, JSON, and file upload and FastJson

JSON

Separate front and rear ends

  • Back-end back-end deployment, providing an interface: provides an interface

    ​ JSON

  • Independent deployment front-end, back-end is responsible for rendering data:

JSON (JavaScript Object Notation, JS object tag) is a lightweight data-interchange format

JSON using entirely independent of programming language text is stored and data representing

Simple and clear hierarchy make JSON an ideal data-interchange language

Easy to read and write, but also easy for machines to parse and generate. And effectively improve network transmission efficiency

In the JavaScript language, everything is an object. Thus, any type of support JavaScript can be represented by the JSON, such as strings, numbers, objects, arrays and the like.

  • When the object is a key-value pair data separated by commas
  • Save Object braces
  • Save array square brackets

JSON key-value pair wording is one way to save the JavaScript object, and also similar JavaScript object, key / value pair combination EDITORIAL keys and double quotation marks "" package, colon: the partition, and then followed by value:

{"name":    "Qinjiang"}

{"age": "3"}

{"sex": "男"}

The relationship between JSON and JavaScript objects

  • JSON JavaScript object string representation, which represent text information using a JS object is essentially a string
var obj = {a: 'hello', b: 'world'};             //对象
var json = '{"a" : "Hello", "b": "world"}';     //JSON字符串

JSON and JavaScript object system conversion

  • To achieve the JSON string into a JavaScript object, using the JSON.parse () Method:
var obj = JSON.parse('{"a": "hello, "b": "world"}');    //结果为 " "
  • To achieve the conversion from a JavaScript object JSON string using the JSON.stringify () Method:
var json = JSON.stringify({a: 'hello', b: 'world'});    //结果为 ' '

test

<script type="text/javascript">
    //编写一个JavaScript对象
    var user = {
        name : "张磊",
        age : 3,
        sex: "男"
    };
//将js对象转换为JSON对象
var json = JSON.stringify(user);
console.log(json);

console.log("================");
//将JSON对象转换为JavaScript对象
var obj = JSON.parse(json);
console.log(obj)
</script>

Controller returns JSON data

  • Jackson should now be better analytical tool for the json
  • Of course, this is more than a tool, such as Alibaba also fastjson etc.
  • We use here Jackson, also need to import it using the jar package
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.2</version>
</dependency>
Garbled solve:
<!-- JSON乱码-->
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="failOnEmptyBeans" value="false"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
@Controller
public class UserController {

    @RequestMapping("/j1")
    @ResponseBody       //不会走视图解析器,直接返回一个字符串
    public String json1() throws JsonProcessingException {
        //jackson, ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("张磊",22,"男");
        String s = mapper.writeValueAsString(user);
        return s;
    }
}

Fast Json

fastjson.jar Ali is dedicated to the development of a Java development package, can easily achieve the conversion json object JavaBean objects to achieve the object conversion JavaBean with a string of json, and json achieve json object into a string. Json method to achieve the conversion of many, the realization of the final result is the same.

rely

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>
System.out.println("*******Java对象 转 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);

System.out.println("\n****** JSON字符串 转 Java对象*******");
User jp_user1=JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

System.out.println("\n****** Java对象 转 JSON对象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));

System.out.println("\n****** JSON对象 转 Java对象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);

File Upload

  • Ready to work

    File upload project development is one of the most common functions, springMVC can be a good support file uploads, but SpringMVC default context is not equipped MultipartResolver, so it can not handle file uploads work by default. If you want to use Spring file upload function, you need to configure MultipartResolver in context.

    Distal form requires: In order to upload a file, the form must be set to the POST method, and enctype to multipart / form-data. Only in this case, the browser will send the user to select a file to the server as binary data;

<!--文件上传-->
<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 id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40968"/>
</bean>
@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.getServletContext().getRealPath("/upload");
    //如果路径不存在,创建一个
    File realPath = new File(path);
    if (!realPath.exists()){
        realPath.mkdir();
    }
    System.out.println("上传文件保存地址:"+realPath);

    InputStream is = file.getInputStream(); //文件输入流
    OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

    //读取写出
    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.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
        realPath.mkdir();
    }
    //上传文件地址
    System.out.println("上传文件保存地址:"+realPath);

    //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
    file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

    return "redirect:/index.jsp";
}

Guess you like

Origin www.cnblogs.com/yfyyy/p/12433560.html