Java Code Examples for javax.servlet.http.HttpServletResponse#sendRedirect()

The following examples show how to use javax.servlet.http.HttpServletResponse#sendRedirect() . These examples are extracted from open source projects. 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 Project: Project   File: AuthorFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest= (HttpServletRequest)servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

    HttpSession session = httpServletRequest.getSession();

    if (session.getAttribute("islogin") == null){
        // 没有登录,跳转回登录界面重新登录
        // 参数里面的相对路径:相对于过滤器当前处理的请求的路径,当前为 main/*
        httpServletResponse.sendRedirect("../login.jsp");
    }else {
        // 用户登录,放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
 
Example 2
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
	response.setContentType("text/plain");
	response.setStatus(this.response);
	switch (this.response) {
		case  HttpServletResponse.SC_OK:
			//response.getWriter().println("<h1>Hello SimpleServlet</h1>");
			this.printParams(request, response);
			break;
		case HttpServletResponse.SC_MOVED_TEMPORARILY:
			response.sendRedirect("/200");
			break;
		default:
			response.getWriter().println("<h1>Hello from defaultt</h1>");
			break;
	}
	System.out.println("Handling Web request for " + ((Request) request).getUri().toString());
}
 
Example 3
Source Project: journaldev   File: LogoutServlet.java    License: MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("text/html");
	Cookie[] cookies = request.getCookies();
	if(cookies != null){
	for(Cookie cookie : cookies){
		if(cookie.getName().equals("JSESSIONID")){
			System.out.println("JSESSIONID="+cookie.getValue());
			break;
		}
	}
	}
	//invalidate the session if exists
	HttpSession session = request.getSession(false);
	System.out.println("User="+session.getAttribute("user"));
	if(session != null){
		session.invalidate();
	}
	response.sendRedirect("login.html");
}
 
Example 4
Source Project: trader   File: AddPortfolio.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String owner = request.getParameter("owner");

	if ((owner!=null) && !owner.equals("")) try {
		logger.info("Redirecting to Summary servlet.");

		//PortfolioServices.createPortfolio(request, owner);
		portfolioClient.createPortfolio("Bearer "+getJWT(), owner);

		response.sendRedirect("summary"); //send control to the Summary servlet
	} catch (Throwable t) {
		logger.warning("Error creating portfolio: "+t.getMessage());

		String message = "Error creating portfolio.  Please check the <i>trader</i> and <i>portfolio</i> pod logs for details.";

		//send control to the Display Message servlet
		response.sendRedirect("message?message="+message);
	}
}
 
Example 5
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final HttpSession session = request.getSession();
    final Cookie csrfCookie = CookieUtils.getCookie(request, "csrf");
    if (csrfCookie == null || !csrfCookie.getValue().equals(request.getParameter("csrf"))) {
        session.setAttribute("errorMessage", LocaleUtils.getLocalizedString("global.csrf.failed"));
    } else {
        final WebManager webManager = new WebManager();
        webManager.init(request, response, session, session.getServletContext());
        final String action = ParamUtils.getStringParameter(request, "action", "");
        switch (action) {
            case "delete":
                deleteProperty(request, response, session);
                break;
            case "cancel":
                session.setAttribute("warningMessage", LocaleUtils.getLocalizedString("system.cache-details.cancelled"));
                break;
            default:
                session.setAttribute("warningMessage", LocaleUtils.getLocalizedString("global.request-error-no-such-action", Collections.singletonList(action)));
                break;
        }
    }
    response.sendRedirect(request.getRequestURI() + ListPager.getQueryString(request, '?', SEARCH_FIELDS));
}
 
Example 6
@RequestMapping("/authorizeResourceOwner")
public void handleRequest(@ModelAttribute(value = "oAuthParams") OAuthParams oAuthParams,
                          HttpServletResponse response) throws Exception {

    String oauthToken = oAuthParams.getOauthToken();
    String resourceOwnerAuthorizationEndpoint = oAuthParams.getResourceOwnerAuthorizationEndpoint();
    if (resourceOwnerAuthorizationEndpoint == null || "".equals(resourceOwnerAuthorizationEndpoint)) {
        oAuthParams.setErrorMessage("Missing resource owner authorization URI");
    }

    if (oauthToken == null || "".equals(oauthToken)) {
        oAuthParams.setErrorMessage("Missing oauth token");
    }

    response
        .sendRedirect(
            new StringBuilder().append(resourceOwnerAuthorizationEndpoint).
                append("?oauth_token=").append(oauthToken).toString());
}
 
Example 7
Source Project: trader   File: AddStock.java    License: 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 {
	String owner = request.getParameter("owner");
	String symbol = request.getParameter("symbol");
	String shareString = request.getParameter("shares");

	if ((shareString!=null) && !shareString.equals("")) {
		int shares = Integer.parseInt(shareString);
		//PortfolioServices.updatePortfolio(request, owner, symbol, shares);
		portfolioClient.updatePortfolio("Bearer "+getJWT(), owner, symbol, shares);
	}

	response.sendRedirect("summary");
}
 
Example 8
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, 
		ServletRequest request, ServletResponse response) throws Exception {
	
       HttpServletRequest httpServletRequest = (HttpServletRequest)request;
       HttpServletResponse httpServletResponse = (HttpServletResponse)response;
       if (!this.isAjaxRequest(httpServletRequest)) {
       	httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
       } else {
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("application/json");
   		response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA);
       }
	return false;
}
 
Example 9
Source Project: aem-solr-search   File: ProxyServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean doResponseRedirectOrNotModifiedLogic(
        HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        HttpResponse proxyResponse, int statusCode)
        throws ServletException, IOException {
    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
        if (locationHeader == null) {
            throw new ServletException("Received status code: " + statusCode
                    + " but no " + HttpHeaders.LOCATION + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());

        servletResponse.sendRedirect(locStr);
        return true;
    }
    // 304 needs special handling.  See:
    // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
    // We get a 304 whenever passed an 'If-Modified-Since'
    // header and the data on disk has not changed; server
    // responds w/ a 304 saying I'm not going to send the
    // body because the file has not changed.
    if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
        servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    return false;
}
 
Example 10
protected void redirect(RequestContext reqCtx, HttpServletResponse response)
		throws ServletException {
	try {
		String url = (String) reqCtx.getExtraParam(RequestContext.EXTRAPAR_REDIRECT_URL);
		response.sendRedirect(url);
	} catch (Exception e) {
		throw new ServletException("Service not available", e);
	}
}
 
Example 11
Source Project: mytwitter   File: AdminServlet.java    License: Apache License 2.0 5 votes vote down vote up
private void toDelTweet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	String tid = request.getParameter("tid");
	int n = tweetsDao.delTweet(tid);
	String uid = request.getParameter("uid");
	if (n > 0) {
		int m = usersinfoDao.delTweetsNum(Integer.parseInt(uid));
		if (m > 0)
			response.sendRedirect("admin.do?method=gettweet");
	}

}
 
Example 12
Source Project: gocd   File: GenericAccessDeniedHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request,
                   HttpServletResponse response,
                   int statusCode,
                   String errorMessage) throws IOException {
    if (SessionUtils.isAnonymousAuthenticationToken(request) && securityService.isSecurityEnabled()) {
        response.sendRedirect("/go/auth/login");
    } else {
        response.sendError(statusCode, "You are not authorized to access this resource!");
    }
}
 
Example 13
Source Project: opensoc-streaming   File: LogoutServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
{
	logger.info( "Doing logout here..." );
	
	Subject currentUser = SecurityUtils.getSubject();

	currentUser.logout();
	
	Cookie authCookie = new Cookie("authToken", "Logout" );
	authCookie.setMaxAge( 0 );
	resp.addCookie(authCookie);
	
	resp.sendRedirect( "/login.jsp" );
}
 
Example 14
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
		Object handler) throws Exception {
	response.setCharacterEncoding("utf-8");
	request.getSession(true);

	final String requestUrl = request.getRequestURI();

	// 无缓存
       if (isNoCache() && !isSpecCache(requestUrl)) {
           ServletUtils.setNoCacheHeaders(response);
       }

	// If server status is not passed
	if (!Application.serversReady()) {
	    if (checkInstalled()) {
               LOG.error("Server Unavailable : " + requestUrl);

               if (!requestUrl.contains("/gw/server-status")) {
                   response.sendRedirect(ServerListener.getContextPath() + "/gw/server-status?s=" + CodecUtils.urlEncode(requestUrl));
	            return false;
               }
           } else if (!(requestUrl.contains("/setup/") || requestUrl.contains("/language/bundle"))) {
			response.sendRedirect(ServerListener.getContextPath() + "/setup/install");
			return false;
		}
       } else {
           // for Language
           Application.getSessionStore().setLocale(AppUtils.getLocale(request));
           // Last active
		if (!(isIgnoreActive(requestUrl) || ServletUtils.isAjaxRequest(request))) {
			Application.getSessionStore().storeLastActive(request);
		}
       }

	boolean chain = super.preHandle(request, response, handler);
	if (chain) {
		return verfiyPass(request, response);
	}
	return false;
}
 
Example 15
/** 
 * Method execute
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 */
public ActionForward execute(
	ActionMapping mapping,
	ActionForm form,
	HttpServletRequest request,
	HttpServletResponse response) throws Exception {
	
	//Check permissions
	sessionContext.checkPermission(Right.ManageInstructors);
	
	InstructorListUpdateForm frm = (InstructorListUpdateForm) form;
	MessageResources rsc = getResources(request);
	String op = frm.getOp();
	
       // Cancel - Go back to Instructors Detail Screen
       if(op != null && op.equals(rsc.getMessage("button.backToInstructorList"))) {
       	response.sendRedirect( response.encodeURL("instructorList.do"));
       	return null;
       }
       
       // Update - Update the instructor and go back to Instructor List Screen
       if(op != null && op.equals(rsc.getMessage("button.update")) ) {
        update(frm, request);
        response.sendRedirect( response.encodeURL("instructorList.do"));
        return null;
       }
	
       // Refresh - set filters
       if(op != null && op.equals(rsc.getMessage("button.applyFilter")) ) {
           request.setAttribute("filterApplied", "1");
       }
       
       Collection assigned = getAssigned();
	if (assigned != null) {
		frm.setAssignedInstr(assigned);
	} 
	
	Collection available = getAvailable(frm, request);
	if (available != null) {
		frm.setAvailableInstr(available);
	}
	
	// Get Position Types
	LookupTables.setupPositionTypes(request);
	setupFilters(frm, request);
	
	frm.setInstructors();		
	frm.setNameFormat(sessionContext.getUser().getProperty(UserProperty.NameFormat));
	
	return mapping.findForward("showUpdateInstructorList");
}
 
Example 16
Source Project: BotLibre   File: SlackServlet.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PageStats.page(request);
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	
	LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean");
	if (loginBean == null) {
		response.sendRedirect("index.jsp");
		return;
	}
	BotBean botBean = loginBean.getBotBean();
	SlackBean bean = loginBean.getBean(SlackBean.class);

	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		String instance = (String)request.getParameter("instance");
		if (instance != null) {
			if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) {
				botBean.validateInstance(instance);
			}
		}
		if (!botBean.isConnected()) {
			response.sendRedirect("slack.jsp");
			return;
		}
		botBean.checkAdmin();
		
		String token = (String)request.getParameter("token");
		String botUsername = (String)request.getParameter("botUsername");
		String incomingWebhook = (String)request.getParameter("incomingWebhook");
		String postRSS = (String)request.getParameter("postRSS");
		String rssKeywords = (String)request.getParameter("rssKeywords");
		boolean autoPost = "on".equals((String)request.getParameter("autoPost"));
		String autoPostHours = (String)request.getParameter("autoPostHours");
		String autoPosts = (String)request.getParameter("autoPosts");
		String rssUsername = (String)request.getParameter("rssUsername");
		String rssChannel = (String)request.getParameter("rssChannel");
		String autoPostUsername = (String)request.getParameter("autoPostUsername");
		String autoPostChannel = (String)request.getParameter("autoPostChannel");
		String submit = (String)request.getParameter("save");
		if (submit != null) {
			bean.save(token, botUsername, incomingWebhook, postRSS, rssKeywords,
					autoPost, autoPostHours, autoPosts, rssUsername, rssChannel, autoPostUsername, autoPostChannel);
			bean.connect();
		}
		submit = (String)request.getParameter("check");
		if (submit != null) {
			bean.checkStatus();
		}
	} catch (Exception failed) {
		botBean.error(failed);
	}
	response.sendRedirect("slack.jsp");
}
 
Example 17
Source Project: quarkus-http   File: RedirectServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.sendRedirect(req.getParameter("redirect"));
}
 
Example 18
Source Project: keycloak   File: SamlFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    ServletHttpFacade facade = new ServletHttpFacade(request, response);
    SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        response.sendError(403);
        log.fine("deployment not configured");
        return;
    }
    FilterSamlSessionStore tokenStore = new FilterSamlSessionStore(request, facade, 100000, idMapper, deployment);
    boolean isEndpoint = request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml");
    SamlAuthenticator authenticator;
    if (isEndpoint) {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new SamlEndpoint(facade, deployment, sessionStore);
            }
        };

    } else {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new BrowserHandler(facade, deployment, sessionStore);
            }
        };
    }
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        log.fine("AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        HttpServletRequestWrapper wrapper = tokenStore.getWrap();
        chain.doFilter(wrapper, res);
        return;
    }
    if (outcome == AuthOutcome.LOGGED_OUT) {
        tokenStore.logoutAccount();
        String logoutPage = deployment.getLogoutPage();
        if (logoutPage != null) {
            if (PROTOCOL_PATTERN.matcher(logoutPage).find()) {
                response.sendRedirect(logoutPage);
                log.log(Level.FINE, "Redirected to logout page {0}", logoutPage);
            } else {
                RequestDispatcher disp = req.getRequestDispatcher(logoutPage);
                disp.forward(req, res);
            }
            return;
        }
        chain.doFilter(req, res);
        return;
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        log.fine("challenge");
        challenge.challenge(facade);
        return;
    }

    if (deployment.isIsPassive() && outcome == AuthOutcome.NOT_AUTHENTICATED) {
        log.fine("PASSIVE_NOT_AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        chain.doFilter(req, res);
        return;
    }

    if (!facade.isEnded()) {
        response.sendError(403);
    }

}
 
Example 19
Source Project: mdw   File: NotFoundServlet.java    License: Apache License 2.0 4 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String assetPath = request.getParameter("missingAsset");
    if (assetPath != null) {
        serveMissingAssetPage(request, response, assetPath);
    }
    else {
        String path = (String) request.getAttribute("javax.servlet.forward.servlet_path");
        if (path != null) {
            if (path.endsWith("/images/tab_sel.png")) {  // hack for nav back from Task UI
                response.sendRedirect(ApplicationContext.getMdwHubUrl() + "/images/tab_sel.png");
                return;
            }
            if (path.endsWith("/mdw.ico")) {  // hack for nav back from Task UI
                response.sendRedirect(ApplicationContext.getMdwHubUrl() + "/images/mdw.ico");
                return;
            }
            if (path.startsWith("/staging") || path.startsWith("/milestones")
                    || (path.indexOf('.') == -1 && path.indexOf('#') == -1 && path.startsWith("/tasks"))) {
                String redirectPath = path;
                String[] pathSegs = path.substring(1).split("/");
                if (pathSegs.length > 2)
                    redirectPath = "/" + pathSegs[0] + "/" + pathSegs[1];
                response.sendRedirect(ApplicationContext.getMdwHubUrl() + "/#" + redirectPath);
                return;
            }
            if (path.startsWith("/edit/")) {
                // TODO implement asset editing in React
                response.sendRedirect(ApplicationContext.getMdwHubUrl() + "/#" + path);
                return;
            }

            if (path.startsWith("/dashboard/")) {
                // shortcut for standalone dashboard app
                path = "/com/centurylink/mdw/dashboard/Index";
            }

            Mdw mdw = WebAppContext.getMdw();
            Page page = findPage(mdw, path);
            if (!page.exists()) {
                String rootPkg = PropertyManager.getProperty(PropertyNames.MDW_HUB_ROOT_PACKAGE);
                if (rootPkg != null)
                    page = findPage(mdw, "/" + rootPkg.replace('\\', '/') + path);
            }

            if (page.exists()) {
                response.setContentType("text/html");

                if (page.getAsset().shouldCache(request.getHeader("If-None-Match"))) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                } else {
                    response.setHeader("ETag", page.getAsset().getETag());
                    InputStream in = null;
                    OutputStream out = response.getOutputStream();
                    try {
                        if (page.getExt().equals("md")) {
                            // TODO: render markdown to html
                        } else if (page.getTemplate() != null) {
                            String html = new String(Files.readAllBytes(Paths.get(page.getTemplateAsset().getFile().getPath())));
                            in = new ByteArrayInputStream(ExpressionUtil.substitute(html, page, true).getBytes());
                        } else {
                            in = new FileInputStream(page.getFile());
                        }
                        int read;
                        byte[] bytes = new byte[1024];
                        if (in != null)
                            while ((read = in.read(bytes)) != -1)
                                out.write(bytes, 0, read);
                    } catch (MdwException ex) {
                        throw new IOException(ex.getMessage(), ex);
                    } finally {
                        if (in != null)
                            in.close();
                        response.setStatus(HttpServletResponse.SC_OK);
                    }
                }
                return;
            }
            else if (path.equals("/com/centurylink/mdw/dashboard/Index")) {
                String unfoundAsset = path.substring(1, path.lastIndexOf('/')).replace('/', '.');
                String redirect = "/404?missingAsset=" + URLEncoder.encode(unfoundAsset, "utf-8");
                request.getRequestDispatcher(redirect).forward(request, response);
                return;
            }
        }
        request.getRequestDispatcher("/error/404.html").forward(request, response);
    }
}
 
Example 20
/**
 * Handle malformed Responses.
 *
 * @param req   HttpServletRequest
 * @param resp  HttpServletResponse
 * @param errorMsg  Error message to be displayed in HttpServletResponse.jsp
 * @throws IOException  Error when redirecting
 */
private void handleMalformedResponses(HttpServletRequest req, HttpServletResponse resp,
                                      String errorMsg) throws IOException {
    HttpSession session = req.getSession();
    session.setAttribute(OIDCConstants.NOTIFICATIONS_ERROR_MSG, errorMsg);
    resp.sendRedirect(getAdminConsoleURL(req) + "oidc-acs/notifications.jsp");
    //return;
}