溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring MVC controller怎么處理301跳轉

發(fā)布時間:2021-12-20 10:37:12 來源:億速云 閱讀:327 作者:iii 欄目:大數據

本篇內容主要講解“Spring MVC controller怎么處理301跳轉”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Spring MVC controller怎么處理301跳轉”吧!

一、 SpringMVC301,302跳轉

spring mvc項目是spring的一個子項目用于處理視圖層的請求。
302跳轉很簡單:

@RequestMapping(value = "blog.html")
public String rindex() {
 return "redirect:/blog";
}

按照不重復造輪子的理念,其實301跳轉也很簡單:

@RequestMapping(value = "blog.html")
public RedirectView rindex(HttpServletRequest request) {
	RedirectView redirectView = new RedirectView("/blog");
	redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
	return redirectView;	
}

spring mvc 提供了一個專門用于處理各種重定向的view視圖。
跳轉結果如下圖:

Spring MVC controller怎么處理301跳轉

其它各種實現如:

response.setStatus(301);
response.setHeader("Location", "https://www.xxxx");

二、 Redorect跳轉傳參

 Redorect傳參3種方式

第一種:手動拼接url

new ModelAndView("redirect:/toList?param1="+value1+"&param2="+value2); 
這樣有個弊端,就是傳中文可能會有亂碼問題,需要自己處理。 


第二種:RedirectAttributes attributes

這里用它的addAttribute方法,這個實際上重定向過去以后你看url,是它自動給你拼了你的url。 
使用方法: 
 public String test(RedirectAttributes attributes) 

    attributes.addAttribute("test", "hello"); 
    return "redirect:/test/test2"; 

第三種:ModelAndView在model加上屬性

ModelAndView  model = new ModelAndView("redirect:/main/index");   
model.addObject("userName", userName);  //把userName參數帶入到controller的RedirectAttributes
return model;  

到此,相信大家對“Spring MVC controller怎么處理301跳轉”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI