Java Code Examples for javax.servlet.http.HttpSession#setAttribute()

The following examples show how to use javax.servlet.http.HttpSession#setAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TeamController.java    From TinyMooc with Apache License 2.0 6 votes vote down vote up
@RequestMapping("goTeamPicture.htm")
    public ModelAndView goteampicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //teamId
        String teamId = request.getParameter("teamId");
        Team team = teamService.findById(Team.class, teamId);

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserTeam.class)
                .add(Restrictions.eq("team", team))
                .add(Restrictions.eq("userState", "批准"))
                .addOrder(Order.desc("approveDate"));
        List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria);

        int memberNum = userTeams.size();

        Team teamforpicture = new Team();
        teamforpicture = (Team) teamService.getCurrentSession().createCriteria(Team.class).add(Restrictions.eq("teamId", teamId)).uniqueResult();
        HttpSession hs = request.getSession();
        hs.setAttribute("teamforpicture", teamforpicture);
//        hs.setMaxInactiveInterval(100);
        request.setAttribute("memberNum", memberNum);
        return new ModelAndView("/team/picture");
    }
 
Example 2
Source File: CSVTag.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates the request parameter string needed to pass info to the action
 * handling the CSV exporting.
 *
 * @return String with request parameters for CSVDownloadAction
 */
public String makeCSVRequestParams() {
    String paramExportColumns = "exportColumns_" + getUniqueName();
    String paramHeader = "header_" + getUniqueName();
    HttpServletRequest request = (HttpServletRequest) pageContext
            .getRequest();
    HttpSession session = request.getSession(true);
    // exportColumns and pageData __must__ be in session context
    // so CSVDownloadAction is able to retreive them.
    session.setAttribute(paramExportColumns, exportColumns);

    String csvKey =
        CSVDownloadAction.EXPORT_COLUMNS + "=" + paramExportColumns +
            "&" + exportDataToSession(session) +
            "&" + CSVDownloadAction.UNIQUE_NAME + "=" + getUniqueName();

    if (header != null) {
        session.setAttribute(paramHeader, header);
        csvKey += "&" + CSVDownloadAction.HEADER_NAME + "=" + paramHeader;
    }

    return csvKey;
}
 
Example 3
Source File: XPageAppService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return an instance of the XPage attached to the current Http Session
 * 
 * @param request
 *            The HTTP request
 * @param entry
 *            The XPage entry
 * @return The XPage instance
 */
private static XPageApplication getXPageSessionInstance( HttpServletRequest request, XPageApplicationEntry entry )
{
    HttpSession session = request.getSession( true );
    String strAttribute = ATTRIBUTE_XPAGE + entry.getId( );
    XPageApplication application = (XPageApplication) session.getAttribute( strAttribute );

    if ( application == null )
    {
        application = getApplicationInstance( entry );
        session.setAttribute( strAttribute, application );
        AppLogService.debug( "New XPage instance of " + entry.getClassName( ) + " created and attached to session " + session );
    }

    return application;
}
 
Example 4
Source File: UserServlet.java    From mytwitter with Apache License 2.0 6 votes vote down vote up
private void toUpdateData(HttpServletRequest request, HttpServletResponse response) throws IOException {
	String urealname = request.getParameter("urealname");
	String uaite = request.getParameter("uaite");
	String uabout = request.getParameter("uabout");
	String date = request.getParameter("udate");
	String brithy = date.substring(0, date.indexOf("日")).replaceAll("[\u4e00-\u9fa5]", "-") + " 00:00:00";
	Timestamp brithyDate = Timestamp.valueOf(brithy);
	HttpSession session = request.getSession();
	Users user = (Users) session.getAttribute("user");
	int uid = user.getUid();
	int n = usersinfoDao.updateData(uid, urealname, uaite, uabout, brithyDate);
	if (n > 0) {
		Users users = usersDao.findById(uid);
		Usersinfo info = usersinfoDao.getInfos(uid);
		session.setAttribute("info", info);
		session.setAttribute("user", users);
		response.getWriter().print("ok");
	}
}
 
Example 5
Source File: GUIService.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * 登录并且注册会话,保存会话信息
 * 
 * @param loginId
 * @param loginPwd
 * @param request
 * @return (false:失败,true:成功)
 */
protected boolean loginRegister(String loginId, String loginPwd, HttpServletRequest request) {

    GUISSOClient guissoClient = GUISSOClientFactory.getGUISSOClient(request);
    Map<String, String> userInfo = guissoClient.getUserByLogin(loginId, loginPwd);

    // 登录成功,sesion入口,保存会话信息
    if (null != userInfo && !userInfo.isEmpty()) {

        // 用户信息会话创建,信息保存
        HttpSession session = request.getSession();

        // 白名单
        whiteListFilter(loginId, userInfo);

        session.setAttribute("apphub.gui.session.login.user.id", userInfo.get("loginId"));
        session.setAttribute("apphub.gui.session.login.user.group", userInfo.get("groupId"));
        session.setAttribute("apphub.gui.session.login.user.emailList", userInfo.get("emailList"));
        setUAuthInfoToSession();
        return true;
    }
    else {
        return false;
    }
}
 
Example 6
Source File: FindCinemaByPageAction.java    From MovieManager with Apache License 2.0 6 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	HttpSession session = request.getSession();
	String pageIndex = request.getParameter("pageIndex");

	CinemaService cinemaService = new CinemaServiceImpl();
	
	Page page = new Page(Integer.valueOf(pageIndex),5);
	List<Cinema> queryAllCinemas = cinemaService.queryAllCinemas();
	page.setTotalRecord(queryAllCinemas.size());
	int totalPage = page.getTotalPage();
	int pageNum = page.getPageIndex();
	List<Cinema> findCinemaByPage = cinemaService.findCinemaByPage(page);
	
	if(findCinemaByPage==null) {
		System.out.println("查询结果为空!");
	}
	
	session.setAttribute("cinemaPage", findCinemaByPage);
	session.setAttribute("totalPage", totalPage);
	session.setAttribute("pageNum", pageNum);

	response.sendRedirect("/MovieManager/buyTickets.jsp");
}
 
Example 7
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // save parameters in web session
    final Service service = (Service) context.getFlowScope().get(SERVICE);
    logger.info("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.info("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example 8
Source File: ClientSessionFilter.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
private void continueRequest(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final HttpSession httpSession, final String clientSessionId) throws IOException, ServletException {
    Assert.requireNonNull(request, "request");
    Assert.requireNonNull(response, "response");
    Assert.requireNonNull(chain, "chain");
    clientSessionManager.setClientSessionForThread(httpSession, clientSessionId);
    try {
        final Object init = httpSession.getAttribute(INITIALIZED_IN_SESSION);
        if (init == null) {
            httpSession.setAttribute(INITIALIZED_IN_SESSION, true);
        }

        response.setHeader(PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME, clientSessionId);
        chain.doFilter(request, response);
    } finally {
        clientSessionManager.resetClientSessionForThread();
    }
}
 
Example 9
Source File: AdminInit.java    From EasyHousing with MIT License 5 votes vote down vote up
@RequestMapping(value="managerRentHouseDealinit.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView managerRentHouseDealinit(HttpServletRequest request) {
	ModelAndView modelAndView = new ModelAndView();
	HttpSession session = request.getSession();
	
	List<RentHouseDeal> rentHouseDealList = rentHouseDealDao.selectAll();
	session.setAttribute("rentHouseDealList", rentHouseDealList);
	
	modelAndView.setViewName("SystemUser/managerRentHistory");
	return modelAndView;
}
 
Example 10
Source File: FileOutputStreamServlet02.java    From spiracle with Apache License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       HttpSession session = request.getSession();
       String newLine = System.getProperty("line.separator");

       String relativePathToTestFilesParentDir = File.separator + "pathTraversal" + File.separator + "testFilesParent";
       String relativePathToTestFilesChildDir = relativePathToTestFilesParentDir + File.separator  + "testFilesChild" + File.separator;
       String absolutePathToTestFilesChildDir = getServletContext().getRealPath(relativePathToTestFilesChildDir);
       String testFileName = request.getParameter("FileOutputStream02");
       String absolutePathToTestFile = absolutePathToTestFilesChildDir + File.separator + "." + testFileName;
       String s = "";

       try {

           FileOutputStream fileOutputStreamTarget = new FileOutputStream(absolutePathToTestFile);
           s = "File output stream opened for file:" + newLine + "'" + absolutePathToTestFile + "'";

       } catch (Exception e) {

           s = "Couldn't open file output stream for file:" + newLine + "'" + absolutePathToTestFile + "'";

       } finally {

           System.out.println(newLine + getClass().getSimpleName() + newLine + s);
           session.setAttribute("outputFileOutputStream", s.toString());
           response.sendRedirect("pathTraversal.jsp");
       }
}
 
Example 11
Source File: ProductSearchSession.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * getSearchOptionsHistoryList.
 * <p>
 * SCIPIO: NOTE: 2018-11-27: The returned list is now immutable.
 */
public static List<ProductSearchOptions> getSearchOptionsHistoryList(HttpSession session) {
    List<ProductSearchOptions> optionsHistoryList = UtilGenerics.checkList(session.getAttribute("_PRODUCT_SEARCH_OPTIONS_HISTORY_"));
    if (optionsHistoryList == null) {
        synchronized (ProductSearchSession.getSyncObject(session)) { // SCIPIO
            optionsHistoryList = UtilGenerics.checkList(session.getAttribute("_PRODUCT_SEARCH_OPTIONS_HISTORY_"));
            if (optionsHistoryList == null) {
                optionsHistoryList = Collections.emptyList(); // SCIPIO: enforce unmodifiable on this one
                session.setAttribute("_PRODUCT_SEARCH_OPTIONS_HISTORY_", optionsHistoryList);
            }
        }
    }
    return optionsHistoryList;
}
 
Example 12
Source File: SavedRequestAwareAuthenticationSuccessHandler.java    From zxl with Apache License 2.0 5 votes vote down vote up
protected void createNewSession(HttpServletRequest request, HttpServletResponse response) {
	HttpSession httpSession = request.getSession();
	if (httpSession != null) {
		httpSession.invalidate();
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length >= 1) {
			for (int i = 0; i < cookies.length; i++) {
				cookies[i].setMaxAge(0);
			}
		}
	}
	httpSession = request.getSession(true);
	httpSession.setAttribute(RANDOM_CODE_ATTRIBUTE, getRandomCode(request));
}
 
Example 13
Source File: CSRFTokenManager.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public static String getToken(HttpSession session) {
    String token = null;

    synchronized (session) {
        token = (String) session.getAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
        if (null == token) {
            token = UUID.randomUUID().toString();
            session.setAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME, token);
        }
    }
    return token;
}
 
Example 14
Source File: LoginEvents.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Save USERNAME and PASSWORD for use by auth pages even if we start in non-auth pages.
 *
 * @param request The HTTP request object for the current JSP or Servlet request.
 * @param response The HTTP response object for the current JSP or Servlet request.
 * @return String
 */
public static String saveEntryParams(HttpServletRequest request, HttpServletResponse response) {
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) request.getAttribute("delegator");

    // save entry login parameters if we don't have a valid login object
    if (userLogin == null) {

        String username = request.getParameter("USERNAME");
        String password = request.getParameter("PASSWORD");

        if ((username != null) && ("true".equalsIgnoreCase(EntityUtilProperties.getPropertyValue("security", "username.lowercase", delegator)))) {
            username = username.toLowerCase(Locale.getDefault());
        }
        if ((password != null) && ("true".equalsIgnoreCase(EntityUtilProperties.getPropertyValue("security", "password.lowercase", delegator)))) {
            password = password.toLowerCase(Locale.getDefault());
        }

        // save parameters into the session - so they can be used later, if needed
        if (username != null) {
            session.setAttribute("USERNAME", username);
        }
        if (password != null) {
            session.setAttribute("PASSWORD", password);
        }

    } else {
        // if the login object is valid, remove attributes
        session.removeAttribute("USERNAME");
        session.removeAttribute("PASSWORD");
    }

    return "success";
}
 
Example 15
Source File: AuthenticationFilter.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		HttpSession session = httpServletRequest.getSession();
		
		if(enable){
			Token EMPTY_TOKEN = null;
			String code=request.getParameter("code");
			
			if(code!=null&&uuidMatches(code)){
				Verifier verifier = new Verifier(code);
				Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
				log.debug(" access token is "+accessToken);
				
				OAuthClient restClient=new OAuthClient(OAuthClient.OAUTH_V20_USERINFO_URI);
				 
				UserInfo userInfo=restClient.getUserInfo(accessToken.getToken());

				session.setAttribute(CONST_CONNSEC_USERINFO, userInfo);
				
			}else if(session.getAttribute(CONST_CONNSEC_USERINFO)==null){
				String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
				log.debug("Redirect to authorization Url : "+authorizationUrl);
				httpServletResponse.sendRedirect(authorizationUrl);
			}
		}
		
		chain.doFilter(request, response);
	}
 
Example 16
Source File: ICalWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private static void logInUser(HttpServletRequest request, HttpServletResponse response) throws GenericServiceException, GenericEntityException {
    Map<String, Object> serviceMap = WebDavUtil.getCredentialsFromRequest(request);
    if (serviceMap == null) {
        return;
    }
    serviceMap.put("locale", UtilHttp.getLocale(request));
    GenericValue userLogin = null;
    HttpSession session = request.getSession();
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Map<String, Object> result = dispatcher.runSync("userLogin", serviceMap);
    if (ServiceUtil.isError(result) || ServiceUtil.isFailure(result)) {
        String errorMessage = ServiceUtil.getErrorMessage(result);
        request.setAttribute("_ERROR_MESSAGE_", errorMessage);
        Debug.logError(errorMessage, module);
        throw new GenericServiceException(errorMessage);
    }
    userLogin = (GenericValue) result.get("userLogin");
    request.setAttribute("userLogin", userLogin);
    session.setAttribute("userLogin", userLogin);
    VisitHandler.getVisitor(request, response);
    GenericValue person = userLogin.getRelatedOne("Person", false);
    if (person != null) {
        request.setAttribute("person", person);
    } else {
        GenericValue partyGroup = userLogin.getRelatedOne("PartyGroup", false);
        if (partyGroup != null) {
            request.setAttribute("partyGroup", partyGroup);
        }
    }
}
 
Example 17
Source File: RandomValidateCode.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 生成随机图片
 */
public void getRandcode(HttpServletRequest request,
                        HttpServletResponse response) {
    HttpSession session = request.getSession();
    //BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Graphics g = image.getGraphics();//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
    g.fillRect(0, 0, width, height);
    g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
    g.setColor(getRandColor(110, 133));
    //绘制干扰线
    for (int i = 0; i <= lineSize; i++) {
        drowLine(g);
    }
    //绘制随机字符
    String randomString = "";
    for (int i = 1; i <= stringNum; i++) {
        randomString = drowString(g, randomString, i);
    }
    session.removeAttribute(RANDOMCODEKEY);
    session.setAttribute(RANDOMCODEKEY, randomString);
    System.out.println(randomString);
    g.dispose();
    try {
        ImageIO.write(image, "JPEG", response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: VerifyServlet.java    From blog-sample with Apache License 2.0 4 votes vote down vote up
/**
 * @param request
 * @param response
 * @throws ServletException
 * @throws java.io.IOException
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
    // 定义图像buffer
    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gd = buffImg.createGraphics();
    // 创建一个随机数生成器类
    Random random = new Random();
    // 将图像填充为白色
    gd.setColor(Color.LIGHT_GRAY);
    gd.fillRect(0, 0, width, height);
    // 创建字体,字体的大小应该根据图片的高度来定。
    Font font = new Font("Times New Roman", Font.PLAIN, fontHeight);
    // 设置字体。
    gd.setFont(font);
    // 画边框。
    gd.setColor(Color.BLACK);
    gd.drawRect(0, 0, width - 1, height - 1);
    // 随机产生16条干扰线,使图象中的认证码不易被其它程序探测到。
    gd.setColor(Color.gray);
    for (int i = 0; i < interLine; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        gd.drawLine(x, y, x + xl, y + yl);
    }
    // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;
    // 随机产生codeCount数字的验证码。
    for (int i = 0; i < codeCount; i++) {
        // 得到随机产生的验证码数字。
        String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
        // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
        red = random.nextInt(255);
        green = random.nextInt(255);
        blue = random.nextInt(255);
        // 用随机产生的颜色将验证码绘制到图像中。
        gd.setColor(new Color(red,green,blue));
        gd.drawString(strRand, (i + 1) * codeX, codeY);
        // 将产生的四个随机数组合在一起。
        randomCode.append(strRand);
    }
    // 将四位数字的验证码保存到Session中。
    HttpSession session = request.getSession();
    session.setAttribute("validateCode", randomCode.toString());
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    response.setContentType("image/jpeg");
    // 将图像输出到Servlet输出流中。
    ServletOutputStream sos = response.getOutputStream();
    ImageIO.write(buffImg, "jpeg", sos);
    sos.close();
}
 
Example 19
Source File: VerifyServlet.java    From blog-sample with Apache License 2.0 4 votes vote down vote up
/**
 * @param request
 * @param response
 * @throws ServletException
 * @throws java.io.IOException
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
    // 定义图像buffer
    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gd = buffImg.createGraphics();
    // 创建一个随机数生成器类
    Random random = new Random();
    // 将图像填充为白色
    gd.setColor(Color.LIGHT_GRAY);
    gd.fillRect(0, 0, width, height);
    // 创建字体,字体的大小应该根据图片的高度来定。
    Font font = new Font("Times New Roman", Font.PLAIN, fontHeight);
    // 设置字体。
    gd.setFont(font);
    // 画边框。
    gd.setColor(Color.BLACK);
    gd.drawRect(0, 0, width - 1, height - 1);
    // 随机产生16条干扰线,使图象中的认证码不易被其它程序探测到。
    gd.setColor(Color.gray);
    for (int i = 0; i < interLine; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        gd.drawLine(x, y, x + xl, y + yl);
    }
    // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;
    // 随机产生codeCount数字的验证码。
    for (int i = 0; i < codeCount; i++) {
        // 得到随机产生的验证码数字。
        String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
        // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
        red = random.nextInt(255);
        green = random.nextInt(255);
        blue = random.nextInt(255);
        // 用随机产生的颜色将验证码绘制到图像中。
        gd.setColor(new Color(red,green,blue));
        gd.drawString(strRand, (i + 1) * codeX, codeY);
        // 将产生的四个随机数组合在一起。
        randomCode.append(strRand);
    }
    // 将四位数字的验证码保存到Session中。
    HttpSession session = request.getSession();
    session.setAttribute("validateCode", randomCode.toString());
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    response.setContentType("image/jpeg");
    // 将图像输出到Servlet输出流中。
    ServletOutputStream sos = response.getOutputStream();
    ImageIO.write(buffImg, "jpeg", sos);
    sos.close();
}
 
Example 20
Source File: LoginFilter.java    From HotelSystem with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    String method= req.getParameter("method");
    String uri = req.getRequestURI();
    String contextPath = req.getContextPath();
    String path = uri.substring(contextPath.length());

    if (!(("/"+Pages.LOGIN_JSP.toString()).equalsIgnoreCase(path)
            || ("/"+Pages.REGIST_JSP.toString()).equalsIgnoreCase(path)
            || (Methods.LOGIN_DO.toString()).equalsIgnoreCase(method)
            || (Methods.REGIST_DO.toString()).equalsIgnoreCase(method)
            || uri.endsWith("jpg"))) {
        /**
         * 如果session不存在则检查cookie
         */
        HttpSession sess = req.getSession(false);
        if (sess == null) {
            /**
             * 如果有记住登陆状态的cookie,则给session添加'user'属性
             */
            Cookie[] cookies = req.getCookies();
            if(cookies!=null){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (USER.toString().equalsIgnoreCase(name)) {
                        sess = req.getSession(true);
                        sess.setAttribute(USER.toString(), cookie.getValue());
                    }
                    if(ADMIN.toString().equalsIgnoreCase(name)){
                        sess=req.getSession(true);
                        sess.setAttribute(ADMIN.toString(),cookie.getValue());
                    }
                }
            }
        }
        /**
         * 检查session是否有'user',没有则重定向到登陆界面
         */
        if (sess == null || sess.getAttribute(USER.toString()) == null) {
            redirect(resp, Pages.LOGIN_JSP.toString());
            return;
        }
    }
    filterChain.doFilter(req, resp);
}