1. 程式人生 > >Maven專案:Spring MVC + Ajax + Json + RequestBody:POST後臺伺服器接收前端JSON資料並註解到POJO內

Maven專案:Spring MVC + Ajax + Json + RequestBody:POST後臺伺服器接收前端JSON資料並註解到POJO內

最近一直看Java伺服器端開發,用的架構在Maven專案內的Web後臺伺服器,用了兩天時間明白了怎麼整合這些框架,很累找了很多資料,尤其在整個過程中Eclipse還時不時崩潰,正常的jsp檔案都打不開,需要重新啟動編譯器,另外還有不斷的除錯。由於本人對於前端不太瞭解,更多時候調節一堆錯誤404,415這些錯誤真的很煩人,有時候重新啟動編譯器可以,但是有時候就需要檢視POST的資料,而網上的大部分東西要麼寫的不全,要不就是隨意寫寫,測試結果用例都沒有,另外錯誤都不一樣,對於我這樣新手很不 友好,難以理解,好了吐槽完畢,整體建立一遍希望有用吧。
1、建立Maven專案
在這裡不陳述如何建立專案了,選擇過程中Packaging選擇war就行,如果生成專案沒有web.xml,可能專案會報錯,可以如下所示點選建立web.xml,為了省事用的上一篇文章的截圖:
這裡寫圖片描述


專案的整體框架如下所示:
這裡寫圖片描述

2、新增JAR開發包
因為最近兩天比較忙,所以就直接把網上下載的Spring框架包直接貼上到了lib裡面沒有挑選,然後紅框裡面的需要讀者自行下載,而Spring框架的JAR包可以看我上一篇文章 建立Spring第一個程式HelloWorld,裡面有地址可以下載最新的版本。
這裡寫圖片描述
這裡寫圖片描述
3、配置web.xml檔案

 <servlet>
        <servlet-name>SpringDispatcherServlet</servlet-name>
        <servlet-class>
org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>
1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

4、配置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 http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

        <mvc:annotation-driven/>
        <!-- 配置自動掃描的包 -->
        <context:component-scan base-package="com.gyc.springmvc"></context:component-scan>

        <!-- 配置檢視解析器 如何把handler 方法返回值解析為實際的物理檢視 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name = "prefix" value="/WEB-INF/views/"></property>
            <property name = "suffix" value = ".jsp"></property>
        </bean>


</beans>

5、pom.xml引入依賴關係

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

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

6、測試前端testjson.jsp檔案
這裡主要用到了Ajax的JQuery,進行JSon資料傳輸,使用POST傳輸方式

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("button").click(function(){
            $.ajax({
                type:"POST",
                url:"testJson",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                data:JSON.stringify({
                        "Name": "test", 
                        "Password": "123456", 
                        "Address": "SD"                     
                }),
                success:function(){
                    console.log("success");
                }
            });
        });
    })
</script>
</head>
<body>
<button>Click</button>
</body>
</html>

7、建立User類檔案

在這裡一定要鄭重的宣告一下:

太坑爹了,一天的時間就是測試如何用RequestBody註解到類內,但是後臺收到資料為null,而且找了半天網上資訊都是前篇一律,可是皇天不負有心人啊,找到了解決辦法,就是在資料POST到後臺以後註解可能Json資料難以一一對應賦值,那怎麼辦呢在類的每一個上邊新增@JsonProperty(value=”xxxx”)一定要寫對啊,要不找不到就註解不進去,不寫出來心情不爽啊,這個辦法地址為spring中使用@RequestBody 接收到的物件值為空,太感謝了,沒有白讓我一天忙活啊。

import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
    @JsonProperty(value="Name")
    private String Name;

    @JsonProperty(value="Password")
    private String Password;

    @JsonProperty(value="Address")
    private String Address;

    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public String getPassword() {
        return Password;
    }
    public void setPassword(String password) {
        Password = password;
    }
    public String getAddress() {
        return Address;
    }
    public void setAddress(String address) {
        Address = address;
    }


    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "User:" + Name + "\n" + "Password:" + Password + 
                "\n" + "Address:" + Address;
    }
}

8、編寫Controller

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gyc.models.User;

@Controller
public class TestJson {


    @RequestMapping(value="/testJson", method=RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public void testJson(@RequestBody User user) {
        System.out.println("success");
        System.out.println(user);
    }

}

9、測試結果
兩天的時間搞明白瞭如何註解POJO,很開心,也十分苦惱,程式設計不易且行且珍惜啊。
這裡寫圖片描述