Java 类javax.servlet.RequestDispatcher 实例源码

项目:LojaDeInstrumentosMusicais    文件:EditarUsuarioServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String destino;
    request.setCharacterEncoding("UTF-8");
    HttpSession sessao = request.getSession();
    if (sessao.getAttribute("usuario") != null) {
        request.setAttribute("usuario", sessao.getAttribute("usuario"));
        // Remove o atributo da sessao para usuario nao ficar preso na tela de resultados           

        destino = "alterarUsuario.jsp";
    } else {
        destino = "alterarUsuario.jsp";
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher(destino);
    dispatcher.forward(request, response);

}
项目:LojaDeInstrumentosMusicais    文件:ConsultarClienteServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<Cliente> clientes = new ArrayList<>();
    ClienteDAO cd = new ClienteDAO();
    try {
        //clientes = cd.listarCliente("");
    } catch (Exception ex) {
        Logger.getLogger(ConsultarClienteServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    request.setAttribute("listaClientes", clientes);
    RequestDispatcher dispatcher = request.getRequestDispatcher("consultarCliente.jsp");
dispatcher.forward(request, response);
}
项目:scott-eu    文件:ServiceProviderCatalogService.java   
/**
 * Return the catalog singleton as HTML
 *
 * Forwards to serviceprovidercatalog_html.jsp to build the html
 *
 * @param serviceProviderId
 */
@GET
@Path("{someId}")
@Produces(MediaType.TEXT_HTML)
public void getHtmlServiceProvider(@PathParam("someId") final String someId)
{
    ServiceProviderCatalog catalog = ServiceProviderCatalogSingleton.getServiceProviderCatalog(httpServletRequest);

    if (catalog !=null )
    {
        httpServletRequest.setAttribute("catalog",catalog);
        // Start of user code getHtmlServiceProvider_setAttributes
        // End of user code

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/serviceprovidercatalog.jsp");
        try {
            rd.forward(httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            e.printStackTrace();
            throw new WebApplicationException(e);
        }
    }
}
项目:central-medic-center    文件:CloseAppointment.java   
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try{
        int appointmentId = Integer.valueOf(request.getParameter("appointmentId"));
        String by = (String)request.getParameter("by");
        int status = new DatabaseHelper().closeAppointment(appointmentId, by);
        if (status > 0) {
            // successfully inserted
            RequestDispatcher rs;
            rs = request.getRequestDispatcher((String)request.getParameter("requestDispatcher"));
            request.setAttribute("appointmentId", appointmentId);
            rs.forward(request, response);
        } else {
            // redirect to login
            redirectToLogin(request, response);
        }
    }catch(Exception e){
        e.printStackTrace();
        // redirect to login
        redirectToLogin(request, response);
    }
}
项目:ChemistryAdministrativePortal    文件:FacultyServlet.java   
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    ReadQuery rq = new ReadQuery("faculty");
    String affectedTable = rq.doRead("faculty");
    String table = rq.createHTMLTable();

    request.setAttribute("table", table);
    request.setAttribute("affectedTable", affectedTable);
    String url = "/table.jsp";

    if(request.getAttribute("message") != null) {
        request.setAttribute("message", (String) request.getAttribute("message"));
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher(url);
    dispatcher.forward(request, response);
}
项目:lazycat    文件:JspServlet.java   
private void handleMissingResource(HttpServletRequest request, HttpServletResponse response, String jspUri)
        throws ServletException, IOException {

    String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);

    if (includeRequestUri != null) {
        // This file was included. Throw an exception as
        // a response.sendError() will be ignored
        String msg = Localizer.getMessage("jsp.error.file.not.found", jspUri);
        // Strictly, filtering this is an application
        // responsibility but just in case...
        throw new ServletException(SecurityUtil.filter(msg));
    } else {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        } catch (IllegalStateException ise) {
            log.error(Localizer.getMessage("jsp.error.file.not.found", jspUri));
        }
    }
    return;
}
项目:lams    文件:DefaultServlet.java   
private String getPath(final HttpServletRequest request) {
    String servletPath;
    String pathInfo;

    if (request.getDispatcherType() == DispatcherType.INCLUDE && request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        servletPath = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    } else {
        pathInfo = request.getPathInfo();
        servletPath = request.getServletPath();
    }
    String result = pathInfo;
    if (result == null) {
        result = servletPath;
    } else if(resolveAgainstContextRoot) {
        result = servletPath + CanonicalPathUtils.canonicalize(pathInfo);
    } else {
        result = CanonicalPathUtils.canonicalize(result);
    }
    if ((result == null) || (result.equals(""))) {
        result = "/";
    }
    return result;

}
项目:tomcat7    文件:JspRuntimeLibrary.java   
/**
 * Perform a RequestDispatcher.include() operation, with optional flushing
 * of the response beforehand.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param relativePath The relative path of the resource to be included
 * @param out The Writer to whom we are currently writing
 * @param flush Should we flush before the include is processed?
 *
 * @exception IOException if thrown by the included servlet
 * @exception ServletException if thrown by the included servlet
 */
public static void include(ServletRequest request,
                           ServletResponse response,
                           String relativePath,
                           JspWriter out,
                           boolean flush)
    throws IOException, ServletException {

    if (flush && !(out instanceof BodyContent))
        out.flush();

    // FIXME - It is tempting to use request.getRequestDispatcher() to
    // resolve a relative path directly, but Catalina currently does not
    // take into account whether the caller is inside a RequestDispatcher
    // include or not.  Whether Catalina *should* take that into account
    // is a spec issue currently under review.  In the mean time,
    // replicate Jasper's previous behavior

    String resourcePath = getContextRelativePath(request, relativePath);
    RequestDispatcher rd = request.getRequestDispatcher(resourcePath);

    rd.include(request,
               new ServletResponseWrapperInclude(response, out));

}
项目:oscm    文件:ClosedMarketplaceFilterTest.java   
@Test
public void testDoFilter_saml() throws Exception {
    doReturn(true).when(closedMplFilter).isSAMLAuthentication();

    // given
    RequestDispatcher dispatcherMock = mock(RequestDispatcher.class);
    ServletContext mockServletContext = mock(ServletContext.class);
    doReturn(mockServletContext).when(requestMock).getServletContext();
    doReturn(dispatcherMock).when(mockServletContext).getRequestDispatcher(
            any(String.class));
    doReturn(true).when(closedMplFilter).isSAMLAuthentication();
    doReturn("/portal/*").when(requestMock).getServletPath();
    doReturn("mpid").when(sessionMock).getAttribute(
            Constants.REQ_PARAM_MARKETPLACE_ID);
    doReturn(getConfiguration(true, true, "testOrg")).when(closedMplFilter)
            .getConfig("mpid");
    doReturn(getUserDetails("anotherOrg")).when(sessionMock).getAttribute(
            Constants.SESS_ATTR_USER);

    // when
    closedMplFilter.doFilter(requestMock, responseMock, chainMock);

    // then
    verify(dispatcherMock, times(1)).forward(requestMock, responseMock);

}
项目:lams    文件:RequestProcessor.java   
/**
 * <p>Do a forward to specified URI using a <code>RequestDispatcher</code>.
 * This method is used by all internal method needing to do a forward.</p>
 *
 * @param uri Context-relative URI to forward to
 * @param request Current page request
 * @param response Current page response
 * @since Struts 1.1
 */
protected void doForward(
    String uri,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

    // Unwrap the multipart request, if there is one.
    if (request instanceof MultipartRequestWrapper) {
        request = ((MultipartRequestWrapper) request).getRequest();
    }

    RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
    if (rd == null) {
        response.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            getInternal().getMessage("requestDispatcher", uri));
        return;
    }
    rd.forward(request, response);
}
项目:scott-eu    文件:ServiceProviderCatalogService.java   
/**
 * Return the catalog singleton as HTML
 *
 * Forwards to serviceprovidercatalog_html.jsp to build the html
 *
 * @param serviceProviderId
 */
@GET
@Path("{someId}")
@Produces(MediaType.TEXT_HTML)
public void getHtmlServiceProvider(@PathParam("someId") final String someId)
{
    ServiceProviderCatalog catalog = ServiceProviderCatalogSingleton.getServiceProviderCatalog(httpServletRequest);

    if (catalog !=null )
    {
        httpServletRequest.setAttribute("catalog",catalog);
        // Start of user code getHtmlServiceProvider_setAttributes
        // End of user code

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/serviceprovidercatalog.jsp");
        try {
            rd.forward(httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            e.printStackTrace();
            throw new WebApplicationException(e);
        }
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:StandardContextValve.java   
/**
 * Select the appropriate child Wrapper to process this request,
 * based on the specified request URI.  If no matching Wrapper can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Disallow any direct access to resources under WEB-INF or META-INF
    MessageBytes requestPathMB = request.getRequestPathMB();
    if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/META-INF"))
            || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Select the Wrapper to be used for this Request
    Wrapper wrapper = request.getWrapper();
    if (wrapper == null || wrapper.isUnavailable()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Acknowledge the request
    try {
        response.sendAcknowledgement();
    } catch (IOException ioe) {
        container.getLogger().error(sm.getString(
                "standardContextValve.acknowledgeException"), ioe);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    if (request.isAsyncSupported()) {
        request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported());
    }
    wrapper.getPipeline().getFirst().invoke(request, response);
}
项目:apache-tomcat-7.0.73-with-comment    文件:Request.java   
/**
 * Notify interested listeners that attribute has been removed.
 */
private void notifyAttributeRemoved(String name, Object value) {
    Object listeners[] = context.getApplicationEventListeners();
    if ((listeners == null) || (listeners.length == 0)) {
        return;
    }
    ServletRequestAttributeEvent event =
      new ServletRequestAttributeEvent(context.getServletContext(),
                                       getRequest(), name, value);
    for (int i = 0; i < listeners.length; i++) {
        if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
            continue;
        }
        ServletRequestAttributeListener listener =
            (ServletRequestAttributeListener) listeners[i];
        try {
            listener.attributeRemoved(event);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
            // Error valve will pick this exception up and display it to user
            attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
        }
    }
}
项目:central-medic-center    文件:UpdateAdminProfile.java   
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
        HttpSession session = request.getSession();
        int adminId = (int) session.getAttribute("UserID");
        // get admin details
        DatabaseHelper databaseHelper = new DatabaseHelper();
        Staff admin = databaseHelper.getStaff(adminId);
        if (admin == null ) {
            // redirect to login
            redirectToLogin(request, response);
            return;
        }
        // redirect to admin dashboard
        RequestDispatcher rs = request.getRequestDispatcher("editAdminProfile.jsp");
        request.setAttribute("admin", admin);
        rs.forward(request, response);
        return;
    } catch (Exception e) {
        // redirect to login
        redirectToLogin(request, response);
    }
}
项目:redesocial    文件:AlbumControle.java   
/**
* Edita um álbum no banco de dados
* @param request requisição
* @param response resposta
* @throws ServletException se ocorre um erro no Servlet
* @throws IOException se ocorre um erro de entrada e saída
*/
private void editar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Integer id = Integer.parseInt(request.getParameter("idalbum"));

        AlbumBO bo = new AlbumBO();
        Album album = bo.selecionar(id);

        Usuario usuario = getUsuario(request);
        request.setAttribute("usuario", usuario);

        request.setAttribute("album", album);
        request.setAttribute("mensagem", "Registro Selecionado com sucesso!");
    } catch (Exception ex) {
        request.setAttribute("erro", ex.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/galeria/cadastro_albuns.jsp");
    rd.forward(request, response);
}
项目:JavaEE    文件:ProductListServlet.java   
@Override
protected void doGet(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException {

    Connection conn = MyUtils.getStoredConnection(request);

    String errorString = null;
    List<Product> list = null;
    try {
        if (conn == null) // if conn was not stored
            conn = ConnectionUtils.getConnection();
        list = DBUtils.queryProduct(conn);
    } catch (Exception e) {
        e.printStackTrace();
        errorString = e.getMessage();
    }

    // store info in request attribute, before forward to views
    request.setAttribute("errorString", errorString);
    request.setAttribute("productList", list);

    // forward to /WEB-INF/views/productListView.jsp
    RequestDispatcher dispatcher = request.getServletContext()
            .getRequestDispatcher("/WEB-INF/views/productListView.jsp");
    dispatcher.forward(request, response);
}
项目:central-medic-center    文件:SubmitLabReport.java   
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {           
        // get doctor lab report id
        int labReportId = Integer.parseInt((String)request.getParameter("labId"));
        DatabaseHelper databaseHelper = new DatabaseHelper();
        int status = databaseHelper.updateLabReport(labReportId, (String)request.getParameter("result"), 
                Integer.parseInt((String)request.getParameter("itemId")));
        if (status<=0) {
            //error
            // redirect to login
            redirectToLogin(request, response);
            return;
        }
        // redirect to lab person dashboard
        RequestDispatcher rs = request.getRequestDispatcher("labPerson");
        rs.forward(request, response);
        return;
    } catch (Exception e) {
        // redirect to login
        redirectToLogin(request, response);
    }
}
项目:E-App    文件:RegistrationController.java   
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      
    String username=request.getParameter("username");
    String email=request.getParameter("email");
    String password=request.getParameter("password");

    //Connection con=DatabaseConnectionFactory.createConnection();

    try
    {
    // Statement st=con.createStatement();
    // String sql = "INSERT INTO users values ('"+username+"','"+password+"','"+email+"')";
            //System.out.println(sql);
     //st.executeUpdate(sql);
    }catch(Exception sqe){System.out.println("Error : While Inserting record in database");}
    try
    {
     //con.close();
    }catch(Exception se){System.out.println("Error : While Closing Connection");}
       request.setAttribute("newUser",username);
    RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/jsps/regSuccess.jsp");
    dispatcher.forward(request, response);      
}
项目:redesocial    文件:TiposAtividadesControle.java   
/**
 * Cadastra uma atividade no banco de dados
 * @param request
 * @param response
 * @throws Exception
 */
private void cadastrar(HttpServletRequest request, HttpServletResponse response) throws Exception{
    TiposAtividades tiposAtividades = new TiposAtividades ();

    if (!"".equals(request.getParameter("id").trim())){
        tiposAtividades.setId(Integer.parseInt(request.getParameter("id")));
    }

    tiposAtividades.setNome(request.getParameter("nome"));


    request.setAttribute("nome", tiposAtividades);

    if (tiposAtividades.getId() == null){
        this.inserir(tiposAtividades, request, response);
    } else {
        this.alterar(tiposAtividades, request, response);
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/tiposAtividades.jsp");
    rd.forward(request, response);
}
项目:central-medic-center    文件:UpdateDoctorProfile.java   
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
        HttpSession session = request.getSession();
        int doctorId = (int) session.getAttribute("UserID");
        // get doctor details
        DatabaseHelper databaseHelper = new DatabaseHelper();
        Doctor doctor = databaseHelper.getDoctor(doctorId);
        ArrayList<ArrayList<Appointment>> appointments = databaseHelper.getAppointments(doctorId, "doctorId");
        if (doctor == null || appointments == null) {
            // redirect to login
            redirectToLogin(request, response);
            return;
        }
        // redirect to doctor dashboard
        RequestDispatcher rs = request.getRequestDispatcher("editDoctorProfile.jsp");
        request.setAttribute("doctor", doctor);
        request.setAttribute("appointments", appointments);
        rs.forward(request, response);
        return;
    } catch (Exception e) {
        // redirect to login
        redirectToLogin(request, response);
    }
}
项目:scott-eu    文件:ServiceProviderService1.java   
@GET
@Path("places/{placeId}")
@Produces({ MediaType.TEXT_HTML })
public Response getPlaceAsHtml(
    @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("placeId") final String placeId
    ) throws ServletException, IOException, URISyntaxException
{
    // Start of user code getPlaceAsHtml_init
    // End of user code

    final Place aPlace = WarehouseControllerManager.getPlace(httpServletRequest, serviceProviderId, placeId);

    if (aPlace != null) {
        httpServletRequest.setAttribute("aPlace", aPlace);
        // Start of user code getPlaceAsHtml_setAttributes
        // End of user code

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/place.jsp");
        rd.forward(httpServletRequest,httpServletResponse);
    }

    throw new WebApplicationException(Status.NOT_FOUND);
}
项目:redesocial    文件:PaisControle.java   
private void editar(HttpServletRequest request, HttpServletResponse response) throws Exception{
    try {
        Integer id = Integer.parseInt(request.getParameter("id"));

        PaisBO paisBO = new PaisBO();
        Pais pais = paisBO.selecionar(id);

        request.setAttribute("pais", pais);

        request.setAttribute("mensagem", "Registro selecionado com sucesso");
    } catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/paises/cadastro_paises.jsp");
    rd.forward(request, response);
}
项目:parabuild-ci    文件:TestServletTestCase2.java   
/**
 * Verify that getNamedDispatcher() can be used to get a dispatcher.
 */
public void testGetRequestDispatcherFromNamedDispatcherOK()
    throws ServletException, IOException
{
    RequestDispatcher rd =
        config.getServletContext().getNamedDispatcher("TestJsp");
    rd.forward(request, response);
}
项目:redesocial    文件:EstadoControle.java   
/**
 * Insere um estado no banco de dados
 * @param request
 * @param response
 * @throws Exception
 */
private void inserir(Estado estado, HttpServletRequest request, HttpServletResponse response) throws Exception{
    try {
        EstadoBO estadoBO = new EstadoBO();
        estadoBO.inserir(estado);

        request.setAttribute("mensagem", "Cadastro realizado com sucesso");
    } catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/estados/cadastro_estados.jsp");
    rd.forward(request, response);
}
项目:redesocial    文件:AlbumControle.java   
/**
* Cria um novo álbum
* @param request requisição
* @param response resposta
* @throws ServletException se ocorre um erro no Servlet
* @throws IOException se ocorre um erro de entrada e saída
*/
private void criarNovo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Album album = new Album();

        Usuario usuario = getUsuario(request);
        request.setAttribute("usuario", usuario);
        request.setAttribute("album", album);
    } catch (Exception e) {
        request.setAttribute("erro", e.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/galeria/cadastro_albuns.jsp");
    rd.forward(request, response);
}
项目:LojaDeInstrumentosMusicais    文件:ConsultaUsuariosTotaisServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

      RequestDispatcher dispatcher
 = request.getRequestDispatcher("/consultarUsuario.jsp");
dispatcher.forward(request, response);
}
项目:Projeto_Integrador_3_Semestre    文件:CadastrarSLAServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/SLA.jsp");
    dispatcher.forward(request, response);

}
项目:Projeto_Integrador_3_Semestre    文件:LoginServlet.java   
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession sessao = request.getSession(false);
    if (sessao != null && sessao.getAttribute("usuario") != null) {
        response.sendRedirect(request.getContextPath() + "/inicio");
        return;
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/login.jsp");
    dispatcher.forward(request, response);
}
项目:apache-tomcat-7.0.73-with-comment    文件:PageContextImpl.java   
private final String getAbsolutePathRelativeToContext(String relativeUrlPath) {
    String path = relativeUrlPath;

    if (!path.startsWith("/")) {
        String uri = (String) request.getAttribute(
                RequestDispatcher.INCLUDE_SERVLET_PATH);
        if (uri == null)
            uri = ((HttpServletRequest) request).getServletPath();
        String baseURI = uri.substring(0, uri.lastIndexOf('/'));
        path = baseURI + '/' + path;
    }

    return path;
}
项目:OftenPorter    文件:WebSocketHandle.java   
private void doConnect(WObject wObject, PorterOfFun porterOfFun) throws ServletException, IOException
{
    HttpServletRequest request = wObject.getRequest().getOriginalRequest();
    HttpServletResponse response = wObject.getRequest().getOriginalResponse();
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(XSServletWSConfig.WS_PATH);
    HttpSession session = request.getSession();

    session.setAttribute(WObject.class.getName(), wObject);
    session.setAttribute(PorterOfFun.class.getName(), porterOfFun);
    session.setAttribute(WebSocket.class.getName(), webSocket);

    requestDispatcher.forward(request, response);
}
项目:Projeto_Integrador_3_Semestre    文件:BuscaClienteServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/BuscaCliente.jsp");
    dispatcher.forward(request, response);
}
项目:Projeto_Integrador_3_Semestre    文件:BuscaFuncionarioServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/BuscaFuncionario.jsp");
    dispatcher.forward(request, response);
}
项目:LojaDeInstrumentosMusicais    文件:ExcluirProdutoServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      RequestDispatcher dispatcher
 = request.getRequestDispatcher("/consultarProduto.jsp");
dispatcher.forward(request, response);
}
项目:LojaDeInstrumentosMusicais    文件:CadastrarProdutoServlet.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

      RequestDispatcher dispatcher
 = request.getRequestDispatcher("/cadastroProduto.jsp");
    dispatcher.forward(request, response);

}
项目:tomcat7    文件:StandardContext.java   
@Override
public boolean fireRequestDestroyEvent(ServletRequest request) {
    Object instances[] = getApplicationEventListeners();

    if ((instances != null) && (instances.length > 0)) {

        ServletRequestEvent event = 
            new ServletRequestEvent(getServletContext(), request);

        for (int i = 0; i < instances.length; i++) {
            int j = (instances.length -1) -i;
            if (instances[j] == null)
                continue;
            if (!(instances[j] instanceof ServletRequestListener))
                continue;
            ServletRequestListener listener =
                (ServletRequestListener) instances[j];

            try {
                listener.requestDestroyed(event);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                getLogger().error(sm.getString(
                        "standardContext.requestListener.requestInit",
                        instances[j].getClass().getName()), t);
                request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
                return false;
            }
        }
    }
    return true;
}
项目:central-medic-center    文件:PatientServlet.java   
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        session = request.getSession();
        if (session.isNew()){
            redirectToLogin(request, response);
             }
        else{

        int personId = (int) session.getAttribute("UserID");
        // get patient details
        DatabaseHelper databaseHelper = new DatabaseHelper();
        Patient patient = databaseHelper.getPatient(personId);
        DashBoard dashBoard = new DashBoard(databaseHelper.getAppointmentCount(personId,"patientId"), 
                DashUtils.getBMI(patient.getHeight(), patient.getWeight()),DashUtils.getMedicineCount(personId),DashUtils.getProfileRating(personId, 1));
        ArrayList<ArrayList<Appointment>> appointments = databaseHelper.getAppointments(personId, "patientId");
        if (patient == null || appointments == null || dashBoard == null) {
            // redirect to login
            redirectToLogin(request, response);
            return;
        }
        // redirect to person dashboard
        RequestDispatcher rs = request.getRequestDispatcher("patient.jsp");
        request.setAttribute("patient", patient);
        request.setAttribute("appointments", appointments);
        request.setAttribute("dashBoard", dashBoard);
        rs.forward(request, response);
        return;
        }
    } catch (Exception e) {
        // redirect to login
        redirectToLogin(request, response);
    }
    }
项目:hadoop    文件:DefaultWrapperServlet.java   
@Private
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
  RequestDispatcher rd = getServletContext().getNamedDispatcher("default");

  HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
    public String getServletPath() {
    return "";
    }
  };

  rd.forward(wrapped, resp);
  }
项目:lams    文件:HttpServletRequestImpl.java   
@Override
public RequestDispatcher getRequestDispatcher(final String path) {
    String realPath;
    if (path.startsWith("/")) {
        realPath = path;
    } else {
        String current = exchange.getRelativePath();
        int lastSlash = current.lastIndexOf("/");
        if (lastSlash != -1) {
            current = current.substring(0, lastSlash + 1);
        }
        realPath = CanonicalPathUtils.canonicalize(current + path);
    }
    return new RequestDispatcherImpl(realPath, servletContext);
}
项目:the-vigilantes    文件:Delete.java   
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @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("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Delete</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet Delete at " + request.getContextPath() + "</h1>");    
        Tools dbTools = new Tools();
        dbTools.connect();
        dbTools.Delete();
        Integer userId = Integer.parseInt(request.getParameter("delete")); // Lagrer brukerId til brukeren som skal slettessom blir sent med fra fra JSP siden
        try {
        dbTools.deleteUser(userId);
        RequestDispatcher rd = request.getRequestDispatcher("JSP/DeleteUser.jsp");
        rd.forward(request, response);
        }
        catch (IOException e) {
            out.println("Det har oppstått en feil, venligst prøv igjen");

        }

        out.println("</body>");
        out.println("</html>");
    }
}
项目:parabuild-ci    文件:RequestDispatcherTest.java   
public void testRequestDispatcherIncludePaths() throws Exception {
        InvocationContext ic = _runner.newClient().newInvocation( "http://localhost/sample/" + outerServletName + "?param=original&param1=first" );

        final HttpServletRequest request = ic.getRequest();
        RequestDispatcherServlet servlet = (RequestDispatcherServlet) ic.getServlet();
        RequestDispatcher rd = servlet.getServletContext().getRequestDispatcher( "/" + innerServletName + "?param=revised&param2=new" );

        assertEquals( "request URI", "/sample/" + outerServletName, request.getRequestURI() );
        assertEquals( "context path attribute", "/sample", request.getContextPath() );
        assertEquals( "servlet path attribute", "/" + outerServletName, request.getServletPath() );
        assertNull( "path info not null attribute", request.getPathInfo() );
//        assertEquals( "query string attribute", "param=original&param1=first", request.getQueryString() ); TODO make this work

        final HttpServletResponse response = ic.getResponse();
        ic.pushIncludeRequest( rd, request, response );

        final HttpServletRequest innerRequest = ic.getRequest();
        assertEquals( "request URI", "/sample/" + outerServletName, innerRequest.getRequestURI() );
        assertEquals( "context path attribute", "/sample", innerRequest.getContextPath() );
        assertEquals( "servlet path attribute", "/" + outerServletName, innerRequest.getServletPath() );
        assertNull( "path info not null attribute", innerRequest.getPathInfo() );
//        assertEquals( "query string attribute", "param=original&param1=first", innerRequest.getQueryString() );

        assertEquals( "request URI attribute", "/sample/" + innerServletName, innerRequest.getAttribute( REQUEST_URI ) );
        assertEquals( "context path attribute", "/sample", innerRequest.getAttribute( CONTEXT_PATH ) );
        assertEquals( "servlet path attribute", "/" + innerServletName, innerRequest.getAttribute( SERVLET_PATH ) );
        assertNull( "path info attribute not null", innerRequest.getAttribute( PATH_INFO ) );
//        assertEquals( "query string attribute", "param=revised&param2=new", innerRequest.getAttribute( QUERY_STRING ) );

        ic.popRequest();
        final HttpServletRequest restoredRequest = ic.getRequest();

        assertNull( "reverted URI attribute not null", restoredRequest.getAttribute( REQUEST_URI ) );
        assertNull( "context path attribute not null", restoredRequest.getAttribute( CONTEXT_PATH ) );
        assertNull( "servlet path attribute not null", restoredRequest.getAttribute( SERVLET_PATH ) );
        assertNull( "path info attribute not null", restoredRequest.getAttribute( PATH_INFO ) );
//        assertNull( "query string attribute not null", "param=revised&param2=new", restoredRequest.getAttribute( QUERY_STRING ) );
    }