Maven + Spring mvc: 前端向后端传递数据

根据前一篇文章,Maven + Spring mvc: Hello World, 已经介绍了spring mvc的简单使用,此片文章介绍一下,如何利用前端将数据传递到后端。
添加依赖引用:

    

    com.fasterxml.jackson.core
    jackson-databind
    2.9.7

前端代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Insert title here




    

hello world.

后端代码, 实体类:

package com.iotzzh.entity;

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;
        }

}

后端代码,controller 代码:

package com.iotzzh.controller;

import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
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.iotzzh.entity.User;


@Controller
@RequestMapping("/hello")

public class HelloWorldController {

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

}

测试:



点击click按钮:


你可能感兴趣的:(Maven + Spring mvc: 前端向后端传递数据)