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

The following are Jave code examples for showing how to use sendRedirect() of the javax.servlet.http.HttpServletResponse class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: JavaStudy   File: AuthInterceptorAdapter.java   View Source Code Vote up 11 votes
private boolean forwardToLogin(HttpServletRequest request,
                               HttpServletResponse response) throws ServletException, IOException {
    String url = "http://" + request.getServerName() + ":"
            + request.getServerPort() + request.getContextPath()
            + "/login.jsp";
    response.sendRedirect(url);
    return false;
}
 
Example 2
Project: ssm-web   File: CheckSessionOutFilter.java   View Source Code Vote up 9 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hsrq = (HttpServletRequest) request;
    HttpServletResponse hsrp = (HttpServletResponse) response;
    String clientType = hsrq.getParameter("clientType");
    if ("WORD".equals(clientType)) {
        chain.doFilter(request, response);
    } else {
        SessionUser person = null;
        String reqPage = hsrq.getServletPath();
        if (!reqPage.trim().equals("/login.do") && !reqPage.trim().equals("/logout.do")
                ) {
            person = (SessionUser) hsrq.getSession().getAttribute(SysConstants.SESSION_USER_KEY);
            if (person == null) {
                hsrp.sendRedirect("login.do");
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
 
Example 3
Project: InfoSys-1D   File: ProfChoperAccessDeniedHandler.java   View Source Code Vote up 7 votes
@Override
public void handle(HttpServletRequest httpServletRequest,
                   HttpServletResponse httpServletResponse,
                   AccessDeniedException e) throws IOException {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    // Log access attempts
    if (auth != null) {
        logger.info("User '" + auth.getName() + "' attempted to access the protected URL: "
                + httpServletRequest.getRequestURI());
    }

    // Direct user to access denied page
    httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
}
 
Example 4
Project: LojaDeInstrumentosMusicais   File: ConsultaFornecedorProdServlet.java   View Source Code Vote up 7 votes
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      HttpSession sessao = request.getSession();  
      ArrayList<Fornecedor> Lista = new ArrayList();
      ServicoFornecedor sf = new ServicoFornecedor();
      String codigoempresa = (String) sessao.getAttribute("Empresa");
      
      try {
        Lista = (ArrayList<Fornecedor>) sf.listarFornecedor("", Integer.parseInt(codigoempresa));
    } catch (Exception e) {
    }
    
      sessao.setAttribute("ListaFornecedoresProd", Lista);
      
      RequestDispatcher dispatcher
 = request.getRequestDispatcher("/cadastroProduto.jsp");
dispatcher.forward(request, response);
response.sendRedirect(request.getContextPath() + "/cadastroProduto.jsp"); 
}
 
Example 5
Project: dswork   File: AuthController.java   View Source Code Vote up 7 votes
/**
 * 用户登出系统
 */
@RequestMapping("/logout")
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException
{
	try
	{
		MyCookie cookie = new MyCookie(request, response);
		String cookieTicket = String.valueOf(cookie.getValue(SessionListener.DS_SSO_TICKET));
		service.saveLogLogout(String.valueOf(cookieTicket), false, false);
		if(!cookieTicket.equals("null") && cookieTicket.length() > 0)
		{
			removeLoginInfo(request, response);// 试着删除
		}
	}
	catch(Exception e)
	{
		log.error(e.getMessage());
	}
	MyRequest req = new MyRequest(request);
	String serviceURL = java.net.URLEncoder.encode(req.getString("service", request.getContextPath() + "/ticket.jsp"), "UTF-8");
	response.sendRedirect(request.getContextPath() + "/login?service=" + String.valueOf(serviceURL));
	return;
}
 
Example 6
Project: webpoll   File: SurveyBuilderServlet.java   View Source Code Vote up 7 votes
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	CreateSurveySessionManager session = new CreateSurveySessionManager(request);
	if (securityService.isLoggedIn()) {
		if (session.hasSurveyModel()) {
			request.getRequestDispatcher("WEB-INF/createsurvey/createsurvey.jsp").forward(request, response);
			session.clearErrorMessages();
		} else {
			response.sendRedirect("lecturer");
			session.clearErrorMessages();
		}
	} else {
		session.setErrorMessage(ErrorMessage.NOT_LOGGED_IN);
		response.sendRedirect("index");
	}
}
 
Example 7
Project: backside-servlet-ks   File: GUIHandler.java   View Source Code Vote up 7 votes
public void handlePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String path = getPath(request);
	
	System.out.println("GUIPOSTPATH "+path);
	if (path.equals("login")) {
		String email = request.getParameter("email");
		String pwd = request.getParameter("pword");
		System.out.println("LoggingIn "+email);
		IResult r = model.authenticate(email, pwd);
		ITicket t = (ITicket)r.getResultObject();
		if (t != null) {
			String rtoken = newUUID();
			
			credentialCache.putTicket(rtoken, t);
			response.sendRedirect("/gui/menu/"+rtoken);
		}
	}

			
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: CommonController.java   View Source Code Vote up 6 votes
/**
 * do login
 * @param user userInfo
 * @param request requestInfo
 * @param response responseInfo
 * @param map data
 * @return login result
 * @throws IOException
 */
@RequestMapping(value="login",method = RequestMethod.POST)
public String doLogin(User user, HttpServletRequest request, HttpServletResponse response,ModelMap map) throws IOException{
    if(!StringUtils.isEmpty(user.getName())){
        request.getSession().setAttribute(Constant.SESSION_USER_KEY,user);

        //login success, redirect to home controller, change the url also. if return viewName,can't change url.
        response.sendRedirect("/home");
        return null;
    }else{
        map.put("welcomeMsg",this.msg);
        return "login"; //login failure, return login page
    }
}
 
Example 9
Project: Queue-Manager-Cloud-Dispatcher   File: PersistenceWithSA.java   View Source Code Vote up 6 votes
@Override
protected void doUndo(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException, SQLException {
	// TODO Auto-generated method stub
	String id = request.getParameter("Id");
       if (id != null && !id.trim().isEmpty()) {
       	int ID = Integer.parseInt(id);
       	int amount = saDAO.getAmount(COMPONENT, ID) - FIXEDVALUE;
       	saDAO.updateIncidentToPerson(id, amount, COMPONENT);
       }
       
       response.sendRedirect(LINKNAME);
}
 
Example 10
Project: ralasafe   File: DecisionEntitlementAction.java   View Source Code Vote up 6 votes
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
		throws ServletException, IOException {
	String oper=req.getParameter( "oper" );
	if( log.isDebugEnabled() ) {
		log.debug( "oper=" + oper );
	}
	
	DecisionEntitlementHandler handler=getHandler( req );
	req.setAttribute( "handler", handler );
	
	if( "loadEntitlements".equals( oper ) ) {
		WebUtil.forward( req, resp, "/ralasafe/privilege/decisionEntitlementTable.jsp" );
		return;
	} else if( "getEntitlement".equals( oper ) ) {
		int index=WebUtil.getIntParameter( req, "index", -23 );
		if( index>=0 ) {
			DecisionEntitlement entitlement=(DecisionEntitlement) handler.getDecisionEntitlements().get( index );
			req.setAttribute( "entitlement", entitlement );				
		}
		
		WebUtil.forward( req, resp, "/ralasafe/privilege/editDecisionEntitlement.jsp" );
		return;
	} else if( "return".equals( oper ) ) {
		String gotoUrl="./nonRolePrivilegeMng.rls";
		if( handler.getPrivilege().getType()==0 ) {
			gotoUrl="./privilegeMng.rls";
		} 
		
		String key=getHandlerAttributeKey( req );
		req.getSession().removeAttribute( key );
		
		resp.sendRedirect( gotoUrl );
		return;
	} else {
		WebUtil.forward( req, resp, "/ralasafe/privilege/decisionEntitlement.jsp" );
		return;
	}
}
 
Example 11
Project: full-javaee-app   File: AdministratorSchoolSessionStatisticsServlet.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();

    int logID = Integer.parseInt(request.getParameter("logID"));
    SchoolAccounts account = (SchoolAccounts) session.getAttribute("schoolAccount");
    SchoolLoginLogs loginLog = SchoolAccountDataAccessObject.getLoginLogByID(logID);

    if (loginLog != null) {
        List<SchoolActivityLogs> activityLogs = loginLog.getActivityLog();
        session.setAttribute("schoolActivityLogs", activityLogs);
    }
    response.sendRedirect("admin/admin-school-logs.jsp");
}
 
Example 12
Project: EasyController   File: RedirectView.java   View Source Code Vote up 6 votes
@Override
public void render(HttpServletRequest request, HttpServletResponse response) throws RenderException {
    getContxtPath(request);
    String finalUrl = buildFinalUrl(request);
    try {
        response.sendRedirect(finalUrl);
    } catch (IOException e) {
        throw new RenderException(e.getMessage(), e);
    }
}
 
Example 13
Project: apollo-custom   File: CtripSsoHeartbeatHandler.java   View Source Code Vote up 6 votes
@Override
public void doHeartbeat(HttpServletRequest request, HttpServletResponse response) {
  try {
    response.sendRedirect("ctrip_sso_heartbeat.html");
  } catch (IOException e) {
  }
}
 
Example 14
Project: OnlineElectionVotingSystem   File: AddEvent.java   View Source Code Vote up 6 votes
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String party = request.getParameter("pname");
	String event = request.getParameter("ename");
	String page="";
	String sql="insert into event values('"+party+"', '"+event+"')";
	
	if(party.equals("") || event.equals(""))
	{
		page="Add_UpcommingEvent.jsp?msg=failure";
	}
	else
	{
		try
		{
			Model m =new Model();
			m.setParty(party);
			m.setEvent(event);
			
			int i = Dao.register(m,sql);
			if(i!=0)
			{
				page="Add_UpcommingEvent.jsp?msg=success";
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		response.sendRedirect(page);
	}	
}
 
Example 15
Project: newblog   File: IndexController.java   View Source Code Vote up 6 votes
/**
 * 处理从QQ到12345网站的单点登录
 *
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/qqLogin")
public void login(HttpServletResponse response) throws Exception {
    try {
        String redirect_url = "https://graph.qq.com/oauth2.0/authorize?" +
                "client_id=" + SSOCommon.qqAppKey +
                "&redirect_uri=" + SSOCommon.qqRedirectUri +
                "&response_type=code" +
                "&state=" + RandomStringUtils.randomAlphanumeric(10) +      //设置为简单的随机数
                "&scope=get_user_info";
        response.sendRedirect(redirect_url);
    } catch (Exception e) {
        logger.error("调用QQ接口异常!", e);
    }
}
 
Example 16
Project: 112016.pizzeria-app   File: AdminRedirectController.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect(response.encodeRedirectURL("./admin/home"));
}
 
Example 17
Project: Projeto_Integrador_3_Semestre   File: CadastroHotelServlet.java   View Source Code Vote up 5 votes
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HotelService service = new HotelService();
    HotelDAO dao = new HotelDAO();

    RelatorioDAO relatorioDAO = new RelatorioDAO();
    RelatorioMudancas relatorio = new RelatorioMudancas();

    String nome_hotel = request.getParameter("nome_hotel");
    String data_entrada = request.getParameter("data_entrada");
    String data_saida = request.getParameter("data_saida");
    int quantidade_quartos = Integer.parseInt(request.getParameter("quantidade_quartos"));
    int quantidade_hospedes = Integer.parseInt(request.getParameter("quantidade_hospedes"));
    float preco = Float.parseFloat(request.getParameter("preco"));

    request.setAttribute("erroNome_hotel", service.validaNome(nome_hotel));
    request.setAttribute("erroData_entrada", service.validaEntrada(data_entrada));
    request.setAttribute("erroData_saida", service.validaSaida(data_saida));
    request.setAttribute("erroQuantidade_quartos", service.validaQuantidade_quartos(quantidade_quartos));
    request.setAttribute("erroQuantidade_hospedes", service.validaQuantidade_hospedes(quantidade_hospedes));
    request.setAttribute("erroPreco", service.validaPreco(preco));

    Hotel hotel = new Hotel(nome_hotel.trim(), data_entrada.trim(), data_saida.trim(),
            quantidade_quartos, quantidade_hospedes, preco, true);

    if (service.validaHotel(nome_hotel, quantidade_quartos, data_entrada, data_saida, quantidade_hospedes, preco)) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/CadastroHotel.jsp");
        dispatcher.forward(request, response);
    } else {
        try {

            dao.inserir(hotel);
            HttpSession sessao = request.getSession();
            int identificacaoF = (int) sessao.getAttribute("id_func");
            relatorio.setId_func(identificacaoF);
            relatorio.setMudanca("Cadastro de hotel efetuado!");
            relatorioDAO.inserir(relatorio);
            response.sendRedirect(request.getContextPath() + "/inicio");

        } catch (Exception ex) {

            Logger.getLogger(CadastroHotelServlet.class.getName()).log(Level.SEVERE, null, ex);

        }
    }
}
 
Example 18
Project: cas-5.1.0   File: DelegatedClientAuthenticationAction.java   View Source Code Vote up 5 votes
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);

    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    LOGGER.debug("clientName: [{}]", clientName);

    if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
        return stopWebflow();
    }
    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
        LOGGER.debug("Client: [{}]", client);

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            LOGGER.debug("Retrieved credentials: [{}]", credentials);
        } catch (final Exception e) {
            LOGGER.debug("The request requires http action", e);
            return stopWebflow();
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);
        context.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, service);
        LOGGER.debug("Retrieve service: [{}]", service);
        if (service != null) {
            request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
        }

        restoreRequestAttribute(request, session, this.themeParamName);
        restoreRequestAttribute(request, session, this.localParamName);
        restoreRequestAttribute(request, session, CasProtocolConstants.PARAMETER_METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            final AuthenticationResult authenticationResult =
                    this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, new ClientCredential(credentials));

            final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
        return stopWebflow();
    }

    if (this.autoRedirect) {
        final Set<ProviderLoginPageConfiguration> urls = context.getFlowScope().get(PAC4J_URLS, Set.class);
        if (urls != null && urls.size() == 1) {
            final ProviderLoginPageConfiguration cfg = urls.stream().findFirst().get();
            LOGGER.debug("Auto-redirecting to client url [{}]", cfg.getRedirectUrl());
            response.sendRedirect(cfg.getRedirectUrl());
            final ExternalContext externalContext = context.getExternalContext();
            externalContext.recordResponseComplete();
            return stopWebflow();
        }
    }
    return error();
}
 
Example 19
Project: quartz-web   File: ResourceServlet.java   View Source Code Vote up 5 votes
/**
 * 复写父类service方法,进行请求转发
 *
 * @param request  请求
 * @param response 应答
 * @throws ServletException 异常
 * @throws IOException      异常
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 项目根路径
    String contextPath = request.getContextPath();
    // servlet访问路径
    String servletPath = request.getServletPath();
    // 访问全路径
    String requestURI = request.getRequestURI();
    // 设置编码
    response.setCharacterEncoding("utf-8");
    // 根目录为空的情况为,root context
    if (contextPath == null) {
        contextPath = "";
    }
    String uri = contextPath + servletPath;
    String path = requestURI.substring(contextPath.length() + servletPath.length());
    // request是否合法
    if (!isPermittedRequest(request, response)) {
        return;
    }
    //
    if ("/submitLogin".equals(path)) {
        response.getWriter().print(this.submitLogin(path, request, response));
        return;
    }
    if ("/submitLogout".equals(path)) {
        response.getWriter().print(this.submitLogout(path, request, response));
        return;
    }
    // 没有权限直接返回
    if (!hasPermission(path, request, response)) {
        return;
    }

    if ("".equals(path)) {
        if (contextPath.equals("") || contextPath.equals("/")) {
            response.sendRedirect(servletPath + "/index.html");
        } else {
            response.sendRedirect(requestURI + "/index.html");
        }
        return;
    }
    if ("/".equals(path)) {
        response.sendRedirect("index.html");
        return;
    }

    if (path.startsWith(servicePathPrefix)) {
        LOG.debug("path:" + path);
        response.getWriter().print(this.process(path, request, response));
        return;
    }
    // 其他
    this.returnResourceFile(path, uri, response);
}
 
Example 20
Project: lams   File: QaLearningAction.java   View Source Code Vote up 5 votes
/**
    * finishes the user's tool activity
    *
    * @param request
    * @param qaService
    * @param response
    * @throws IOException
    * @throws ToolException
    */
   public ActionForward endLearning(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException, ToolException {
initializeQAService();
QaLearningForm qaLearningForm = (QaLearningForm) form;

LearningUtil.saveFormRequestData(request, qaLearningForm);

String toolSessionID = request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID);
qaLearningForm.setToolSessionID(toolSessionID);

String userID = request.getParameter("userID");
qaLearningForm.setUserID(userID);

QaSession qaSession = QaLearningAction.qaService.getSessionById(new Long(toolSessionID).longValue());

QaQueUsr qaQueUsr = QaLearningAction.qaService.getUserByIdAndSession(new Long(userID),
	qaSession.getQaSessionId());
qaQueUsr.setLearnerFinished(true);
QaLearningAction.qaService.updateUser(qaQueUsr);

/*
 * The learner is done with the tool session. The tool needs to clean-up.
 */
HttpSession ss = SessionManager.getSession();
/* get back login user DTO */
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);

qaSession.setSession_end_date(new Date(System.currentTimeMillis()));
qaSession.setSession_status(QaAppConstants.COMPLETED);
QaLearningAction.qaService.updateSession(qaSession);

String httpSessionID = qaLearningForm.getHttpSessionID();
// request.getSession().removeAttribute(httpSessionID);
qaLearningForm.setHttpSessionID(httpSessionID);

qaLearningForm.resetAll();

String nextActivityUrl = QaLearningAction.qaService.leaveToolSession(new Long(toolSessionID),
	new Long(user.getUserID().longValue()));
response.sendRedirect(nextActivityUrl);

return null;
   }