controller 方法返回值

1.ModelAndView:
    1.1:不需要传值的ModelAndView返回值

public ModelAndView confirmlogin() {
    ModelAndView mv = new ModelAndView("redirect:/index.html");
    return mv;
	}

    1.2:需要传值的ModelAndView返回值

ModelAndView mv = new ModelAndView();
	List<DocInfo> docInfos = docInfoService.getAll();
	mv.addObject("docInfos",docInfos);
	mv.setViewName("页面地址");
	return mv;

2.string:
    2.1:返回逻辑视图名

public String returnString(Model model){
	List<DocInfo> infos = docInfoService.getAll();
	model.addAttribute("infos", infos);
	return "页面路径";
	}

    2.2:redirect --重定向
        2.2.1:浏览器地址会发生改变,request数据不共享
        重定向到handler方法

return "redirect:queryDoc.action";

    2.3:forward --请求转发
        2.3.1:浏览器地址不会发生改变,request数据共享

return "forward:forwardMethod"

        2.3.2:数据共享 请求转发当中的方法可以不接收参数,到请求转发的方法中去接收参数:

public String forwardMethod(HttpServletRequest request){
   String id = request.getParameter("id")  // id 是页面传来的参数
   // 业务逻辑...
}

3.void:
    3.1:定义为 void 可以通过 request 、response 指定响应结果
        3.3.1:使用 request 转向页面

public void forwardMethod(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
	request.getRequestDispatcher("页面地址").forward(request, response);
		}

        3.3.2:使用 response 重定向页面

public void forwardMethod(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
	response.sendRedirect("页面路径");
		}

        3.3.3:使用 response 指定响应结果,例如响应 json 数据

public void forwardMethod(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
	response.setCharacterEncoding("UTF-8");
	response.setContentType("application/json;charset=UTF-8");
	response.getWriter().write("json串");
		}

以上,来源于我看的一个视频,黑马程序员
笔芯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值