SpringMVC基础-08-转发与重定向

School.java

package com.monkey1024.bean;

/*
 * 学校
 */
public class School {
	public String getSchoolName() {
		return schoolName;
	}
	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	private String schoolName;
	private String address;
	
}

ForWardRedirectController.java

package com.monkey1024.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.monkey1024.bean.School;

/*
 * spring mvc中的转发和重定向
 */
@Controller
public class ForwardRedirctController {
	/*
	 * 返回modelAndView对象的转发
	 */
	@RequestMapping("/forwardMAV.do")
	public ModelAndView forwardMAV() throws Exception{
		ModelAndView mv = new ModelAndView();
		mv.addObject("type","返回ModelAndView对象的转发");
		//默认使用转发来进行跳转
//		mv.setViewName("/result");
		//手动显示的指定使用转发,此时视图解析器将会失效
//		mv.setViewName("forward:/jsp/result.jsp");
		//如果要跳转到其他controller中,此时需要显示写上forward
		mv.setViewName("forward:other.do");
		return mv;
	}
	
	@RequestMapping("/redirectMAV.do")
	public ModelAndView redirectMAV() throws Exception{
		ModelAndView mv = new ModelAndView();
		
		//这里只能传递基本数据类型和String类型
		mv.addObject("type","返回ModelAndView对象的重定向");
		mv.addObject("schoolName","清华");
		mv.addObject("address","北京");
		//重定向
//		mv.setViewName("redirect:/jsp/result.jsp");
		mv.setViewName("redirect:other.do");
		
		return mv;
	}
	
	/*
	 * 返回Strin类型的转发
	 */
	@RequestMapping("/forwardStr.do")
	//方法中的参数会被自动的放到request域中
	public String forwardStr(School school) throws Exception{
		
		//return "result";
		//显示的指定使用转发
		return "forward:/jsp/result.jsp";
	}
	
	/*
	 * 返回String类型的重定向
	 */
	@RequestMapping("/redirectStr.do")
	public String redirectStr(Model model,School school) throws Exception{
		//数据会被放到url地址栏中,因此只能传递基本数据类型和String类型
		model.addAttribute("schoolName",school.getSchoolName());
		model.addAttribute("address",school.getAddress());
		return "redirect:/jsp/result.jsp";
	}
}

result.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
${type }<br>
${content }<br>
${param.type }<br>
${requestScope.school.address }<br>
${school.schoolName }
${param.address }<br>
${param.schoolName }
</body>
</html> 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值