SubmitServlet:
package edu.hpu.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.hpu.Pojo.Role;
import net.sf.json.JSONObject;
/**
- Servlet implementation class SubmitServlet
*/
public class SubmitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SubmitServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data=request.getParameter(“data”); //获取前端传递数据
System.out.println(“服务端接收到的数据是:” +data);
JSONObject json=JSONObject.fromObject(data);
System.out.println(“转换为JSON对象之后是:”+ json);
Role role = (Role)JSONObject.toBean(json,Role.class);
System.out.println(“转换为Hero对象之后是:”+role);
}
}
web.xml配置:
SubmitServlet
edu.hpu.servlet.SubmitServlet
SubmitServlet
/submitServlet
跑一下,结果:
[](()前端获取一个对象GetOneServlet:
package edu.hpu.servlet;
import edu.hpu.pojo.Role;
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetOneServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Role role=new Role();
role.setName(“柳飘飘”);
role.setFilm(“喜剧之王”);
JSONObject json= new JSONObject();
json.put(“role”, JSONObject.fromObject(role));
response.setContentType(“text/html;charset=utf-8”);
response.getWriter().print(json);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
web.xml配置:
GetOneServlet
edu.hpu.servlet.GetOneServlet
GetOneServlet
/getOneServlet
getOne.html:
影视角色:
跑一下,结果:
F12可以进入调试模式,查看前端发出的异步请求以及后端的响应:
[](()前端获取多个对象GetManyServlet:
package edu.hpu.servlet;
import edu.hpu.pojo.Role;
import net.sf.json.JSONSerializer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)