Spring MVC 中的 forward 和 redirect

本文介绍了Spring MVC中两种常见的视图返回方式:前进(forward)与重定向(redirect)。通过实例展示了如何使用@RequestParam接收参数,并分别用forward与redirect进行页面跳转。此外还提供了一种使用ModelAndView结合前进与重定向的混合方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[url]http://zachary-guo.iteye.com/blog/1503352[/url]

详细参考: [url]http://panyongzheng.iteye.com/blog/1942839[/url]
两种返回方式都可以是ModelAndView或者String类型
[color=red][b]forward[/b][/color]
String url="list";
return new ModelAndView(url);

[color=red][b]redirect[/b][/color]
String url="redirect:/list.do";
return new ModelAndView(url);


package com.pas.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {

@RequestMapping(value = "/forward.do")
public String forward(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("role") String role) {

System.out.println("Login.....................................");
return "index";//使用forward方式
}

@RequestMapping(value = "/redirect.do")
public String redirect(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("role") String role) {

System.out.println("Login.....................................");
return "redirect:index.jsp";//重定向方式
}


}


或者这种方式:
public ModelAndView login(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("role") String role) {
System.out.println("Login.....................................");
ModelAndView view = null;
if (StringUtils.equalsIgnoreCase("pandy", userName)
&& StringUtils.equalsIgnoreCase("pandy", password)) {
view = new ModelAndView(new RedirectView("index.jsp"));
} else {
view = new ModelAndView("../login");
}

return view;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值