mvc使用html页面跳转,页面重定向跳转的方式

在一次面试的时候被问到页面跳转有多少种方式,当时回答的不好,现在总结如下:

1.在server端sendRedirect重定向

response.sendRedircet("http://auto.sina.com.cn");

执行该语句后server会发送一个body为空的http response,状态码为302,在respose header中location属性,值为http://auto.sina.com.cn。浏览器接收到response后读取location信息,向url发起请求,地址栏变成url。

可以跨域

2.在server端使用ReqestDispatcher进行forward请求转发

//1.

request.getRequestDispatcher("http://auto.sina.com.cn").forward(request, response);

//2.

request.getSession().getServletContext().getRequestDispatcher("http://auto.sina.com.cn").forward(request, response);

server内部转发,浏览器地址栏不会发生变化

两个资源共享request里面的数据

ServletContext和ServletContext获取getRequestDispatcher的区别是,前者path参数必须是绝对路径,后者path参数可以是绝对或者相对

3.使用JSP的response对象重定向

response是JSP的内置对象

//1.

response.sendRedirect("http://auto.sina.com.cn");

%>

//2.

response.setStatus(302);

response.setHeader("location", "http://auto.sina.com.cn");

%>

在browser端使用Javascript进行重定向

//1.

window.location="http://auto.sina.com.cn";

//2.

location.href="http://auto.sina.com.cn";

//3.

location.assign("http://auto.sina.com.cn");

//4.

location.replace("http://auto.sina.com.cn");

4.在browser端使用html标签进行重定向

跳转

5.SpringMVC页面跳转方式

如果跳转到WEB-INF目录下面的页面,直接通过超链接的形式是不能直接跳转的,必须经过后端来进行跳转

(1).使用视图解析:

当配置好了视图解析器时,controller中返回的是一个普通的字符串,则跳转到/WEB-INF/jsp/hello.jsp

@RequestMapping(value="/to",method={RequestMethod.POST,RequestMethod.GET})

public String to(@ModelAttribute("message") String msg, @ModelAttribute("to") String to){

System.out.println("-----------------------------");

System.out.println("message:"+msg);

System.out.println("to:"+too);

System.out.println("-----------------------------");

return "hello";

}

(2).不使用视图解析

如果controller字符串中有redirect、forward关键字时,将会忽略视图解析器,直接跳转到controller对应的请求方法,而不是跳转到页面,比如hello方法中继续做页面的跳转

return "redirect:hello"

return "forward:hello"

(3).使用ModelAndView请求转发:需要使用视图解析

@Override

public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest,

javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {

ModelAndView mv = new ModelAndView();

//封装要显示到视图的数据

mv.addObject("msg","hello world");

//视图名

mv.setViewName("hello");

return mv;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值