(一)重定向
1.如何在java中重定向到外部URL
重定向之余并給外部域名下加cookie
CookieUtils.setCookie(response, "token", att, expiresIn);
return new ModelAndView(new RedirectView((String) httpSession.getAttribute("originUrl")));
setCookie
public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int time) {
// new一個(gè)Cookie對象,鍵值對為參數(shù)
Cookie cookie = new Cookie(name, value);
// tomcat下多應(yīng)用共享
cookie.setPath("/");
// 如果cookie的值中含有中文時(shí),需要對cookie進(jìn)行編碼,不然會(huì)產(chǎn)生亂碼
try {
URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
cookie.setMaxAge(time);
// 將Cookie添加到Response中,使之生效
response.addCookie(cookie); // addCookie后,如果已經(jīng)存在相同名字的cookie,則最新的覆蓋舊的cookie
return response;
}
2.重定向到內(nèi)部
response.sendRedirect(path);
前后端分離的情況下
response.sendRedirect(path)也可以用來重定向到前端URL
(二)轉(zhuǎn)發(fā)
request.getRequestDispatcher("/server/user/requestAuth").forward(request, response);
(三)請求轉(zhuǎn)發(fā)和重定向的主要區(qū)別
(1) 請求轉(zhuǎn)發(fā)forward 只有一次請求,而重定向是兩次請求:
(2) 請求轉(zhuǎn)發(fā):僅限于當(dāng)前web應(yīng)用內(nèi),"/"代表當(dāng)前web應(yīng)用的根目錄
請求重定向:可以定向到任何資源,"/"代表當(dāng)前web站點(diǎn)的根目錄
(3)轉(zhuǎn)發(fā)請求的參數(shù)不會(huì)丟失重定向參數(shù)會(huì)丟失,request還是之前請求的request
請求重定向的request會(huì)生成新的request