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

The following examples show how to use javax.servlet.http.HttpServletRequest#getServletContext() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter pw = resp.getWriter();
    ServletContext sc = req.getServletContext();
    pw.println("01-" + sc.getContext("/bar").getInitParameter("id"));
    pw.println("02-" + sc.getContext("/foo").getInitParameter("id"));
    pw.println("03-" + sc.getContext("/foo##1").getInitParameter("id"));
    pw.println("04-" + sc.getContext("/foo##2").getInitParameter("id"));
    pw.println("05-" + sc.getContext("/foo##3").getInitParameter("id"));
    pw.println("06-" + sc.getContext("/unknown").getInitParameter("id"));
    pw.println("07-" + sc.getContext("/").getInitParameter("id"));
    pw.println("08-" + sc.getContext("/foo/bar").getInitParameter("id"));
    pw.println("09-" + sc.getContext("/football").getInitParameter("id"));
}
 
Example 2
Source Project: scipio-erp   File: UtilHttp.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a map from a ServletContext object
 * @return The resulting Map
 */
public static Map<String, Object> getServletContextMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
    Map<String, Object> servletCtxMap = new HashMap<>();

    // look at all servlet context attributes
    ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
    Enumeration<String> applicationAttrNames = UtilGenerics.cast(servletContext.getAttributeNames());
    while (applicationAttrNames.hasMoreElements()) {
        String attrName = applicationAttrNames.nextElement();
        if (namesToSkip != null && namesToSkip.contains(attrName)) {
            continue;
        }

        Object attrValue = servletContext.getAttribute(attrName);
        servletCtxMap.put(attrName, attrValue);
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("Made ServletContext Attribute Map with [" + servletCtxMap.size() + "] Entries", module);
        Debug.logVerbose("ServletContext Attribute Map Entries: " + System.getProperty("line.separator") + UtilMisc.printMap(servletCtxMap), module);
    }

    return servletCtxMap;
}
 
Example 3
Source Project: scipio-erp   File: TaskEvents.java    License: Apache License 2.0 6 votes vote down vote up
/** Delegate and accept assignment event */
public static String delegateAndAcceptAssignment(HttpServletRequest request, HttpServletResponse response) {
    ServletContext ctx = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
    RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
    Locale locale = UtilHttp.getLocale(request);

    if (addToOrderRole(request)) {
        try {
            EventHandler eh = rh.getEventFactory().getEventHandler("service");
            eh.invoke(new Event("service", "", "wfAcceptRoleAssignment", true), null, request, response);
        } catch (EventHandlerException e) {
            Debug.logError(e, "Invocation error", module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,"OrderFailedToInvokeTheWfDelegateAndAcceptAssignmentService", locale));
            return "error";
        }
        return "success";
    }
    return "error";
}
 
Example 4
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    ServletContext sc;
    if (targetContextPath == null) {
        sc = req.getServletContext();
    } else {
        sc = req.getServletContext().getContext(targetContextPath);
    }
    sc.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE);
    sc.getRequestDispatcher(targetPath).forward(req, resp);
}
 
Example 5
/**
 * 加载资源-权限关系
 */
private void loadResource(HttpServletRequest request) {
    try {
        List<ResourceEntity> resourceEntityList = resourceEntityMapper.selectByExample(new ResourceEntityExample());
        if (resourceEntityList == null || resourceEntityList.size() == 0) {
            log.warn("DB中没有查到资源权限列表,请先配置resource_entity!");
        } else {
            resourceMap.clear();
            Collection<ConfigAttribute> array;
            ConfigAttribute cfg;
            ServletContext sc = request.getServletContext();
            ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

            HandlerMappingIntrospector introspector = ac.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, HandlerMappingIntrospector.class);

            for (ResourceEntity resourceEntity : resourceEntityList) {
                array = new ArrayList<>();
                cfg = new ExpressionConfigAttribute(expressionHandler.getExpressionParser().parseExpression(resourceEntity.getPermission()));
                array.add(cfg);
                resourceMap.put(new MvcRequestMatcher(introspector, resourceEntity.getUrl()), array);
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("加载权限列表异常", e);
        }
    }

}
 
Example 6
@RequestMapping("/httpdoc")
public void render(
        @RequestParam(value = "charset", required = false) String charset,
        @RequestParam(value = "contentType", required = false) String contentType,
        HttpServletRequest req,
        HttpServletResponse res
) throws IOException, DocumentTranslationException {
    String uri = req.getRequestURI();
    int index = uri.indexOf('.');
    String suffix = index < 0 ? null : uri.substring(index + 1);
    Serializer serializer = suffix != null ? serializers.get(suffix) : serializers.values().iterator().next();
    if (serializer == null) {
        res.sendError(404);
        return;
    }

    Container container = new SpringMVCHttpdocContainer(req.getServletContext());
    Translation translation = new Translation(container, supplier, interpreter);

    translation.setHttpdoc(httpdoc != null ? httpdoc : Module.getInstance().getVersion());
    translation.setProtocol(protocol != null ? protocol : req.getProtocol().split("/")[0].toLowerCase());
    translation.setHostname(hostname != null ? hostname : req.getServerName());
    translation.setPort(port != null ? port : req.getServerPort());
    translation.setContext(context != null ? context : req.getContextPath());
    translation.setVersion(version);

    Document document = translator.translate(translation);

    charset = charset != null && charset.trim().length() > 0 ? charset : "UTF-8";
    contentType = contentType != null && charset.trim().length() > 0 ? contentType : serializer.getType();
    res.setCharacterEncoding(charset);
    res.setContentType(contentType + "; charset=" + charset);
    Map<String, Object> doc = converter.convert(document, format);
    serializer.serialize(doc, res.getOutputStream());
}
 
Example 7
Source Project: soabase   File: JerseyGuiceModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@RequestScoped
public ServletContext provideServletContext()
{
    HttpServletRequest request = filter.getServletRequest();
    return (request != null) ? request.getServletContext() : null;
}
 
Example 8
Source Project: glowroot   File: UserIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MockHttpSession session = new MockHttpSession(request.getServletContext(), "123456789");
    ((MockHttpServletRequest) request).setSession(session);
    request.getSession(true);
    super.service(request, response);
}
 
Example 9
private void startLazily(HttpServletRequest request) {
	if (this.servletContext != null) {
		return;
	}
	synchronized (this.lifecycleMonitor) {
		if (this.servletContext == null) {
			this.servletContext = request.getServletContext();
			start();
		}
	}
}
 
Example 10
private void closeEditWrap(Writer out, HttpServletRequest request, HttpServletResponse response, String thisContentId, String editRequestName) throws IOException {
    String fullRequest = editRequestName;
    String delim = "?";
    if (UtilValidate.isNotEmpty(thisContentId)) {
        fullRequest += delim + "contentId=" + thisContentId;
        delim = "&";
    }
    out.write("<a href=\"");
    ServletContext servletContext = request.getServletContext(); // SCIPIO: NOTE: no longer need getSession() for getServletContext(), since servlet API 3.0
    RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
    out.append(rh.makeLink(request, response, "/" + fullRequest, false, null, true)); // SCIPIO: 2018-07-09: changed secure to null
    out.write("\">Edit</a>");
    out.write("</div>");
}
 
Example 11
protected ServerContainer getContainer(HttpServletRequest request) {
	ServletContext servletContext = request.getServletContext();
	String attrName = "javax.websocket.server.ServerContainer";
	ServerContainer container = (ServerContainer) servletContext.getAttribute(attrName);
	Assert.notNull(container, "No 'javax.websocket.server.ServerContainer' ServletContext attribute. " +
			"Are you running in a Servlet container that supports JSR-356?");
	return container;
}
 
Example 12
Source Project: scipio-erp   File: LoginWorker.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean hasBasePermission(GenericValue userLogin, HttpServletRequest request) {
    Security security = (Security) request.getAttribute("security");
    if (security != null) {
        ServletContext context = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
        String serverId = (String) context.getAttribute("_serverId");
        // SCIPIO: delegated to new overload
        return hasBasePermission(userLogin, request, security, serverId);
    } else {
        Debug.logWarning("Received a null Security object from HttpServletRequest", module);
    }
    return true;
}
 
Example 13
Source Project: scipio-erp   File: RequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * SCIPIO: Public redirect helper method that honors the status codes configured in the current controller
 * or requestHandler.properties, preserving the incoming query string.
 * <p>
 * FIXME: If uri provides any parameters, they may be crushed or duplicated by the incoming ones.
 */
public static void sendControllerUriRedirectWithQueryString(HttpServletRequest request, HttpServletResponse response, String uri, Boolean allowCacheRedirect) throws IllegalStateException {
    ServletContext ctx = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
    RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
    String url = rh.makeLinkFull(request, response, uri + rh.makeQueryString(request, null, null));
    if (url != null) {
        sendRedirect(request, response, url, allowCacheRedirect);
    } else {
        throw new IllegalStateException("Cannot redirect to controller uri because failed to generate link: " + uri);
    }
}
 
Example 14
public IAlbianRestfulActionContext AlbianRestfulActionContext_Safe(HttpServletRequest req,
                                                                   HttpServletResponse resp) {
    Map<String, String> param_pairs = splitQuery(req.getQueryString());
    IAlbianLogicIdService lids = AlbianServiceRouter.getLogIdService();
    return new AlbianRestfulActionContext(req, resp,
            req.getServletContext(), param_pairs.get("service"),
            param_pairs.get("action"), lids.makeStringUNID("session"),//req.getSession(true).getId(),内存持续增长
            param_pairs.get("sp"), param_pairs, null);
}
 
Example 15
Source Project: OASystem   File: AjaxAction.java    License: MIT License 5 votes vote down vote up
/**
 * ��ȡ��֤��
 * ��codeStr����֤���ַ���
 * @param req
 * @return ��֤�����ڵ�·��
 */
@RequestMapping(value="ajax/getLoginCodeAjax.do")
@ResponseBody
public String getLoginCode(HttpServletRequest req){
	HttpSession session = req.getSession();
	String codeStr = "";//��֤���
	String codeCon = "";//��֤������
	String path = "img/loginCode";//��֤��·��
	
	ServletContext application = req.getServletContext();
	String realPath = application.getRealPath("img/loginCode");
	String fileName = new Date().getTime()+".jpg";
	File file = new File(realPath+File.separator+fileName);//File.separator
	int num1 = (int)(Math.random()*10);
	int num2 = (int)(Math.random()*10);
	int fu = (int)(new Date().getTime()%2);
	if(fu==1){
		codeStr = (num1+num2)+"";
		codeCon = num1+"+"+num2;
	}else{
		codeStr = (num1-num2)+"";
		codeCon = num1+"-"+num2;
	}
	codeCon += "=?";
	try {
		CodeOfLogin.outputImage(600,200,file,codeCon);
	} catch (IOException e) {
		e.printStackTrace();
		return "error,jpg";
	}
	String name = fileName;//��֤���ļ���
	session.setAttribute("codeStr", codeStr);
	return path+"/"+name;
}
 
Example 16
Source Project: glowroot   File: SessionAttributeIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MockHttpSession session = new MockHttpSession(request.getServletContext(), "123456789");
    ((MockHttpServletRequest) request).setSession(session);
    request.getSession(true);
    super.service(request, response);
}
 
Example 17
Source Project: glowroot   File: UserIT.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void before(HttpServletRequest request, HttpServletResponse response) {
    MockHttpSession session = new MockHttpSession(request.getServletContext(), "123456789");
    ((MockHttpServletRequest) request).setSession(session);
}
 
Example 18
protected HttpServletRequest requestWrapper0(final HttpServletRequest request, HttpResponse response) {
    final Session session = decodeSession(response);
    bindAttributes(request);
    return new AuthenticationServletRequest(request, request.getServletContext(), session, httpClient(), serviceInvokeRetry, sessionURL(request));
}
 
Example 19
Source Project: OASystem   File: FileDepotAction.java    License: MIT License 4 votes vote down vote up
/**
 * ���ļ��ֿ�ɾ���ļ�
 * @param fileId
 * @param req
 * @return
 */
@RequestMapping("file/delFile.do")
public ModelAndView delFile(String fileId, HttpServletRequest req){
	String url = req.getHeader("REFERER");
	if(url!=null){
		if(url.indexOf("/file/")==-1){
			url = "/home.do";
		}else{
			url = url.substring(url.indexOf("/file/"));
		}
	}else{
		url = "/home.do";
	}
	
	if(fileId==null || fileId.length()==0){
		return JumpPrompt.jumpOfModelAndView(url, "ɾ��ʧ�ܡ���ȱ�ٲ�����");
	}
	String jobId = (String)req.getSession().getAttribute("userJobId");
	int userKind = userServer.getUserKindByJobId(jobId);
	int userPart = userServer.getUserPartByJobId(jobId);
	int userGroup= userServer.getUserGroupByJobId(jobId);
	
	FileDepot fd = fileDepotService.getOneFileInfoById(Integer.parseInt(fileId));
	if(fd==null){
		return JumpPrompt.jumpOfModelAndView(url, "ɾ��ʧ�ܡ���δ�ҵ���Ӧ�ļ���");
	}
	String createUserId = fd.getCreatePerson();
	
	//�ж��Ƿ����ɾ��
	boolean canDel = false;
	if(fd.getSource()==FileDepot.SOURCE_COMPANY && userKind==UserInfo.KIND_MANAGER_WEB){
		//��˾�ļ�
		canDel = true;
	}else if(fd.getSource()==FileDepot.SOURCE_PART){
		//�����ļ�
		if(userKind==UserInfo.KIND_MANAGER_WEB){
			canDel = true;
		}else if(userKind==UserInfo.KIND_MANAGER_PART && fd.getPart()==userPart){
			canDel = true;
		}
	}else if(createUserId.equals(jobId)){
		canDel = true;
	}else{
		//��
		if(userKind==0){
			canDel = true;
		}else if(userKind==UserInfo.KIND_MANAGER_PART && fd.getPart()==userPart){
			canDel = true;
		}else if(userKind==UserInfo.KIND_MANAGER_GROUP && fd.getPart()==userPart && fd.getGroup()==userGroup){
			canDel = true;
		}
	}
	if(!canDel){
		return JumpPrompt.jumpOfModelAndView(url, "ɾ��ʧ�ܡ�����Ȩ�ޣ�");
	}
	
	ServletContext application = req.getServletContext();
	String realPath = application.getRealPath("upload/file/fileDepot");
	String fileName = realPath+File.separator+fd.getRealFileName();
	File file = new File(fileName);
	if(file.exists()){
		//ɾ�����ݿ�
		boolean tempB = false;
		try {
			tempB = fileDepotService.delFileById(Integer.parseInt(fileId));
		} catch (Exception e) {}
		if(!tempB){
			return JumpPrompt.jumpOfModelAndView(url, "ɾ��ʧ�ܡ������ݿ�ɾ��ʧ�ܣ�");
		}
		if(file.delete()){
			return JumpPrompt.jumpOfModelAndView(url, "ɾ���ļ���"+fd.getShowFileName()+"���ɹ���");
		}else{
			return JumpPrompt.jumpOfModelAndView(url, "ɾ���ļ���"+fd.getShowFileName()+"���ɹ�������������ɾ���ļ�ʧ�ܣ�");
		}
	}else{
		return JumpPrompt.jumpOfModelAndView(url, "ɾ��ʧ�ܡ����������Ҳ������ļ���");
	}
}
 
Example 20
/**
 * Get {@link ServletContext} from {@link HttpServletRequest}
 *
 * @param request {@link HttpServletRequest}
 * @return non-null
 */
public static ServletContext getServletContext(HttpServletRequest request) {

    if (isRunningBelowServlet3Container()) { // below Servlet 3.x

        return request.getSession().getServletContext();

    }

    return request.getServletContext();
}