本文整理汇总了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;
}