1.添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2.返回json数组
<script>
$(function (){
$("[title='test']").click(function (){
alert();
$.ajax({
type:"GET",
url:"${pageContext.request.contextPath}/users",
dataType:"json",
success:function (json){
console.log(json);
}
});
});
})
json数组形式:
在使用注解开发时需要用到两个重要的 JSON 格式转换注解,分别是
@RequestBody 和 @ResponseBody。
-
@RequestBody:用于将请求体中的数据绑定到方法的形参中,该注解应用在方法的形参上。
-
@ResponseBody:用于直接返回 return 对象,该注解应用在方法上。
在该处理方法上,除了通过 @RequestMapping 指定请求的 URL,还有一个 @ResponseBody 注解。
该注解的作用是将标注该注解的处理方法的返回结果直接写入 HTTP Response Body(Response 对象的 body 数据区)中。
一般情况下,@ResponseBody 都会在异步获取数据时使用,被其标注的处理方法返回的数据都将输出到响应流中,客户端获取并显示数据。
实体类:
package com.openlab.bean;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
public class Employee {
private Integer empid;
private String empname;
private String empsex;
private String phone;
static int i;
public Employee(){
i++;
this.empid=i;
}
public Employee(String empname, String empsex, String phone) {
this();
this.empname = empname;
this.empsex = empsex;
this.phone = phone;
}
}
实现类方法:
package com.openlab.dao;
import com.openlab.bean.Employee;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class EmpDaoImpl implements EmpDao{
static Map<Integer,Employee> map=new HashMap<>();
static {
Employee employee1=new Employee("tony","男","1356789");
Employee employee2=new Employee("luck","男","1353444");
Employee employee3=new Employee("韩梅","女","1353459");
map.put(employee1.getEmpid(),employee1);
map.put(employee2.getEmpid(),employee2);
map.put(employee3.getEmpid(),employee3);
}
@Override
public List<Employee> findAll() {
return new ArrayList<>(map.values());
}
@Override
public void saveorupdate(Employee employee) {
map.put(employee.getEmpid(),employee);
}
@Override
public void delete(Integer empid) {
map.remove(empid);
}
@Override
public Employee findById(Integer empid) {
return map.get(empid);
}
}
controller类:
package com.openlab.controller;
import com.openlab.bean.Employee;
import com.openlab.dao.EmpDao;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
public class UsersController {
@Autowired
private EmpDao empDao;
@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
@ResponseBody
public Employee findUsers(@PathVariable("id") Integer userid){
Employee employee = empDao.findById(userid);
return employee;
}
@GetMapping("/users")
@ResponseBody
public List<Employee> findAll(){
return empDao.findAll();
}
@DeleteMapping("/users/{id}")
@ResponseBody
public String delete(@PathVariable("id") Integer userid){
empDao.delete(userid);
return "success";
}
@PostMapping("/users")
@ResponseBody
public String save(Employee employee){
empDao.saveorupdate(employee);
return "success";
}
@PutMapping("/users/{id}")
@ResponseBody
public String update(Employee employee){
empDao.saveorupdate(employee);
return "success";
}
}
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title> //引入静态资源
<link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/jQuery/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
</head>
<body>
<div id="container">
<table class="table table-striped" title="table" align="center">
<tr >
<td>员工编号</td>
<td>员工姓名</td>
<td>员工性别</td>
<td>员工电话</td>
<td>操作</td>
</tr>
</table>
<input type="button" value="添加" title="update"/>
</div>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
添加
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">员工信息添加</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">员工姓名</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="empname" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">员工性别</label>
<div class="col-sm-10">
<input type="radio" name="empsex" value="男" >男
<input type="radio" name="empsex" value="女" title="female">女
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">员工电话</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="phone" name="phone" placeholder="phone">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" title="saveChange">Save changes</button>
</div>
</div>
</div>
</div>
</body>
<script>
$(function (){
$.ajax({
type:"GET",
url:"${pageContext.request.contextPath}/users",
dataType:"json",
success:function (jsonarr){
$(jsonarr).each(function (i,v){
var tr = $(" <tr> <td>"+v.empid+"</td> <td>"+v.empname+"</td> <td>"+v.empsex+"</td> <td> "+v.phone+"</td> <td> <input type='button' value='修改' title='update' class='btn btn-primary'/><input type='button' value='删除' title='delete' class='btn btn-warning'/>"+"</td> </tr>");
$("[title='table']").append(tr);
});
}
});
//修改
$("#container").on('click','[title="update"]',function (){
var id = $(this).parents("tr").find("td:first").html();
alert(id);
});
//删除
$("#container").on('click','[title="delete"]',function (){
var empid= $(this).parents("tr").find("td:first").html();
$.ajax({
// type: "POST",
type:"DELETE",
url:"${pageContext.request.contextPath}/users/"+empid,
// data:"_method=delete",
success: function (info){
if(info=='success'){
window.location.reload();
}
}
});
});
$("[title='saveChange']").click(function (){
var sex='男';
if($("[title='female']").get(0).checked){
sex='女';
}
$.ajax({
type: "POST",
url:"${pageContext.request.contextPath}/users/",
data:"empname="+$("[name='empname']").val()+"&phone="+$("[name='phone']").val()+"&empsex="+sex,
success: function (info){
if(info=='success'){
window.location.reload();
}
}
});
});
})
</script>
</html>
交互页面