Servlet中Request,Response,Ajax,转发,重定向等的关系
程序员文章站
2022-04-23 16:52:56
...
Servlet中Request,Response,Ajax,转发,重定向等的关系
一.Request设置参数,通过转发或者重定向,跳转到页面:
if ("specialDoc".equals(action)) { String userName = null; User user = (User) request.getSession().getAttribute("user"); if (user != null) { userName = user.getUsername(); } long id = Long.valueOf(request.getParameter("id")); ProjectDao projectDao = new ProjectDao(); List list = projectDao.getItemById(id); if (list != null && list.size() > 0) { Object[] obj = (Object[]) list.get(0); request.setAttribute("itemName", obj[1]); request.setAttribute("remark", obj[2]); request.setAttribute("createDate", obj[3]); request.setAttribute("list", list); } if (userName == null) { request.setAttribute("userName", "nobody"); } else { request.setAttribute("userName", userName); } request.getRequestDispatcher("/frontShow/special-info.jsp").forward(request, response); return; }
1.request设置参数:
2.获取转发器,转发地址跳回原页面或跳到新页面:
二.Response用于Ajax返回数据(一般返回Json字符串):
if ("pageAjax".equals(action)) { String userName = null; User user = (User) request.getSession().getAttribute("user"); if (user != null) { userName = user.getUsername(); } String tableName = request.getParameter("table"); int start = Integer.valueOf(request.getParameter("page")); String pageSizesString = request.getParameter("pageSize"); int pageSize = 0; if (pageSizesString != null) { pageSize = Integer.valueOf(request.getParameter("pageSize")); } pageDao = new PageDaoImpl(); pageDao.init(start, pageSize, tableName, level);//Page对象初始化 Page page = pageDao.getPage();//获取Page对象 JSONObject jObj = new JSONObject(); jObj.put("userName", userName); jObj.put("currentPage", page.getCurrentPage()); jObj.put("totalPages", page.getTotalPage()); jObj.put("hasPrevious", page.isHasPreviousPage()); jObj.put("hasNext", page.isHasNextPage()); jObj.put("isFirst", page.isFirstPage()); jObj.put("isLast", page.isLastPage()); jObj.put("list", page.getList()); response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print(jObj); out.close(); return; }
1.创建Json字符串:
2.通过PrintWriter输出,即返回给Ajax:
上一篇: 3 jsp内置对象