Example usage for javax.servlet.http HttpServletRequest getAttribute

List of usage examples for javax.servlet.http HttpServletRequest getAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Usage

From source file:com.mycompany.capstone.controllers.ErrorController.java

@RequestMapping(value = "/error")
// #2 - note the use of the Spring Model object rather than a Map
public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
    // #3 - retrieve some useful information from the request
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
    Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
    String exceptionMessage = null;
    exceptionMessage = httpStatus.getReasonPhrase();

    String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
    if (requestUri == null) {
        requestUri = "Unknown";
    }//  ww  w .  j a  v a 2s. com
    // #4 - format the message for the view
    //        String message = MessageFormat.format("{0} returned for {1}: {2}",
    //                statusCode, requestUri, exceptionMessage);

    String message = "Page Content is not Available/ You are not Authorized to access";
    // #5 - put the message in the model object
    model.addAttribute("errorMessage", message);
    return "customError";
}

From source file:cz.muni.fi.myweb1.RestaurantServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String name = request.getAttribute("username").toString();
    String password = request.getAttribute("password").toString();

    /*  /*from   w ww.  j a va  2  s . c o m*/
       response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    out.println("<h1>Text</h1><pre>generated directly from servlet code");
    out.println("serverInfo=" + getServletContext().getServerInfo());
    out.println("parameters: "+ name + " " + password);
       */

    if (loginFacade.login(name, password)) {
        request.getSession().setAttribute("username", name);
        RequestDispatcher rd = request.getRequestDispatcher("/outline.jsp");
        rd.forward(request, response);
    }

    else {
        //TODO error
    }

    /*
     try {
        List<Restaurant> list = myFacade.topRestaurants();
        request.getSession().setAttribute("restList", list);
        RequestDispatcher rd=request.getRequestDispatcher("/outline.jsp");
        rd.forward(request, response);
     } catch (Exception e) {
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
     }
      */
}

From source file:org.jboss.arquillian.warp.extension.spring.container.SpringWarpTestEnricherTestCase.java

/**
 * <p>Sets the {@link SpringMvcResult} on tested object.</p>
 *
 * @param springMvcResult the {@link SpringMvcResult}
 *
 * @throws Exception if any error occurs
 *//*  w  w  w.  ja va 2  s . com*/
private void setSpringMvcResult(SpringMvcResult springMvcResult) throws Exception {

    HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
    when(mockServletRequest.getAttribute(Commons.SPRING_MVC_RESULT_ATTRIBUTE_NAME)).thenReturn(springMvcResult);

    Instance<HttpServletRequest> mockServletRequestInstance = mock(Instance.class);
    TestReflectionHelper.setFieldValue(instance, "servletRequest", mockServletRequestInstance);
    when(mockServletRequestInstance.get()).thenReturn(mockServletRequest);
}

From source file:ru.org.linux.spring.Perf4jHandlerInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    StopWatch stopWatch = (StopWatch) request.getAttribute(ATTRIBUTE);

    if (stopWatch != null) {
        stopWatch.stop();//  www  . j a  v  a2  s.co  m
    }
}

From source file:istata.web.HtmlController.java

@RequestMapping(value = { "/help **", "/help **/**" })
public String help(HttpServletRequest request, Map<String, Object> model) {

    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    stataService.saveCmd(path);//w w w.  j av  a2 s . c o  m

    path = path.substring(6);

    return "redirect:http://www.stata.com/help.cgi?" + path;
}

From source file:com.iflytek.edu.cloud.frame.error.support.ErrorRequestMessageConverter.java

/**
 * ??format?// www.j  av  a  2  s. c  o m
 * 
 * @param httpServletResponse
 * @param format
 * @param mainError
 * @throws IOException
 */
public void convertData(HttpServletRequest request, HttpServletResponse httpServletResponse,
        MainError mainError) throws IOException {
    final String format = (String) request.getAttribute(Constants.SYS_PARAM_KEY_FORMAT);

    if (Constants.DATA_FORMAT_JSON.equals(format)) {
        jsonMessageConverter.write(mainError, MediaType.valueOf("application/json;charset=UTF-8"),
                new ServletServerHttpResponse(httpServletResponse));
    } else {
        xmlMessageConverter.write(mainError, MediaType.valueOf("application/xml;charset=UTF-8"),
                new ServletServerHttpResponse(httpServletResponse));
    }
}

From source file:com.marklogic.samplestack.web.security.SamplestackSecurityFilters.java

@Override
/**//  w w w.j a v a 2 s .c  om
 * Hooks into Spring Security filter mechanism to manipulate
 * headers as needed.
 */
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
    if (token != null) {
        response.setHeader("X-CSRF-HEADER", token.getHeaderName());
        response.setHeader("X-CSRF-PARAM", token.getParameterName());
        response.setHeader(token.getHeaderName(), token.getToken());
    }
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
    filterChain.doFilter(request, response);

}

From source file:org.jnap.core.mvc.bind.AtmosphereResourceArgumentResolver.java

protected AtmosphereResource getAtmosphereResource(NativeWebRequest webRequest, boolean session) {
    HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
    AtmosphereResource resource = null;//from www  . ja  v  a  2 s  .  c  o  m

    if (session) {
        if ((Boolean) req.getAttribute(FrameworkConfig.SUPPORT_SESSION)) {
            //            resource = (AtmosphereResource) req.getSession().getAttribute(AtmosphereFilter.SUSPENDED_RESOURCE); TODO check
        }
    }

    if (resource == null) {
        resource = (AtmosphereResource) req.getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE);
    }

    return resource;
}

From source file:org.tec.webapp.web.ErrorServlet.java

/**
 * process the error//from w  w w  . j a  va 2s  .  c om
 * @param request the request instance
 * @param response the response instance
 * @throws IOException if processing fails
 */
protected void processError(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
    Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    String requestUri = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);

    LOGGER.error("failed to process " + requestUri + " error code: " + statusCode);

    WebError we;
    if (throwable != null) {
        LOGGER.error("error", throwable);
        we = new WebError(throwable.getMessage(), ErrorCodes.UNRESOLVEABLE_ERROR);
    } else {
        we = new WebError("error", ErrorCodes.UNRESOLVEABLE_ERROR);
    }

    PrintWriter pw = null;
    try {
        response.setStatus(statusCode != null ? statusCode : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
        pw = response.getWriter();
        pw.write(we.toJSON());
        pw.flush();
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}

From source file:org.cloudifysource.rest.command.CommandManager.java

/**
 * Constructor takes as input the entire commands URI, held in the request
 * and the root object from which to begin invocation.
 * @param request - the commands request 
 * @param root - the root command's object
 *//*from  www  .  java2  s.  co m*/
public CommandManager(HttpServletRequest request, Object root) {
    final String prefix = "/admin/";
    String executionPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    if (executionPath.endsWith("/")) {
        executionPath = executionPath.substring(0, executionPath.length() - 1);
    }
    if (!executionPath.startsWith(prefix)) {
        throw new IllegalArgumentException("Bad request URL " + request.getRequestURL());
    }
    String restUrl = "http://" + request.getLocalAddr() + ":" + request.getLocalPort()
            + request.getContextPath();
    this.commandURL = restUrl + executionPath;
    initilizeCommandList(executionPath.substring(prefix.length()), root);
}