页面响应
为了页面跳转。
request、response
@RequestMapping("addStu")
public void addStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("正在增加…………增加成功");
//请求转发
request.getRequestDispatcher("../index.jsp").forward(request,response);
//重定向
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
redirect、forword
直接根据字符串实现转发与重定向。
@RequestMapping("addStu")
public String addStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("正在增加…………增加成功");
return "redirect:/index.jsp";
//或者 return "forward:../index.jsp";
}
return
直接的页面响应。
@RequestMapping("addStu")
public String addStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("正在增加…………增加成功");
return "/index.jsp";
}
ModelAndView
直接响应ModelAndView (内部进行封装)。
@RequestMapping("addStu")
public ModelAndView addStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/index.jsp");
//或者 mv.setViewName("forward:../index.jsp");
return mv;
}
数据响应
为了提供数据至客户端(ajax请求时)。
在index.jsp中添加返回数据。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>name1:${name1}</h1>
<h1>name2:${name2}</h1>
<h1>name3:${name3}</h1>
<h1>name4:${name4}</h1>
<h1>name5:${name5}</h1>
<h1>stu的值:${stu.id},${stu.name}</h1>
</body>
</html>
Servlet API
使用servletAPI实现模拟响应数据。
@RequestMapping("/findAll")
public void findAll(HttpServletRequest request,) {
request.setAttribute("name1","雪碧");
request.getSession().setAttribute("name2","冰淇淋");
}
ajax
创建ajax.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
function f(){
$.ajax({
url:'${pageContext.request.contextPath}/StudentController/getdata',
type:'POST',
contentType:'application/json;character=utf-8',
success:function (data) {
$(data).each(function (index , el) {
alert("遍历的元素为:"+ el.id + "..." + el.name)
});
},
error:function (data) {
alert("接受到的错误信息为:"+data)
}
});
}
</script>
</head>
<body>
<h1 onclick="f()">点我触发</h1>
</body>
</html>
响应对象
406 Not Acceptable:服务端错误:表示引用数据类型响应数据时,格式无法正常转换。
@RequestMapping("/getdata")
@ResponseBody
public Student getdata() {
Student student = new Student(6, "翠花");
return student;
}
响应集合
@RequestMapping("/getdata")
@ResponseBody
public List getdata() {
Student s1 = new Student(1,"哈哈哈");
Student s2 = new Student(2, "嘿嘿嘿");
Student s3 = new Student(3, "吼吼吼");
List list = new ArrayList();
list.add(s1);
list.add(s2);
list.add(s3);
return list;
}
地址栏中访问ajax.jsp,即可返回设置的集合数据。