Java Code Examples for javax.servlet.http.HttpServletRequest#getContextPath()

The following examples show how to use javax.servlet.http.HttpServletRequest#getContextPath() . 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: SaleStockServlet.java    From Stock-Trading-System with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=GBK");
	PrintWriter out = response.getWriter();
	HttpSession session = request.getSession();
	String pathadd = request.getContextPath();
	String userid = ((UserInfoBean) session.getAttribute("user"))
			.getUserid();
	String stockId = request.getParameter("stockid");
	String tradeNumber = request.getParameter("tradeNumber");
	String tradePrice = request.getParameter("tradePrice");
	StockTradeModel stm = new StockTradeModel();
	int n = 0;
	try {
		n = stm.saleStock(userid, stockId, tradePrice, tradeNumber);
	} catch (SQLException e) {
		e.printStackTrace();
	}
	if (n == 0)
		out.print("<script>alert('�µ�ʧ�ܣ�');location.href='" + pathadd
				+ "/servlet/MainServlet';</script>");
	else
		out.print("<script>alert('�µ��ɹ���');location.href='" + pathadd
				+ "/servlet/MainServlet';</script>");
}
 
Example 2
Source File: StringUtil.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * getSystemUrl:(获取访问服务器的端口号IP)
 * http://localhost:8081/lcApp 或者http://localhost:8081/lcApp
 *
 * @param request
 * @param isHttps 是否https 链接
 * @return
 * @author rufei.cn
 */
public static String getSystemUrl(HttpServletRequest request) {
    // 用于获取服务器IP 端口号 项目名
    int localPort = request.getServerPort();
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    logger.info("ip/domname:" + scheme + "://" + serverName + ":" + localPort + request.getContextPath());
    String url = "";
    if (localPort == 80) {
        url = scheme + "://" + serverName + request.getContextPath();
    } else {
        url = scheme + "://" + serverName + ":" + localPort
                + request.getContextPath();
    }
    return url;
}
 
Example 3
Source File: JaxrsODataService.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("{id:.*}")
public Response service(@Context HttpServletRequest req, @Context HttpServletResponse resp) {

    String requestMapping = req.getContextPath() + req.getServletPath() + "/DemoService.svc";
    req.setAttribute("requestMapping", requestMapping);
    // create odata handler and configure it with EdmProvider and Processor
    OData odata = OData.newInstance();
    ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(),
                                                      new ArrayList<EdmxReference>());
    ODataHttpHandler handler = odata.createHandler(edm);
    handler.register(new DemoEntityCollectionProcessor());

    // let the handler do the work
    handler.process(req, resp);
    return Response.ok().build();
}
 
Example 4
Source File: ApiAction.java    From swagger with Apache License 2.0 6 votes vote down vote up
private Properties loadSettings(HttpServletRequest request) throws IOException {
    Properties props = new Properties();
    InputStream is = ResourceUtil.getResourceAsStream("swagger.properties");
    props.load(is);
    String path = request.getContextPath();
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    props.setProperty("apiHost", host);
    String apiFile = props.getProperty("apiFile");
    if (StringUtils.isBlank(apiFile)) {
        apiFile = DEFAULT_API_FILE;
    }
    String apiFilePath = request.getServletContext().getRealPath(apiFile);
    props.setProperty("apiFile", apiFilePath);
    if (StringUtils.isBlank(props.getProperty("devMode"))) {
        props.setProperty("devMode", devMode);
    }
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    props.put("suffix", suffix);
    return props;
}
 
Example 5
Source File: HomeController.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@RequestMapping(value = "/mobile/{page}")
public String mobileLogin(@PathVariable("page") String page, 
						  HttpServletRequest request,
						  ModelMap model)
           throws Exception {
	//System.out.println("mobileLogin");
	HttpSession session = request.getSession(false);
	String contextPath = request.getContextPath();
	
	if (page.equalsIgnoreCase("mLogin")) {

		if(session != null && contextPath.equals("/mobile")) {
			GroupAuthorization requestAuth = (GroupAuthorization) session.getAttribute("requestAuth");
			if(requestAuth != null) {
				return "redirect:" + HeritProperties.getProperty("Globals.mMainPage") +".do";
			} 
		}
		return "/mobile/mLogin";
	} else {
		return "/mobile/"+page;			
	}		
   }
 
Example 6
Source File: ShopLoginInterceptor.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
 * 主要做事前拦截,即用户操作前执行,改写preHandler里的逻辑,进行用户操作权限的拦截
 * 
 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(HttpServletRequest,
 *      HttpServletResponse, Object)
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
	System.out.println(">>>ShopLoginInterceptor>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
	// 从session中获取用户信息
	Object userObj = request.getSession().getAttribute("user");
	// 如果用户信息存在
	if (userObj != null) {
		// 将session中的用户信息转换为PersonInfo实体类对象
		PersonInfo user = (PersonInfo) userObj;
		// 用户存在且可用,并且用户类型为店家或者管理员
		if (user != null && user.getUserId() != null && user.getUserId() > 0
				&& user.getEnableStatus().equals(EnableStatusEnum.AVAILABLE.getState())
				&& (user.getUserType().equals(PersonInfoTypeEnum.OWNER.getState())
						|| user.getUserType().equals(PersonInfoTypeEnum.ADMIN.getState()))) {
			// 如果通过验证,则返回true,用户正常执行后续操作
			return true;
		}
	}
	// 不满足登录条件,则直接跳转后台用户登录页面
	String loginUrl = request.getContextPath() + "/admin/login?userType=back";
	response.sendRedirect(loginUrl);
	return false;
}
 
Example 7
Source File: S2gUtil.java    From s2g-zuul with MIT License 6 votes vote down vote up
public static String getServerletUrl(HttpServletRequest request) {
	//String url= request.getServletPath();
    String uri = request.getRequestURI();
    String contextPath = request.getContextPath();
    if (StringUtils.length(contextPath) > 0) {
        uri = StringUtils.substring(uri, contextPath.length());
    }
    if(StringUtils.length(uri) > 0){
    	uri=uri.substring(1, StringUtils.length(uri));
    }
    String query= request.getQueryString();	
	if(!StringUtils.isEmpty(query)){
		uri+="?"+query;
	}
	return uri;
}
 
Example 8
Source File: WikiAccessServlet.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Make a redirect to the login url.
 * 
 * @param req
 *        HttpServletRequest object with the client request.
 * @param res
 *        HttpServletResponse object back to the client.
 * @param path
 *        The current request path, set ONLY if we want this to be where to redirect the user after successfull login
 * @throws IOException 
 */
protected void doLogin(HttpServletRequest req, HttpServletResponse res, String path) throws ToolException, IOException
{
	// if basic auth is valid do that
	if ( basicAuth.doAuth(req,res) ) {
		//log.info("BASIC Auth Request Sent to the Browser ");
		return;
	} 
	
	
	// get the Sakai session
	Session session = SessionManager.getCurrentSession();

	// set the return path for after login if needed (Note: in session, not tool session, special for Login helper)
	if (path != null)
	{
		// where to go after
		String returnPath  = Web.returnUrl(req, Validator.escapeUrl(path));
		session.setAttribute(Tool.HELPER_DONE_URL, returnPath );
	}

	// check that we have a return path set; might have been done earlier
	if (session.getAttribute(Tool.HELPER_DONE_URL) == null)
	{
		log.error("doLogin - proceeding with null HELPER_DONE_URL");
	}

	// map the request to the helper, leaving the path after ".../options" for the helper
	ActiveTool tool = ActiveToolManager.getActiveTool("sakai.login");
	String context = req.getContextPath() + req.getServletPath() + "/login";
	tool.help(req, res, context, "/login");
}
 
Example 9
Source File: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Propfind helper method.
 *
 * @param req The servlet request
 * @param generatedXML XML response to the Propfind request
 * @param path Path of the current resource
 * @param type Propfind type
 * @param propertiesVector If the propfind type is find properties by
 * name, then this Vector contains those properties
 */
private void parseProperties(HttpServletRequest req,
                             XMLWriter generatedXML,
                             String path, int type,
                             Vector<String> propertiesVector) {

    // Exclude any resource in the /WEB-INF and /META-INF subdirectories
    if (isSpecialPath(path))
        return;

    WebResource resource = resources.getResource(path);
    if (!resource.exists()) {
        // File is in directory listing but doesn't appear to exist
        // Broken symlink or odd permission settings?
        return;
    }

    String href = req.getContextPath() + req.getServletPath();
    if ((href.endsWith("/")) && (path.startsWith("/")))
        href += path.substring(1);
    else
        href += path;
    if (resource.isDirectory() && (!href.endsWith("/")))
        href += "/";

    String rewrittenUrl = rewriteUrl(href);

    generatePropFindResponse(generatedXML, rewrittenUrl, path, type, propertiesVector,
            resource.isFile(), false, resource.getCreation(), resource.getLastModified(),
            resource.getContentLength(), getServletContext().getMimeType(resource.getName()),
            resource.getETag());
}
 
Example 10
Source File: SecurityServlet.java    From quartz-web with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected boolean hasPermission(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 项目根路径
    String contextPath = request.getContextPath();
    // servlet访问路径
    String servletPath = request.getServletPath();
    // 设置编码
    response.setCharacterEncoding("utf-8");
    // 根目录为空的情况为,root context
    if (contextPath == null) {
        contextPath = "";
    }
    String uri = contextPath + servletPath;
    if (isRequireAuth() //
            && !containsUser(request)//
            && !checkLoginParam(request)//
            && !("/login.html".equals(path) //
            || path.startsWith("/css")//
            || path.startsWith("/js") //
            || path.startsWith("/img"))) {
        if (contextPath.equals("") || contextPath.equals("/")) {
            response.sendRedirect(servletPath + "/login.html");
        } else {
            if (uri.endsWith("/")) {
                response.sendRedirect(uri + "login.html");
            } else {
                response.sendRedirect(uri + "/login.html");
            }
        }
        return false;

    }
    return true;
}
 
Example 11
Source File: HostedSiteServlet.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	traceRequest(req);
	String pathInfoString = req.getPathInfo();
	IPath pathInfo = new Path(null /*don't parse host:port as device*/, pathInfoString == null ? "" : pathInfoString); //$NON-NLS-1$
	if (pathInfo.segmentCount() > 0) {
		String hostedHost = pathInfo.segment(0);
		IHostedSite site = HostingActivator.getDefault().getHostingService().get(hostedHost);
		if (site != null) {
			IPath path = pathInfo.removeFirstSegments(1);
			IPath contextPath = new Path(req.getContextPath());
			IPath contextlessPath = path.makeRelativeTo(contextPath).makeAbsolute();
			URI[] mappedPaths;
			try {
				mappedPaths = getMapped(site, contextlessPath, req.getQueryString());
			} catch (URISyntaxException e) {
				String message = "Could not create target URI";
				logger.error(message, e);
				handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, message, e));
				return;
			}
			if (mappedPaths != null) {
				serve(req, resp, site, mappedPaths);
			} else {
				handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("No mappings matched {0}", path), null));
			}
		} else {
			resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
			String msg = NLS.bind("Hosted site {0} is stopped", hostedHost);
			handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
		}
	} else {
		super.doGet(req, resp);
	}
}
 
Example 12
Source File: RemoteValidateHandler.java    From validator-web with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    
    String content = null;
    
    String scriptName = super.generateJavaScript(request.getContextPath(),
            request.getServletPath(), request.getPathInfo(), getLocale(request));
    
    if (scriptName != null) {
        try {
            boolean result = validateSingleConstraint(request, scriptName);
            content = String.valueOf(result);
        } catch (NoFoundException e) {
            // send 404
        }
    }
    
    if (content != null) {
        response.setContentType(getContentType());
        PrintWriter out = response.getWriter();
        out.write(content);
        out.flush();
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}
 
Example 13
Source File: SiteResetHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res,
		Session session) throws PortalHandlerException
{
	if ((parts.length > 2) && (parts[1].equals(SiteResetHandler.URL_FRAGMENT)))
	{
		try
		{
			String siteUrl = req.getContextPath() + "/site"
					+ Web.makePath(parts, 2, parts.length);
			// Make sure to add the parameters such as panel=Main
			String queryString = Validator.generateQueryString(req);
			if (queryString != null)
			{
				siteUrl = siteUrl + "?" + queryString;
			}
			portalService.setResetState("true");
			res.sendRedirect(siteUrl);
			return RESET_DONE;
		}
		catch (Exception ex)
		{
			throw new PortalHandlerException(ex);
		}
	}
	else
	{
		return NEXT;
	}
}
 
Example 14
Source File: JettyHandler.java    From cougar with Apache License 2.0 5 votes vote down vote up
/**
 * getContextPath and getContextPath are defined in terms of servlets which we bypass completely.
 * we may need to amend this implementation
       *
 * @param request
 * @return
 */
      private final void buildPathInfo(final HttpServletRequest request) {
          fullPath = request.getContextPath() + (request.getPathInfo() ==  null ? "" : request.getPathInfo());

          // Strip the binding protocolBindingRoot off the front.
          if (protocolBindingRoot != null && protocolBindingRoot.length() > 0) {
              operationPath =  fullPath.substring(protocolBindingRoot.length());
          } else {
              operationPath =  fullPath;
          }
}
 
Example 15
Source File: BaseController.java    From Juice with GNU General Public License v3.0 5 votes vote down vote up
protected String getReqUrl() {
    HttpServletRequest request = getRequest();

    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    String path = requestURI.substring(contextPath.length());

    return path;
}
 
Example 16
Source File: ServletRequestUtils.java    From knox with Apache License 2.0 4 votes vote down vote up
public static String getContextPathWithQuery(HttpServletRequest httpServletRequest) {
  return httpServletRequest.getContextPath() + getRequestPathWithQuery(httpServletRequest);
}
 
Example 17
Source File: UploadUtils.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
 * 上传验证,并初始化文件目录
 * 
 * @param request
 */
private String validateFields(HttpServletRequest request) {
	String errorInfo = "true";
	// boolean errorFlag = true;
	// 获取内容类型
	String contentType = request.getContentType();
	int contentLength = request.getContentLength();
	// 文件保存目录路径
	savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/";
	// 文件保存目录URL
	saveUrl = request.getContextPath() + "/" + basePath + "/";
	File uploadDir = new File(savePath);
	if (contentType == null || !contentType.startsWith("multipart")) {
		// TODO
		System.out.println("请求不包含multipart/form-data流");
		errorInfo = "请求不包含multipart/form-data流";
	} else if (maxSize < contentLength) {
		// TODO
		System.out.println("上传文件大小超出文件最大大小");
		errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]";
	} else if (!ServletFileUpload.isMultipartContent(request)) {
		// TODO
		errorInfo = "请选择文件";
	} else if (!uploadDir.isDirectory()) {// 检查目录
		// TODO
		errorInfo = "上传目录[" + savePath + "]不存在";
	} else if (!uploadDir.canWrite()) {
		// TODO
		errorInfo = "上传目录[" + savePath + "]没有写权限";
	} else if (!extMap.containsKey(dirName)) {
		// TODO
		errorInfo = "目录名不正确";
	} else {
		// .../basePath/dirName/
		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		// .../basePath/dirName/yyyyMMdd/
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		// 获取上传临时路径
		tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";
		File file = new File(tempPath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	return errorInfo;
}
 
Example 18
Source File: UploadUtils.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 上传验证,并初始化文件目录
 * 
 * @param request
 */
private String validateFields(HttpServletRequest request) {
	String errorInfo = "true";
	// boolean errorFlag = true;
	// 获取内容类型
	String contentType = request.getContentType();
	int contentLength = request.getContentLength();
	// 文件保存目录路径
	savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/";
	// 文件保存目录URL
	saveUrl = request.getContextPath() + "/" + basePath + "/";
	File uploadDir = new File(savePath);
	if (contentType == null || !contentType.startsWith("multipart")) {
		// TODO
		org.jeecgframework.core.util.LogUtil.info("请求不包含multipart/form-data流");
		errorInfo = "请求不包含multipart/form-data流";
	} else if (maxSize < contentLength) {
		// TODO
		org.jeecgframework.core.util.LogUtil.info("上传文件大小超出文件最大大小");
		errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]";
	} else if (!ServletFileUpload.isMultipartContent(request)) {
		// TODO
		errorInfo = "请选择文件";
	} else if (!uploadDir.isDirectory()) {// 检查目录
		// TODO
		errorInfo = "上传目录[" + savePath + "]不存在";
	} else if (!uploadDir.canWrite()) {
		// TODO
		errorInfo = "上传目录[" + savePath + "]没有写权限";
	} else if (!extMap.containsKey(dirName)) {
		// TODO
		errorInfo = "目录名不正确";
	} else {
		// .../basePath/dirName/
		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		// .../basePath/dirName/yyyyMMdd/
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		// 获取上传临时路径
		tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";
		File file = new File(tempPath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	return errorInfo;
}
 
Example 19
Source File: MockMvcConnectionBuilderSupportTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@RequestMapping
public String contextPath(HttpServletRequest request) {
	return request.getContextPath();
}
 
Example 20
Source File: JetFunctions.java    From jetbrick-template-1x with Apache License 2.0 4 votes vote down vote up
/**
 * @since 1.2.0
 */
public static String ctxpath(JetPageContext ctx, String url) {
    HttpServletRequest request = (HttpServletRequest) ctx.getContext().get(JetWebContext.REQUEST);
    return request.getContextPath() + url;
}