Example usage for javax.servlet.http HttpServletResponse sendRedirect

List of usage examples for javax.servlet.http HttpServletResponse sendRedirect

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse sendRedirect.

Prototype

public void sendRedirect(String location) throws IOException;

Source Link

Document

Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.

Usage

From source file:org.awesomeagile.webapp.config.SslRedirectConfig.java

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {
        @Override// w w  w  . j  av  a  2 s  . com
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
            Server server = tomcat.getServer();

            Service service = new StandardService();
            service.setName("ssl-redirect-service");
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(sslRedirectPort);
            service.addConnector(connector);
            server.addService(service);

            Engine engine = new StandardEngine();
            service.setContainer(engine);

            Host host = new StandardHost();
            host.setName("ssl-redirect-host");
            engine.addChild(host);
            engine.setDefaultHost(host.getName());

            Context context = new StandardContext();
            context.addLifecycleListener(new Tomcat.FixContextListener());
            context.setName("ssl-redirect-context");
            context.setPath("");
            host.addChild(context);

            Wrapper wrapper = context.createWrapper();
            wrapper.setServlet(new HttpServlet() {
                @Override
                public void service(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    ServletServerHttpRequest r = new ServletServerHttpRequest(req);
                    UriComponentsBuilder b = UriComponentsBuilder.fromHttpRequest(r);
                    b.scheme("https");
                    b.port(null);
                    res.sendRedirect(b.toUriString());
                }
            });
            wrapper.setName("ssl-redirect-servlet");
            context.addChild(wrapper);
            context.addServletMapping("/", wrapper.getName());

            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}

From source file:org.venice.piazza.servicecontroller.controller.ServiceController.java

/**
 * Statistics for the Piazza Service controller This service is meant for internal Piazza use, Swiss-Army-Knife
 * (SAK) administration and for testing of the serviceController.
 * // w  w w.j a  va 2  s .  c  om
 * @return json as statistics
 */
@RequestMapping(value = "/admin/stats", method = RequestMethod.GET)
public void stats(HttpServletResponse response) throws IOException {
    response.sendRedirect("/metrics");
}

From source file:ca.flop.jpublish.dwr.DWRUrlProcessor.java

public void handle(JPublishContext context) throws IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    try {/*from  ww  w.  j  a v a 2s.c om*/
        String pathInfo = LocalUtil.replace(request.getPathInfo(), (String) context.get("dwrPathPrefix"), "");
        //String pathInfo = request.getPathInfo();

        if (pathInfo == null || pathInfo.length() == 0 || pathInfo.equals("/")) {
            response.sendRedirect(request.getContextPath() + request.getServletPath() + indexHandlerUrl);
        } else {
            // Loop through all the known URLs
            for (Iterator it = urlMapping.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                String url = (String) entry.getKey();

                // If this URL matches, call the handler
                if (pathInfo.startsWith(url)) {
                    Handler handler = (Handler) entry.getValue();
                    handler.handle(request, response);
                    context.setStopProcessing();
                    return;
                }
            }

            notFoundHandler.handle(request, response);
        }
    } catch (Exception ex) {
        exceptionHandler.setException(ex);
        exceptionHandler.handle(request, response);
    }
}

From source file:com.mycompany.login.filter.AutenticacaoFilter.java

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {
    //super.unsuccessfulAuthentication(request, response, failed);
    SecurityContextHolder.clearContext();
    request.removeAttribute("usuarioLogado");
    request.getSession().setAttribute("msg", mensagem);
    request.getSession().invalidate();/*w w w.  j  a va  2  s. c  o  m*/
    response.sendRedirect("index.xhtml");

}

From source file:com.oncloud6.atd.invoices.InvoicesShowServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*  w ww.j  av a 2  s.  c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SessionFactory factory = new HibernateConnector().getSessionFactory();
    Session hibernateSession = factory.openSession();
    Transaction tx = null;

    boolean idSet = false;
    if (request.getParameter("id") == null || request.getParameter("id").equals("")) {
        response.sendRedirect("invoices");
    } else {
        try {
            Factuur gekozenFactuur = new Factuur();
            gekozenFactuur = (Factuur) hibernateSession.get(Factuur.class,
                    Integer.parseInt(request.getParameter("id")));
            if (gekozenFactuur == null) {
                response.sendRedirect("invoices");
            } else {
                HttpSession session = request.getSession(true);
                RequestDispatcher rd = null;
                if (!RightsControl.checkGroup("invoices_show", "own", session,
                        gekozenFactuur.getDeKlant().getGebruiker().getId())) {
                    rd = request.getRequestDispatcher("error/403error.jsp");
                    rd.forward(request, response);
                    return;
                }

                response.addHeader("Content-Disposition",
                        "attachment; filename=fac" + gekozenFactuur.getFactuurNummer() + ".pdf");
                Process process = Runtime.getRuntime().exec(
                        "c:\\rotativa\\wkhtmltopdf.exe -q -n --disable-smart-shrinking http://localhost:8080/Themaproject/invoicessource?id="
                                + request.getParameter("id") + "&secret=" + gekozenFactuur.getSecret() + " -");
                response.setContentType("application/pdf");
                try {
                    IOUtils.copy(process.getInputStream(), response.getOutputStream());
                } finally {
                    process.getInputStream().close();
                    response.getOutputStream().close();
                }
            }
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            hibernateSession.close();
        }
    }

}

From source file:com.gs.config.CustomFilterLogin.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Assert.isInstanceOf(HttpServletRequest.class, request, "Can only process HttpServletRequest");
    Assert.isInstanceOf(HttpServletResponse.class, response, "Can only process HttpServletResponse");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    //        System.out.println("ESTOY EN CUSTOMFILTERLOGIN: "+httpRequest.getServletPath());
    String path = httpRequest.getServletPath();
    HttpSession session = httpRequest.getSession(false);
    if (session == null && !httpRequest.isRequestedSessionIdValid()) {
        String targetUrl = httpRequest.getContextPath() + "/login";
        httpResponse.sendRedirect(httpResponse.encodeRedirectURL(targetUrl));
        return;//from w ww  . j ava 2 s.  c  o  m
    }
    chain.doFilter(request, response);
}

From source file:edu.pitt.rest.diagnosisws.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  ww . java 2s .  com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        HttpSession session = request.getSession(true);

        if (Security.checkHijackedSession(session, request)) {
            response.sendRedirect("index.jsp");
        }

        String diagnosis = "";
        if (request.getParameter("diagnosis") != null) {
            diagnosis = request.getParameter("diagnosis").toString();
        }
        MySqlDbUtilities db = new MySqlDbUtilities();
        String sql = "SELECT * FROM diagnoses ";
        if (!diagnosis.equals("")) {
            sql += "WHERE diagnosisName LIKE '" + diagnosis + "%" + "' ";
        }
        sql += "LIMIT 20;";
        JSONArray fullUserList = new JSONArray();
        ResultSet rs = db.getResultSet(sql);

        while (rs.next()) {
            Diagnosis diag = new Diagnosis(rs.getString("diagnosisId"));
            fullUserList.put(diag.getDiagnosisAsJSON());
            diag.getDb().closeDbConnection();
        }

        StringWriter sw = new StringWriter();
        fullUserList.write(sw);
        out.print(sw.toString());

    } catch (SQLException ex) {
        Logger.getLogger(patientvisitws.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(patientvisitws.class.getName()).log(Level.SEVERE, null, ex);
    }

    finally {
        out.close();
    }
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateIndexController.java

@RequestMapping(value = "/createindex", method = RequestMethod.GET)
public String createIndex(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {

    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from  w  w  w.  j av  a2s .c  o  m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to create a new index");

    String tabName = (String) request.getParameter("tabName");
    String schema = (String) request.getParameter("schemaName");

    logger.debug("Table = " + schema + "." + tabName);

    IndexDAO indexDAO = GemFireXDWebDAOFactory.getIndexDAO();

    List<IndexColumn> columns = indexDAO.retrieveIndexColumns(schema, tabName,
            (String) session.getAttribute("user_key"));

    model.addAttribute("tabName", tabName);
    model.addAttribute("tableSchemaName", schema);
    model.addAttribute("columns", columns);
    model.addAttribute("schema", schema);

    model.addAttribute("indexAttribute", new NewIndex());

    // This will resolve to /WEB-INF/jsp/create-index.jsp
    return "create-index";
}

From source file:com.hp.avmon.home.web.HomeController.java

/**
 * /*from w ww  .j a v a2s.co m*/
 * @throws IOException 
 * @throws ServletException 
 */
@RequestMapping(value = "/")
public void index(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // ?
    logger.debug("go to login.jsp !!!");
    //return main(session,model);
    //request.getRequestDispatcher("modules/index.jsp").forward(request, response);
    response.sendRedirect("modules/index.jsp");

}

From source file:edu.pitt.rest.symptomws.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  ww  .j  a  va  2s  . c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

        HttpSession session = request.getSession(true);

        if (Security.checkHijackedSession(session, request)) {
            response.sendRedirect("index.jsp");
        }

        String symptom = "";
        if (request.getParameter("symptom") != null) {
            symptom = request.getParameter("symptom").toString();
        }
        MySqlDbUtilities db = new MySqlDbUtilities();
        String sql = "SELECT * FROM symptoms ";
        if (!symptom.equals("")) {
            sql += "WHERE symptomName LIKE '" + symptom + "%" + "' ";
        }
        sql += "LIMIT 20;";
        JSONArray fullSymptomList = new JSONArray();
        ResultSet rs = db.getResultSet(sql);

        while (rs.next()) {
            Symptom symp = new Symptom(rs.getString("symptomId"));
            fullSymptomList.put(symp.getSymptomAsJSON());
            symp.getDb().closeDbConnection();
        }

        StringWriter sw = new StringWriter();
        fullSymptomList.write(sw);
        out.print(sw.toString());
    } catch (SQLException ex) {
        Logger.getLogger(patientvisitws.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(patientvisitws.class.getName()).log(Level.SEVERE, null, ex);
    }

    finally {
        out.close();
    }
}