Example usage for javax.servlet.http HttpServletRequest getServletPath

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

Introduction

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

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:architecture.ee.web.community.spring.controller.SocialConnectController.java

/**
 * Returns a RedirectView with the URL to redirect to after a connection is
 * created or deleted. Defaults to "/connect/{providerId}" relative to
 * DispatcherServlet's path. May be overridden to handle custom redirection
 * needs.//from   w  ww .ja v a2s.c om
 * 
 * @param providerId
 *            the ID of the provider for which a connection was created or
 *            deleted.
 * @param request
 *            the NativeWebRequest used to access the servlet path when
 *            constructing the redirect path.
 */
protected RedirectView connectionStatusRedirect(String providerId, NativeWebRequest request) {
    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    String path = "/connect/" + providerId + getPathExtension(servletRequest);
    if (prependServletPath(servletRequest)) {
        path = servletRequest.getServletPath() + path;
    }
    log.debug(path);
    request.getNativeResponse(HttpServletResponse.class).setContentType("text/html;charset=UTF-8");
    return new RedirectView(path, true);
}

From source file:io.seldon.api.interceptor.GenericScopedInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    final String requestURI = request.getRequestURI();
    if (logger.isDebugEnabled())
        logger.debug("Scoped interceptor for: " + requestURI);
    Date start = new Date();
    request.setAttribute("startTime", start);
    try {//  w  w w  . j a v a2 s. c om
        final ConsumerBean consumerBean = authorise(request);
        final HttpSession session = request.getSession();
        session.setAttribute("consumer", consumerBean);
        return super.preHandle(request, response, handler);
    } catch (APIException e) {
        exceptionResponse(request, response, e);
        String apiKey = request.getServletPath().replaceAll("/", "\\."); //Asumes no user/item ids in path!!!!
        ApiLogger.log(apiKey, start, request, null);
    } catch (Throwable t) {
        logger.error("GenericScopedInterceptor#preHandle: " + t.getMessage(), t);
    }
    return false;
}

From source file:MyServlet.UserController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  ww  w. ja  v a2s .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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    String url = "/main.jsp";
    Object message;
    action = request.getServletPath();
    PrintWriter writer = response.getWriter();
    String formName = request.getParameter("formname");
    HttpSession session = request.getSession();
    writer.println("formName  :" + formName);
    System.out.println("Inside post user");
    if (formName.equals("create")) {
        String hosturl = request.getRequestURL().toString();
        String baseURL = hosturl.substring(0, hosturl.length() - request.getRequestURI().length())
                + request.getContextPath() + "/";
        System.out.println("hosturl" + hosturl);
        System.out.println("baseURL" + baseURL);
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String cpass = request.getParameter("cpass");
        String token = request.getParameter("token");

        User user = new User();
        user.setName(name);
        user.setEmail(email);
        request.setAttribute("user", user);
        if (password.equals(cpass)) {
            if (userDB.getUser(email) == null) {
                if (token != null) {
                    int recomCoins;
                    User userRecom, newUser;
                    userRecom = UserDB.activateUser(token);
                    if (userRecom != null) {
                        newUser = UserDB.getUser(userRecom.getEmail());
                        recomCoins = newUser.getCoins();
                        newUser.setCoins(recomCoins + 2);
                        UserDB.update(newUser);
                        UserDB.deleteTemp(token);
                    }

                }
                UUID uId = UUID.randomUUID();
                System.out.println("UUID One: " + uId);
                //session.setAttribute("theUser", user);
                userPassword.put(email, password);
                userDB.tempUser(user, uId);
                /*
                userDB.addUser(user,password);
                userDB.addUser(user);*/
                String to = email;
                String from = email;
                String subject = "Activation Link";

                String body = baseURL + "user?action=activation&activationcode=" + uId;
                boolean bodyIsHTML = false;
                try {
                    MailUtilLocal.sendMail(to, from, subject, body, bodyIsHTML);
                    System.out.println("mail sent");
                    message = "Activation link sent to your email account";
                    request.setAttribute("message", message);
                    url = "/login.jsp";
                } catch (MessagingException e) {
                    String errorMessage = "ERROR: Unable to send email." + "ERROR MESSAGE:" + e.getMessage();
                    System.out.println(errorMessage);
                    request.setAttribute("errorMessage", errorMessage);
                    url = "/contact.jsp";
                }

            } else {
                message = "Email address already exist!!";
                request.setAttribute("message", message);
                url = "/signup.jsp";
            }

        } else {
            writer.println("Error");
            message = "Confirm Password doesnot match";
            request.setAttribute("message", message);
            url = "/signup.jsp";
        }

    } else if (formName.equals("login")) {

        User userLogin;
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        writer.println("inside login" + userPassword.get(email));
        userLogin = userDB.getUser(email);
        if (userLogin == null) {
            writer.println("no user");
            message = "Not found email address : " + email;
            request.setAttribute("message", message);
            url = "/login.jsp";

        } else {
            writer.println("inside else");
            try {
                String salt = UserDB.getSalt(email);
                if (salt != null) {
                    password = hashPassword(password + salt);
                    if (userDB.validateUser(email, password)) {
                        if (session.getAttribute("theUser") != null) {
                            session.invalidate();
                        }
                        session = request.getSession();
                        session.setAttribute("theUser", userLogin);

                        url = "/main.jsp";
                    } else {
                        message = "Password is incorrect!!";
                        request.setAttribute("message", message);
                        url = "/login.jsp";

                    }
                }
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    } else if (formName.equals("forgetpassword")) {
        String name = "name";
        String email = request.getParameter("email");
        System.out.println("email" + email);
        if (userDB.getUser(email) != null) {
            UUID uId = UUID.randomUUID();
            System.out.println("UUID One: " + uId);
            //session.setAttribute("theUser", user);
            String to = email;
            String from = email;
            String subject = "Password Reset Link";
            String hosturl = request.getRequestURL().toString();
            String baseURL = hosturl.substring(0, hosturl.length() - request.getRequestURI().length())
                    + request.getContextPath() + "/";

            String body = baseURL + "user?action=resetpassword&token=" + uId;
            boolean bodyIsHTML = false;
            try {
                User user = new User();
                user.setName(name);
                user.setEmail(email);
                userDB.tempUser(user, uId);
                MailUtilLocal.sendMail(to, from, subject, body, bodyIsHTML);
                System.out.println("mail sent");
                message = "Please check your email account";
                request.setAttribute("message", message);
                url = "/login.jsp";
            } catch (MessagingException e) {
                String errorMessage = "ERROR: Unable to send email." + "ERROR MESSAGE:" + e.getMessage();
                System.out.println(errorMessage);
                request.setAttribute("errorMessage", errorMessage);
                url = "/contact.jsp";
            }
        }
    } else if (formName.equals("resetpassword")) {
        try {
            String currentTime = sdf.format(dt);
            String password = request.getParameter("password");
            String cpass = request.getParameter("cpass");
            String email = request.getParameter("email");
            String token = request.getParameter("token");
            String expiryTime = UserDB.getTime(token);
            Date date1 = sdf.parse(expiryTime);
            Date date2 = sdf.parse(currentTime);
            long differenceInMillis = date2.getTime() - date1.getTime();
            if (differenceInMillis < 3600000) {
                User user = new User();
                user.setEmail(email);
                if (password.equals(cpass)) {
                    try {
                        password = hashAndSalt(password);
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    UserDB.updatePassword(user, password, salt);
                    UserDB.deleteTempEmail(email);
                    url = "/login.jsp";
                } else {

                    request.setAttribute("user", user);
                    request.setAttribute("userResetToken", token);
                    url = "/resetpassword.jsp";
                }
            } else {
                message = "Token is expired!!";
                request.setAttribute("message", message);
                url = "/signup.jsp";
            }
            //url="/login.jsp";
        } catch (ParseException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    getServletContext().getRequestDispatcher(url).forward(request, response);
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String servletPath = (String) request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
    String pathInfo = null;/* w  w w  .  j  a  v a 2 s . com*/
    if (servletPath == null) {
        servletPath = request.getServletPath();
        pathInfo = request.getPathInfo();
    } else
        pathInfo = (String) request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);

    String pathInContext = URI.addPaths(servletPath, pathInfo);

    boolean endsWithSlash = pathInContext.endsWith("/");
    Resource resource = getResource(pathInContext);

    // Is the method allowed?
    String method = request.getMethod();
    if (_AllowString.indexOf(method) < 0) {
        if (resource != null && resource.exists()) {
            response.setHeader(HttpFields.__Allow, _AllowString);
            response.sendError(HttpResponse.__405_Method_Not_Allowed);
        } else
            response.sendError(HttpResponse.__404_Not_Found);
        return;
    }

    // Handle the request
    try {
        // handle by method.
        if (method.equals(HttpRequest.__GET) || method.equals(HttpRequest.__POST)
                || method.equals(HttpRequest.__HEAD))
            handleGet(request, response, pathInContext, resource, endsWithSlash);
        else if (_putAllowed && method.equals(HttpRequest.__PUT))
            handlePut(request, response, pathInContext, resource);
        else if (_delAllowed && method.equals(HttpRequest.__DELETE))
            handleDelete(request, response, pathInContext, resource);
        else if (_putAllowed && _delAllowed && method.equals(HttpRequest.__MOVE))
            handleMove(request, response, pathInContext, resource);
        else if (method.equals(HttpRequest.__OPTIONS))
            handleOptions(request, response);
        else if (method.equals(HttpRequest.__TRACE))
            _servletHandler.handleTrace(request, response);
        else {
            // anything else...
            try {
                if (resource.exists())
                    response.sendError(HttpResponse.__501_Not_Implemented);
                else
                    _servletHandler.notFound(request, response);
            } catch (Exception e) {
                LogSupport.ignore(log, e);
            }
        }
    } catch (IllegalArgumentException e) {
        LogSupport.ignore(log, e);
    } finally {
        if (resource != null && !(resource instanceof CachedResource))
            resource.release();
    }

}

From source file:net.sf.ginp.GinpServlet.java

/**
 * Deliver the view that the controller has selected.  Do this in
 * a way that the page is not cached.  Also works around a bug in
 * Session URL Encdoing in Tomcat//w w w .j a  v  a2s  .c  om
 * @param req  The Servlet Request
 * @param res  The Servlet response
 * @param url The URL To send to
 * @throws IOException if there is an error retrieving or
 * sending the page
 * @throws ServletException if there is some other error
 */
private void forwardToPage(final HttpServletRequest req, final HttpServletResponse res, String url)
        throws IOException, ServletException {
    Random rnd = new Random();

    // Add no cache random number
    if (url.indexOf("?") == -1) {
        url = res.encodeRedirectURL(url + "?nocache=" + rnd.nextInt(999999999));
    } else {
        // Pass the parameters throught the urlEncodeParameters method
        url = res.encodeRedirectURL(url + "&nocache=" + rnd.nextInt(999999999));
    }

    // Add the Path
    if (!url.startsWith("/")) {
        String serPath = req.getServletPath();
        url = serPath.substring(0, serPath.lastIndexOf("/")) + "/" + url;
    }

    // if ;jsessionid= then cookies not used so it is safer to redirect
    // than forward, due to a bug (or spec requirement) in Tomcat 4
    if (url.indexOf(";jsessionid=") != -1) {
        // debug to log
        if (log.isDebugEnabled()) {
            log.debug("redirect to new page url=" + url);
        }

        // redirect to new page
        res.sendRedirect(url);
    } else {
        // debug to log
        if (log.isDebugEnabled()) {
            log.debug("forward to new page url=" + url);
        }

        getServletConfig().getServletContext().getRequestDispatcher(url).forward(req, res);
    }
}

From source file:eionet.cr.web.filters.HomespaceUrlFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    // Pass on if not a HTTP request.
    if (!(servletRequest instanceof HttpServletRequest)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;//from   ww  w  .  jav  a2  s .  c o m
    }

    // Instantiate local variables for HTTP request, response and request-URL
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    String requestURL = httpRequest.getRequestURL().toString();

    boolean isProjectFolder = FolderUtil.isProjectFolder(requestURL);

    String contextPath = httpRequest.getContextPath();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("httpRequest.getRequestURL() = " + requestURL);
        LOGGER.trace("httpRequest.getRequestURI() = " + httpRequest.getRequestURI());
        LOGGER.trace("httpRequest.getContextPath() = " + contextPath);
        LOGGER.trace("httpRequest.getServletPath() = " + httpRequest.getServletPath());
        LOGGER.trace("httpRequest.getPathInfo() = " + httpRequest.getPathInfo());
    }

    // Parse path info if it is not null and its length is greater than 1
    // (because if its equal to 1, then it is "/", meaning the application's root URI).
    String pathInfo = httpRequest.getPathInfo();
    if (pathInfo != null && pathInfo.length() > 1) {

        int i = pathInfo.indexOf('/', 1);
        if (i != -1 && pathInfo.length() > (i + 1)) {

            try {
                // Prepare the default redirect location.
                String queryString = "?uri=" + URLEncoder.encode(requestURL, "UTF-8");
                String redirectLocation = contextPath + Util.getUrlBinding(ExportTriplesActionBean.class)
                        + queryString;

                // Override the prepared redirect location in the below special cases.
                if (DAOFactory.get().getDao(HelperDAO.class).isTabularDataSubject(requestURL)) {
                    // The requested URL is a subject in tabular data (i.e. CSV or TSV) file.
                    redirectLocation = contextPath + TabularDataServlet.URL_PATTERN + queryString;
                    LOGGER.debug("URL points to tabular data subject, redirecting to: " + redirectLocation);
                    // if project file, do not check the filestore in ordinary way
                } else if (isStoredFile(pathInfo, isProjectFolder) && !isRdfXmlPreferred(httpRequest)) {
                    // The requested URL is a stored file, and requester wants original copy (i.e. not triples)
                    redirectLocation = contextPath + DownloadServlet.URL_PATTERN + queryString;
                    LOGGER.debug("URL points to stored file, redirecting to: " + redirectLocation);
                } else if (isSparqlBookmark(pathInfo)) {
                    if (isRdfXmlPreferred(httpRequest)) {
                        redirectLocation = contextPath + Util.getUrlBinding(ExportTriplesActionBean.class)
                                + queryString + "&exportProperties=";
                    } else {
                        redirectLocation = contextPath + Util.getUrlBinding(ViewActionBean.class) + queryString;
                    }
                }

                // Redirect to the location resolved above.
                httpResponse.sendRedirect(redirectLocation);
                return;
            } catch (DAOException e) {
                throw new ServletException(e.getMessage(), e);
            }
        }
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

protected void debugRequest(HttpServletRequest request) {
    /*     see values with just a plain old request object being sent through */
    logger.debug("request RequestURL: " + request.getRequestURL());
    logger.debug("request RequestURI: " + request.getRequestURI());
    logger.debug("request PathInfo: " + request.getPathInfo());
    logger.debug("request PathTranslated: " + request.getPathTranslated());
    logger.debug("request QueryString: " + request.getQueryString());
    logger.debug("request ContextPath: " + request.getContextPath());
    logger.debug("request ServletPath: " + request.getServletPath());
    logger.debug("request toString:" + request.toString());
    Enumeration<String> attributeNames = request.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String attributeName = attributeNames.nextElement();
        logger.debug("request " + attributeName + ": " + request.getAttribute(attributeName));
    }/*from  ww w  .j  a va2 s  .  c  o  m*/
    /*      values of proxyServletWrapper request object to be sent through */
    logger.info("");

    /*      uncomment to see what the parameters of servlet passed in are  */
    Map<String, String[]> parameterMap = request.getParameterMap();

    for (Object key : parameterMap.keySet()) {
        String[] values = parameterMap.get((String) key);
        for (int i = 0; i < values.length; ++i) {
            logger.info("request ParameterMap: " + (String) key + " = " + values[i]);
        }

    }
    logger.debug("");

}

From source file:org.slc.sli.dashboard.web.interceptor.SessionCheckInterceptor.java

/**
 * Prehandle performs a session check on all incoming requests to ensure a user with an active spring security session,
 *  is still authenticated against the api.
 *///w ww.j a v  a2 s.c  o m
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = SecurityUtil.getToken();

    JsonObject json = restClient.sessionCheck(token);

    // If the user is not authenticated, expire the cookie and set oauth_token to null
    if (!json.get(Constants.ATTR_AUTHENTICATED).getAsBoolean()) {
        SecurityContextHolder.getContext().setAuthentication(null);
        HttpSession session = request.getSession();
        session.setAttribute(SLIAuthenticationEntryPoint.OAUTH_TOKEN, null);
        for (Cookie c : request.getCookies()) {
            if (c.getName().equals(SLIAuthenticationEntryPoint.DASHBOARD_COOKIE)) {
                c.setMaxAge(0);
            }
        }

        // Only redirect if not error page
        if (!(request.getServletPath().equalsIgnoreCase(ErrorController.EXCEPTION_URL)
                || request.getServletPath().equalsIgnoreCase(ErrorController.TEST_EXCEPTION_URL))) {
            response.sendRedirect(request.getRequestURI());
            return false;
        }
    }

    return true;
}

From source file:net.openkoncept.vroom.VroomController.java

/**
 * <p> This method analyzes the request and delegate control to other
 * methods for processing. </p>/*from  w w  w. j  ava 2s . com*/
 *
 * @param request - HttpServletRequest
 * @param response - HttpServletResponse
 * @throws ServletException - ServletException
 * @throws IOException - IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String contextPath = request.getContextPath();
    String servletPath = request.getServletPath();
    String sessionId = request.getSession().getId();
    String requestPath = contextPath + servletPath + ";" + SESSION_ID + "=" + sessionId;
    String uri = request.getParameter(GENERATE_URI);
    String rt = request.getParameter(RT);
    String method = request.getParameter(METHOD);

    List parts = null;
    Map paramMap = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        paramMap = new HashMap();
        DiskFileItemFactory factory = new DiskFileItemFactory(fileUploadSizeThreshold, fileUploadTempFolder);
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
            parts = sfu.parseRequest(request);
            Iterator iter = parts.iterator();
            while (iter.hasNext()) {
                FileItem fi = (FileItem) iter.next();
                //                    if(fi.isFormField()) {
                //                        List l = (List) paramMap.get(fi.getFieldName());
                //                        if(l == null) {
                //                            l = new ArrayList();
                //                            paramMap.put(fi.getFieldName(), l);
                //                        }
                //                        l.add(fi.getString());
                //                    } else {
                //                        paramMap.put(fi.getFieldName(), fi);
                //                    }
                List l = (List) paramMap.get(fi.getFieldName());
                if (l == null) {
                    l = new ArrayList();
                    paramMap.put(fi.getFieldName(), l);
                }
                if (fi.isFormField()) {
                    l.add(fi.getString());
                } else {
                    l.add(fi);
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException("Unable to part multipart/form-data", e);
        }
        if (parts != null) {
            rt = (String) ((ArrayList) paramMap.get(RT)).get(0);
            method = (String) ((ArrayList) paramMap.get(METHOD)).get(0);
        }
    }

    if (RT_JS.equals(rt)) {
        if (METHOD_FILE.equals(method)) {
            processRequestJSFile(request, response, contextPath, servletPath, sessionId, requestPath);
        } else if (METHOD_GENERATE.equals(method)) {
            processRequestJSGenerate(request, response, contextPath, servletPath, sessionId, uri);
        }
    } else if (RT_INVOKE.equals(rt)) {
        processRequestInvoke(request, response);
    } else if (RT_SUBMIT.equals(rt)) {
        processRequestSubmit(request, response, paramMap);
    }
}