前端从后端请求数据,基本思想,依旧是通过ajax将java返回的数据,显示在前端。
首先,在后端提供一个接口:/getHelloWorld,返回hello字符串,代码如下:
package com.iotzzh.controller;
import org.springframework.stereotype.Controller;
import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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
// look for hello page.
@RequestMapping("/hello")
public class HelloWorldController {
@RequestMapping("/getHelloWorld")
@ResponseBody
public String getHelloWorld() throws IOException{
// map.put("name", "zhang");
// map.put("password", "12345678");
System.out.println("success");
return "hello";
}
@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";
}
}
前端调用该接口,并将数据弹出,代码如下:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<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:"helloworld",
contentType:"application/json;charset=utf-8",
dataType:"json",
data:JSON.stringify({
"Name": "test",
"Password": "123456",
"Address": "SD"
}),
success:function(){
console.log("success");
}
});
});
});
$(function(){
$("#getData").click(function(){
$.ajax({
type:"GET",
url:"getHelloWorld",
success:function(data){
console.log("success");
alert("Data: " + data);
}
});
});
});
</script>
</head>
<body>
<h1>hello world.</h1>
<button>Click</button>
<div id = "getData">getdataFromJava</div>
</body>
</html>
显示: