Java Code Examples for javax.servlet.RequestDispatcher#forward()

The following examples show how to use javax.servlet.RequestDispatcher#forward() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlbumControle.java    From redesocial with MIT License 6 votes vote down vote up
/**
* Lista todos os álbuns existentes 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 listar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Usuario usuario = getUsuario(request);
    
    try{
        AlbumBO bo = new AlbumBO();
        List album = bo.listarAlbunsPessoais(usuario.getId());

        request.setAttribute("usuario", usuario);
        
        request.setAttribute("album", album);
    }catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }
    
    RequestDispatcher rd = request.getRequestDispatcher("paginas/galeria/listagem_albuns.jsp");
    rd.forward(request, response);
}
 
Example 2
Source File: TiposAtividadesControle.java    From redesocial with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: MockServletContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void setDefaultServletName() throws Exception {
	final String originalDefault = "default";
	final String newDefault = "test";
	assertNotNull(sc.getNamedDispatcher(originalDefault));

	sc.setDefaultServletName(newDefault);
	assertEquals(newDefault, sc.getDefaultServletName());
	assertNull(sc.getNamedDispatcher(originalDefault));

	RequestDispatcher namedDispatcher = sc.getNamedDispatcher(newDefault);
	assertNotNull(namedDispatcher);
	MockHttpServletResponse response = new MockHttpServletResponse();
	namedDispatcher.forward(new MockHttpServletRequest(sc), response);
	assertEquals(newDefault, response.getForwardedUrl());
}
 
Example 4
Source File: RequestForwardUtils.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void forwardRequestRelativeToGivenContext(String fwdPath, ServletContext targetContext,
    HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  if (fwdPath == null || targetContext == null || request == null || response == null) {
    String msg = "Path, context, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToGivenContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();
  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = targetContext.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example 5
Source File: UserFilter.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String url = request.getRequestURI();
    if (!urlSet.contains(url)) {
        String token = request.getHeader(JwtUtils.AUTHORIZATION_HEADER_PREFIX);
        String privateSecret = GovernanceApplication.governanceConfig.getPrivateSecret();
        if (!StringUtils.isBlank(token) && JwtUtils.verifierToken(token, privateSecret)) {
            AccountEntity accountEntity = JwtUtils.decodeToken(token, privateSecret);
            if (accountEntity != null) {
                log.info("get token from HTTP header, {} : {}", JwtUtils.AUTHORIZATION_HEADER_PREFIX, token);
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(accountEntity.getUsername(), null, null);
                auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        filterChain.doFilter(request, response);
    } else {
        String newPath = url.replace("/weevent-governance", "");
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(newPath);
        requestDispatcher.forward(request, response);

    }

}
 
Example 6
Source File: CidadeControle.java    From redesocial with MIT License 6 votes vote down vote up
private void editar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Integer id = Integer.parseInt(request.getParameter("id"));

        CidadeBO cidadeBO = new CidadeBO();
        Cidade cidade = cidadeBO.selecionar(id);

        request.setAttribute("cidade", cidade);

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

    RequestDispatcher rd = request.getRequestDispatcher("paginas/cidades/cadastro_cidades.jsp");
    rd.forward(request, response);
}
 
Example 7
Source File: MockServletContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void registerAndUnregisterNamedDispatcher() throws Exception {
	final String name = "test-servlet";
	final String url = "/test";
	assertNull(sc.getNamedDispatcher(name));

	sc.registerNamedDispatcher(name, new MockRequestDispatcher(url));
	RequestDispatcher namedDispatcher = sc.getNamedDispatcher(name);
	assertNotNull(namedDispatcher);
	MockHttpServletResponse response = new MockHttpServletResponse();
	namedDispatcher.forward(new MockHttpServletRequest(sc), response);
	assertEquals(url, response.getForwardedUrl());

	sc.unregisterNamedDispatcher(name);
	assertNull(sc.getNamedDispatcher(name));
}
 
Example 8
Source File: MockServletContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void setDefaultServletName() throws Exception {
	final String originalDefault = "default";
	final String newDefault = "test";
	assertNotNull(sc.getNamedDispatcher(originalDefault));

	sc.setDefaultServletName(newDefault);
	assertEquals(newDefault, sc.getDefaultServletName());
	assertNull(sc.getNamedDispatcher(originalDefault));

	RequestDispatcher namedDispatcher = sc.getNamedDispatcher(newDefault);
	assertNotNull(namedDispatcher);
	MockHttpServletResponse response = new MockHttpServletResponse();
	namedDispatcher.forward(new MockHttpServletRequest(sc), response);
	assertEquals(newDefault, response.getForwardedUrl());
}
 
Example 9
Source File: MockServletContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void registerAndUnregisterNamedDispatcher() throws Exception {
	final String name = "test-servlet";
	final String url = "/test";
	assertNull(sc.getNamedDispatcher(name));

	sc.registerNamedDispatcher(name, new MockRequestDispatcher(url));
	RequestDispatcher namedDispatcher = sc.getNamedDispatcher(name);
	assertNotNull(namedDispatcher);
	MockHttpServletResponse response = new MockHttpServletResponse();
	namedDispatcher.forward(new MockHttpServletRequest(sc), response);
	assertEquals(url, response.getForwardedUrl());

	sc.unregisterNamedDispatcher(name);
	assertNull(sc.getNamedDispatcher(name));
}
 
Example 10
Source File: ArtigoControle.java    From redesocial with MIT License 5 votes vote down vote up
private void listar(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        ArtigoBO bo = new ArtigoBO();
        List artigos = bo.listar();

        request.setAttribute("lista", artigos);
    } catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/artigos/listagem.jsp");
    rd.forward(request, response);
}
 
Example 11
Source File: EstadoControle.java    From redesocial with MIT License 5 votes vote down vote up
/**
 * Lista todos os estados no banco de dados
 * @param request
 * @param response
 * @throws Exception
 */
private void listar(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        EstadoBO bo = new EstadoBO();
        List estados = bo.listar();

        request.setAttribute("lista", estados);
    } catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }

    RequestDispatcher rd = request.getRequestDispatcher("paginas/paises/listagem_estados.jsp");
    rd.forward(request, response);
}
 
Example 12
Source File: AlbumControle.java    From redesocial with MIT License 5 votes vote down vote up
/**
* 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);
}
 
Example 13
Source File: DeleteHeroServlet.java    From SA47 with The Unlicense 5 votes vote down vote up
private void doProcess(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	String username = request.getParameter("name");
	HeroManager hm = new HeroManager();
	HeroDTO hero = hm.findHero(username);
	System.out.println(hero.toString());
	hm.deleteHero(hero);
	RequestDispatcher rd = request.getRequestDispatcher("/load");
	rd.forward(request, response);
}
 
Example 14
Source File: SpecificPageFilterFactory.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;

    // Skip filter if there isn't any selector in the URL
    String selector = slingRequest.getRequestPathInfo().getSelectorString();
    if (selector == null) {
        chain.doFilter(request, response);
        return;
    }

    // Skip filter on AEM author
    WCMMode wcmMode = WCMMode.fromRequest(request);
    if (!WCMMode.DISABLED.equals(wcmMode)) {
        chain.doFilter(request, response);
        return;
    }

    Resource page = slingRequest.getResource();
    LOGGER.debug("Checking sub-pages for {}", slingRequest.getRequestURI());

    Resource subPage = UrlProviderImpl.toSpecificPage(page, selector);
    if (subPage != null) {
        RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(subPage);
        dispatcher.forward(slingRequest, response);
        return;
    }

    chain.doFilter(request, response);
}
 
Example 15
Source File: DefaultServletHttpRequestHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	Assert.state(this.servletContext != null, "No ServletContext set");
	RequestDispatcher rd = this.servletContext.getNamedDispatcher(this.defaultServletName);
	if (rd == null) {
		throw new IllegalStateException("A RequestDispatcher could not be located for the default servlet '" +
				this.defaultServletName + "'");
	}
	rd.forward(request, response);
}
 
Example 16
Source File: AlbumControle.java    From redesocial with MIT License 5 votes vote down vote up
/**
* Altera um álbum no banco de dados
* @param album identificador do álbum a ser alterado
* @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 alterar(Album album, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        AlbumBO bo = new AlbumBO();
        bo.alterar(album);
        
        request.setAttribute("mensagem", "Alterado com sucesso!");
    } catch (Exception ex) {
        request.setAttribute("erro", ex.getMessage());
    }
    
    RequestDispatcher rd = request.getRequestDispatcher("./AlbumControle?operacao=Listar");
    rd.forward(request, response);
}
 
Example 17
Source File: Home.java    From HotelReservationSystem with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String checkInDate = request.getParameter("checkInDate");
    String checkOutDate = request.getParameter("checkOutDate");

    request.setAttribute("checkInDate", checkInDate);
    request.setAttribute("checkOutDate", checkOutDate);

    List<Room> availableRooms = roomFacade.findAll();
    List<Reservation> reservation = reservationFacade.findAll();

    for (int i = 0; i < reservation.size(); i++) {
        if (
                (isDateAfterThan(checkInDate, reservation.get(i).getCheckInDate().toString()) && 
                isDateAfterThan(reservation.get(i).getCheckOutDate().toString(), checkOutDate))
                ||
                (isDateAfterThan(reservation.get(i).getCheckInDate().toString(), checkInDate) && 
                isDateAfterThan(checkOutDate, reservation.get(i).getCheckOutDate().toString()))
                ||
                (isDateAfterThan(checkInDate, reservation.get(i).getCheckInDate().toString()) && 
                isDateAfterThan(checkOutDate, reservation.get(i).getCheckOutDate().toString()))
                ||
                (isDateAfterThan(reservation.get(i).getCheckInDate().toString(), checkInDate) && 
                isDateAfterThan(reservation.get(i).getCheckOutDate().toString(), checkOutDate))
            ) {
            for(int j = 0; j < availableRooms.size(); j++) {
                if(reservation.get(i).getIdRoom() == availableRooms.get(j).getId()) {
                    availableRooms.remove(j);
                    break;
                }
            }
        }
    }

    request.setAttribute("availableRooms", availableRooms);

    RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/views/available_rooms.jsp");
    reqDispatcher.forward(request, response);
}
 
Example 18
Source File: ControleBase.java    From redesocial with MIT License 4 votes vote down vote up
public void mostrar(HttpServletRequest request, HttpServletResponse response, 
        String pagina) throws ServletException, IOException{
    RequestDispatcher rd = request.getRequestDispatcher(pagina);
    rd.forward(request, response);
}
 
Example 19
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    RequestDispatcher rd = req.getRequestDispatcher("/ServletB");
    rd.forward(req, resp);
}
 
Example 20
Source File: JspToHtml.java    From DWSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
public void jspWriteToHtml(String url, String filePath,String fileName) throws Exception {
	HttpServletRequest request = Struts2Utils.getRequest();
	HttpServletResponse response = Struts2Utils.getResponse();
	ServletContext sc = ServletActionContext.getServletContext();
	url = "/my-survey-design!previewDev.action?surveyId=402880ea4675ac62014675ac7b3a0000";
	// 这是生成的html文件名,如index.htm
	filePath = filePath.replace("/", File.separator);
	filePath = filePath.replace("\\", File.separator);
	String fileRealPath = sc.getRealPath("/") + filePath;
	RequestDispatcher rd = sc.getRequestDispatcher(url);
	final ByteArrayOutputStream os = new ByteArrayOutputStream();

	final ServletOutputStream stream = new ServletOutputStream() {
		public void write(byte[] data, int offset, int length) {
			os.write(data, offset, length);
		}

		public void write(int b) throws IOException {
			os.write(b);
		}
	};

	final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,
			"UTF-8"));

	HttpServletResponse rep = new HttpServletResponseWrapper(response) {
		public ServletOutputStream getOutputStream() {
			return stream;
		}

		public PrintWriter getWriter() {
			return pw;
		}
	};

	rd.forward(request, response);
	pw.flush();

	File file2 = new File(fileRealPath);
	if (!file2.exists() || !file2.isDirectory()) {
		file2.mkdirs();
	}
	File file = new File(fileRealPath + fileName);
	if (!file.exists()) {
		file.createNewFile();
	}
	FileOutputStream fos = new FileOutputStream(file);
	os.writeTo(fos);
	fos.close();
}