本文整理匯總了Java中javax.servlet.http.Cookie.setPath方法的典型用法代碼示例。如果您正苦於以下問題:Java Cookie.setPath方法的具體用法?Java Cookie.setPath怎麽用?Java Cookie.setPath使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.servlet.http.Cookie
的用法示例。
在下文中一共展示了Cookie.setPath方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: addCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* 往客戶端寫入Cookie
* @param name cookie參數名
* @param value cookie參數值
* @param maxAge 有效時間,int(單位秒),0:刪除Cookie,-1:頁麵關閉時刪除cookie
* @param path 與cookie一起傳輸的虛擬路徑
* @param domain 與cookie關聯的域
* @param isSecure 是否在https請求時才進行傳輸
* @param isHttpOnly 是否隻能通過http訪問
*/
public void addCookie(String name, String value, int maxAge, String path, String domain, boolean isSecure, boolean isHttpOnly)
{
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
cookie.setPath(path);
if(maxAge > 0 && domain != null)
{
cookie.setDomain(domain);
}
cookie.setSecure(isSecure);
try
{
Cookie.class.getMethod("setHttpOnly", boolean.class);
cookie.setHttpOnly(isHttpOnly);
}
catch(Exception e)
{
System.out.println("MyCookie ignore setHttpOnly Method");
}
response.addCookie(cookie);
}
示例2: deleteCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
Cookie cookie, String domain, String path) {
if (cookie != null) {
if(StringUtils.isNotBlank(domain)){
cookie.setDomain(domain);
}
cookie.setPath(path);
cookie.setValue("");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
示例3: exportExcel
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* Exports tool results into excel.
*
* @throws IOException
*/
private ActionForward exportExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
initializeScratchieService();
String sessionMapID = request.getParameter(ScratchieConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(sessionMapID);
Scratchie scratchie = (Scratchie) sessionMap.get(ScratchieConstants.ATTR_SCRATCHIE);
LinkedHashMap<String, ExcelCell[][]> dataToExport = service.exportExcel(scratchie.getContentId());
String fileName = "scratchie_export.xlsx";
fileName = FileUtil.encodeFilenameForDownload(request, fileName);
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// set cookie that will tell JS script that export has been finished
String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue");
Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue);
fileDownloadTokenCookie.setPath("/");
response.addCookie(fileDownloadTokenCookie);
// Code to generate file and write file contents to response
ServletOutputStream out = response.getOutputStream();
ExcelUtil.createExcel(out, dataToExport, null, false);
return null;
}
示例4: switchUser
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
@Override
public void switchUser(AdminUser user) throws AdminInterfaceException {
if (!userInfoProvider.getIsAdmin()) {
throw new IllegalArgumentException("Unauthorized.");
}
// BEWARE THIS IS A HACK
// We are going to switch users and set the readOnly flag
// When this call returns we depend on the client side doing a complete
// reload. It will then get a new User object based on these updated
// session fields.
// OLD CODE
// HttpSession session = localSession.getSession();
// session.setAttribute("userid", user.getId());
// session.setAttribute("readonly", true);
OdeAuthFilter.UserInfo nuser = new OdeAuthFilter.UserInfo(user.getId(),
false);
nuser.setReadOnly(true);
String newCookie = nuser.buildCookie(false);
Cookie cook = new Cookie("AppInventor", newCookie);
cook.setPath("/");
getThreadLocalResponse().addCookie(cook);
}
示例5: run
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
@Override
public Object run() {
logger.info("Moving cookies from byte stream to header");
RequestContext ctx = RequestContext.getCurrentContext();
String rawCookies = responseBodyOf(ctx);
Map<String, String> cookies = jsonOf(ctx, rawCookies);
HttpServletResponse response = ctx.getResponse();
for (Map.Entry<String, String> entry : cookies.entrySet()) {
Cookie cookie = new Cookie(entry.getKey(), entry.getValue());
cookie.setPath("/");
response.addCookie(cookie);
}
ctx.setResponse(response);
ctx.setResponseBody("logged in");
return null;
}
示例6: setCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* 創建cookie
*
* @param response
* @param nameValues 存入cookie的鍵值對
* @param hours 設置cookie的有效期(為空時隨瀏覽器銷毀)
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, Integer hours, Boolean isHttpOnly) {
try {
if (value!=null){
value = java.net.URLEncoder.encode(value, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
logger.warn("生成cookie[{}]失敗。{}", name, e.getMessage());
}
Cookie cookie = new Cookie(name, value);
if (null != hours) {
//(生成緩存文件,否則在內存中)
cookie.setMaxAge(hours * 60 * 60);
cookie.setPath("/");
}
if (null != isHttpOnly) {
cookie.setHttpOnly(isHttpOnly);
}
String domain = request.getServerName();
boolean isIp = StringUtil.isIpAddress(domain);
if (!isIp){
String[] dis = domain.split(".");
if (dis.length>=2){
cookie.setDomain("."+ dis[dis.length-2]+"."+ dis[dis.length-1]);
}
}
response.addCookie(cookie);
}
示例7: addCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**添加cookie*/
public List<Cookie> addCookie(User user) {
Cookie cookieU = new Cookie(Constants.COOKIE_USERNAME, user.getUsername());
Cookie cookieP = new Cookie(Constants.COOKIE_PASSWORD, user.getPassword());
cookieU.setMaxAge(60 * 60 * 24 * 14);
cookieP.setMaxAge(60 * 60 * 24 * 14);
cookieU.setPath("/");
cookieP.setPath("/");
List<Cookie> list = new ArrayList<Cookie>();
list.add(cookieP);
list.add(cookieU);
return list;
}
示例8: register
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
@RequestMapping(value = "/register",method = RequestMethod.POST)
public String register(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestParam("name") String name,
@RequestParam("password")String password, @RequestParam("tel")String tel, Model model){
try {
UserInfo userInfo = userInfoService.queryByUsername(name);
if(userInfo == null){
userInfoService.newWorkerInfo(new UserInfo(name, MD5Util.EncryptedByMD5(password),new Date(),tel));
Cookie ucookie = new Cookie("uid",name);
ucookie.setPath("/");
httpServletResponse.addCookie(ucookie);
String exnamesession = (String) httpServletRequest.getSession().getAttribute("uid");
if(exnamesession != null){
httpServletRequest.getSession().removeAttribute("uid");
}
model.addAttribute("uid",name);
return "redirect:/home";
}else {
model.addAttribute("errormsg","用戶名已存在!");
return "signup";
}
}catch (Exception e){
e.printStackTrace();
model.addAttribute("errormsg","用戶名已存在!");
return "/signup";
}
}
示例9: setCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
public static void setCookie(HttpServletResponse response, String name, String value, int expire, String domain) {
Cookie c = new Cookie(name, value);
c.setMaxAge(expire);
if (domain != null) {
c.setDomain(domain);
}else {
c.setPath("/");
}
response.addCookie(c);
}
示例10: setCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* 設置 Cookie
*
* @param name 名稱
* @param value 值
* @param maxAge 生存時間(單位秒)
* @param path 路徑
*/
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
Cookie cookie = new Cookie(name, null);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
try {
cookie.setValue(URLEncoder.encode(value, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.addCookie(cookie);
}
示例11: login
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* Logins the specified user from the specified request.
*
* <p>
* If no session of the specified request, do nothing.
* </p>
*
* @param request
* the specified request
* @param response
* the specified response
* @param user
* the specified user, for example,
*
* <pre>
* {
* "userEmail": "",
* "userPassword": ""
* }
* </pre>
*/
public static void login(final HttpServletRequest request, final HttpServletResponse response,
final JSONObject user) {
final HttpSession session = request.getSession();
if (null == session) {
logger.warn("The session is null");
return;
}
session.setAttribute(User.USER, user);
try {
final JSONObject cookieJSONObject = new JSONObject();
cookieJSONObject.put(User.USER_EMAIL, user.optString(User.USER_EMAIL));
cookieJSONObject.put(User.USER_PASSWORD, user.optString(User.USER_PASSWORD));
final Cookie cookie = new Cookie("b3log-latke", cookieJSONObject.toString());
cookie.setPath("/");
cookie.setMaxAge(COOKIE_EXPIRY);
response.addCookie(cookie);
} catch (final Exception e) {
logger.warn("Can not write cookie", e);
}
}
示例12: getServletResponse
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* Returns the final response from the servlet. Note that this method should
* only be invoked after all processing has been done to the servlet response.
**/
public WebResponse getServletResponse() throws IOException {
if (_contextStack.size() != 1) throw new IllegalStateException( "Have not returned from all request dispatchers" );
if (_webResponse == null) {
HttpSession session = getRequest().getSession( /* create */ false );
if (session != null && session.isNew()) {
Cookie cookie = new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, session.getId() );
cookie.setPath( _application.getContextPath() );
getResponse().addCookie( cookie );
}
_webResponse = new ServletUnitWebResponse( _client, _frame, _effectiveURL, getResponse(), _client.getExceptionsThrownOnErrorStatus() );
}
return _webResponse;
}
示例13: set
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* 保存
* @param response
* @param key
* @param value
* @param ifRemember
*/
public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) {
int age = COOKIE_MAX_AGE;
if (ifRemember) {
age = COOKIE_MAX_AGE;
} else {
age = -1;
}
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(age); // Cookie過期時間,單位/秒
cookie.setPath(COOKIE_PATH); // Cookie適用的路徑
response.addCookie(cookie);
}
示例14: setSearchHistroy
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* 設置search記錄到cookie中,操作步驟:
* 檢查加入的記錄是否已經存在cookie中,如果存在,則更新列表次序;如果不存在,則插入到最前麵
* @param context
* @param value
*/
private void setSearchHistroy(Map<String, Object> context, String value) {
//分析已有的cookie
String separatorsB = "\\.\\.\\.\\.\\.\\.";
String newCookiev = value;
Cookie[] cookies = request.getCookies();
for(Cookie c:cookies){
if(c.getName().equals("HISTORY")){
String cookiev = c.getValue();
String[] values = cookiev.split(separatorsB);
int count = 1;
for(String v : values){
if(count<=10){
if(!value.equals(v)){
newCookiev = newCookiev + separatorsB + v;
}
}
count ++;
}
break;
}
}
Cookie _cookie=new Cookie("HISTORY", newCookiev);
_cookie.setMaxAge(60*60*24*7); // 設置Cookie的存活時間為30分鍾
_cookie.setPath("/");
response.addCookie(_cookie); // 寫入客戶端硬盤
}
示例15: createSessionCookie
import javax.servlet.http.Cookie; //導入方法依賴的package包/類
/**
* Creates a new session cookie for the given session ID
*
* @param context The Context for the web application
* @param sessionId The ID of the session for which the cookie will be
* created
* @param secure Should session cookie be configured as secure
*/
public static Cookie createSessionCookie(Context context,
String sessionId, boolean secure) {
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
// NOTE: The priority order for session cookie configuration is:
// 1. Context level configuration
// 2. Values from SessionCookieConfig
// 3. Defaults
Cookie cookie = new Cookie(
SessionConfig.getSessionCookieName(context), sessionId);
// Just apply the defaults.
cookie.setMaxAge(scc.getMaxAge());
cookie.setComment(scc.getComment());
if (context.getSessionCookieDomain() == null) {
// Avoid possible NPE
if (scc.getDomain() != null) {
cookie.setDomain(scc.getDomain());
}
} else {
cookie.setDomain(context.getSessionCookieDomain());
}
// Always set secure if the request is secure
if (scc.isSecure() || secure) {
cookie.setSecure(true);
}
// Always set httpOnly if the context is configured for that
if (scc.isHttpOnly() || context.getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
String contextPath = context.getSessionCookiePath();
if (contextPath == null || contextPath.length() == 0) {
contextPath = scc.getPath();
}
if (contextPath == null || contextPath.length() == 0) {
contextPath = context.getEncodedPath();
}
if (context.getSessionCookiePathUsesTrailingSlash()) {
// Handle special case of ROOT context where cookies require a path of
// '/' but the servlet spec uses an empty string
// Also ensure the cookies for a context with a path of /foo don't get
// sent for requests with a path of /foobar
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
} else {
// Only handle special case of ROOT context where cookies require a
// path of '/' but the servlet spec uses an empty string
if (contextPath.length() == 0) {
contextPath = "/";
}
}
cookie.setPath(contextPath);
return cookie;
}