当前位置: 首页>>代码示例>>Java>>正文


Java HttpServletRequest类代码示例

本文整理汇总了Java中javax.servlet.http.HttpServletRequest的典型用法代码示例。如果您正苦于以下问题:Java HttpServletRequest类的具体用法?Java HttpServletRequest怎么用?Java HttpServletRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


HttpServletRequest类属于javax.servlet.http包,在下文中一共展示了HttpServletRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: shouldBodyBeZero

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
/**
 * Performs a number of checks to ensure response saneness according to the rules of RFC2616:
 * <ol>
 * <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body
 * to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
 * <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body
 * to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
 * </ol>
 *
 * @param request        the client HTTP request
 * @param responseStatus the responseStatus
 * @return true if the response should be 0, even if it is isn't.
 */
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) {

    //Check for NO_CONTENT
    if (responseStatus == HttpServletResponse.SC_NO_CONTENT) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
                    request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT);
        }
        return true;
    }

    //Check for NOT_MODIFIED
    if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
                    request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED);
        }
        return true;
    }
    return false;
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:35,代码来源:GZipResponseUtil.java

示例2: getCookie

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
public Map<String,Cookie> getCookie() {
    if (this.cookie == null) {
        this.cookie = new ScopeMap<Cookie>() {
            @Override
            protected Enumeration<String> getAttributeNames() {
                Cookie[] c = ((HttpServletRequest) page.getRequest())
                        .getCookies();
                if (c != null) {
                    Vector<String> v = new Vector<String>();
                    for (int i = 0; i < c.length; i++) {
                        v.add(c[i].getName());
                    }
                    return v.elements();
                }
                return null;
            }

            @Override
            protected Cookie getAttribute(String name) {
                Cookie[] c = ((HttpServletRequest) page.getRequest())
                        .getCookies();
                if (c != null) {
                    for (int i = 0; i < c.length; i++) {
                        if (name.equals(c[i].getName())) {
                            return c[i];
                        }
                    }
                }
                return null;
            }

        };
    }
    return this.cookie;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:36,代码来源:ImplicitObjectELResolver.java

示例3: doFilterInternal

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:19,代码来源:CsrfCookieGeneratorFilter.java

示例4: showInit

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
/**
 * Shows initialization page.
 *
 * @param context
 *            the specified http request context
 * @param request
 *            the specified http servlet request
 * @param response
 *            the specified http servlet response
 * @throws Exception
 *             exception
 */
@RequestMapping(value = "/init", method = RequestMethod.GET)
public void showInit(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
	if (initService.isInited()) {
		response.sendRedirect("/");
		return;
	}

	final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
	renderer.setTemplateName("init.ftl");

	final Map<String, Object> dataModel = renderer.getDataModel();

	final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));

	dataModel.putAll(langs);

	dataModel.put(Common.VERSION, SoloConstant.VERSION);
	dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
	dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));

	Keys.fillRuntime(dataModel);
	filler.fillMinified(dataModel);
	renderer.render(request, response);
}
 
开发者ID:daima,项目名称:solo-spring,代码行数:37,代码来源:InitProcessor.java

示例5: getUsername

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
/**
    * TODO default proper exception at lams level to replace RuntimeException TODO isTesting should be removed when
    * login is done properly.
    *
    * @param req
    *            -
    * @return username from principal object
    */
   public static String getUsername(HttpServletRequest req, boolean isTesting) throws RuntimeException {
if (isTesting) {
    return "test";
}

Principal prin = req.getUserPrincipal();
if (prin == null) {
    throw new RuntimeException(
	    "Trying to get username but principal object missing. Request is " + req.toString());
}

String username = prin.getName();
if (username == null) {
    throw new RuntimeException("Name missing from principal object. Request is " + req.toString()
	    + " Principal object is " + prin.toString());
}

return username;
   }
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:28,代码来源:WebUtil.java

示例6: doAliPayRes

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
public String doAliPayRes(HttpServletRequest request) throws ServletException, IOException {
	String logPrefix = "【支付宝支付回调通知】";
	//获取支付宝POST过来反馈信息
	Map<String,String> params = new HashMap<String,String>();
	Map requestParams = request.getParameterMap();
	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		String name = (String) iter.next();
		String[] values = (String[]) requestParams.get(name);
		String valueStr = "";
		for (int i = 0; i < values.length; i++) {
			valueStr = (i == values.length - 1) ? valueStr + values[i]
					: valueStr + values[i] + ",";
		}
		//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
		//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
		params.put(name, valueStr);
	}
	_log.info("{}通知请求数据:reqStr={}", logPrefix, params);
	if(params.isEmpty()) {
		_log.error("{}请求参数为空", logPrefix);
		return PayConstant.RETURN_ALIPAY_VALUE_FAIL;
	}
	return notifyPayService.doAliPayNotify(params);
}
 
开发者ID:ywtnhm,项目名称:pay-xxpay-master,代码行数:25,代码来源:Notify4AliPayController.java

示例7: createTargetUrl

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
/**
 * Creates the target URL by checking if the redirect string is a URI template first,
 * expanding it with the given model, and then optionally appending simple type model
 * attributes as query String parameters.
 */
protected final String createTargetUrl(Map<String, Object> model, HttpServletRequest request)
        throws UnsupportedEncodingException {
    // Prepare target URL.
    StringBuilder targetUrl = new StringBuilder();
    if (this.contextRelative && getUrl().startsWith("/")) {
        // Do not apply context path to relative URLs.
        targetUrl.append(request.getContextPath());
    }
    targetUrl.append(getUrl());
    
    String enc = this.encodingScheme;
    if (enc == null) {
        enc = request.getCharacterEncoding();
    }
    if (enc == null) {
        enc = DEFAULT_CHARACTER_ENCODING;
    }
    
    if (this.expandUriTemplateVariables && StringUtils.hasText(targetUrl)) {
        Map<String, String> variables = Collections.<String, String> emptyMap();
        targetUrl = replaceUriTemplateVariables(targetUrl.toString(), model, variables, enc);
    }
    if (this.exposeModelAttributes) {
        appendQueryProperties(targetUrl, model, enc);
    }
    return targetUrl.toString();
}
 
开发者ID:devefx,项目名称:validator-web,代码行数:33,代码来源:RedirectView.java

示例8: index

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
@At("/")
@Ok("beetl:/WEB-INF/base/productlevel_list.html")
public void index(@Param("..")Page p,
                  @Param("..")Productlevel productlevel,
                  HttpServletRequest request){

    Cnd c = new ParseObj(productlevel).getCnd();
    if (c == null || c.equals(""))
    {
        p.setRecordCount(productlevelService.listCount(c));
        request.setAttribute("list_obj", productlevelService.queryCache(c,p));
    }else{
        p.setRecordCount(productlevelService.count(c));
        request.setAttribute("list_obj", productlevelService.query(c,p));
    }

    request.setAttribute("page", p);
    request.setAttribute("productlevel", productlevel);
}
 
开发者ID:lq10001,项目名称:product,代码行数:20,代码来源:ProductlevelAction.java

示例9: execute

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("uflo-html/designer.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
开发者ID:youseries,项目名称:uflo,代码行数:17,代码来源:DesignerServletHandler.java

示例10: selectMockRuleScript

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
@ResponseBody
@RequestMapping(value = "/selectMockRuleScript")
public String selectMockRuleScript(HttpServletRequest arg0, Boolean selectFlag) throws Exception {
    String serviceId = arg0.getParameter("serviceId");
    String mockTestIds = arg0.getParameter("mockTestIds");
    String[] mocks = mockTestIds.split(",");
    Integer[] integers = new Integer[mocks.length];
    for (int i = 0; i < mocks.length; i++) {
        integers[i] = Integer.valueOf(mocks[i]);
    }
    MockGenericService service = dubboMockServer.buildMockGenericService(Integer.valueOf(serviceId), integers);
    Map<String, String> map = Maps.newConcurrentMap();
    Set<String> set = service.getRules().keySet();
    for (String key : set) {
        MethodRule rule = service.getRules().get(key);
        map.put(key, rule.getTemplate().getRaw());
    }
    return JSON.toJSONString(map);
}
 
开发者ID:tonyruiyu,项目名称:dubbo-mock,代码行数:20,代码来源:MockOperDefineController.java

示例11: getFileServer

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
public static Server getFileServer(ApplicationContext context) {
    Resource resource = context.getResource("classpath:templates");

    Server server = new Server(UrlTestingUtils.TEST_FILE_SERVER_PORT);
    server.setHandler(new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request,
                               HttpServletResponse response) throws IOException, ServletException {
            String uri = baseRequest.getRequestURI();
            LOGGER.info(uri);
            File file = new File(resource.getFile().getAbsolutePath() + uri);
            MultipartFileSender fileSender = MultipartFileSender.fromFile(file);
            try {
                fileSender.with(request).with(response).serveResource();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    return server;
}
 
开发者ID:react-dev26,项目名称:NGB-master,代码行数:23,代码来源:UrlTestingUtils.java

示例12: doGet

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
@Override
protected void doGet(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException,
                                                          IOException {
  response.setContentType("text/html");
  try {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL resource = classLoader.getResource(indexPagePath);
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{resource});

    InputStream input = urlClassLoader.getResourceAsStream(indexPagePath);
    String result = CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8));
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(result);
  } catch (Exception e) {
    response.getWriter().print(e);
    LOG.error("error : ", e);
  }
}
 
开发者ID:pinterest,项目名称:doctorkafka,代码行数:20,代码来源:DoctorKafkaWebServer.java

示例13: export

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
@RequestMapping("bpm-category-export")
public void export(@ModelAttribute Page page,
        @RequestParam Map<String, Object> parameterMap,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<PropertyFilter> propertyFilters = PropertyFilter
            .buildFromMap(parameterMap);
    page = bpmCategoryManager.pagedQuery(page, propertyFilters);

    List<BpmCategory> bpmCategories = (List<BpmCategory>) page.getResult();
    TableModel tableModel = new TableModel();
    tableModel.setName("bpm-category");
    tableModel.addHeaders("id", "name");
    tableModel.setData(bpmCategories);
    exportor.export(request, response, tableModel);
}
 
开发者ID:zhaojunfei,项目名称:lemon,代码行数:17,代码来源:BpmCategoryController.java

示例14: validate

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
       ActionErrors errors = new ActionErrors();

       if(iSetting==null || iSetting.intValue()<0)
           errors.add("setting", new ActionMessage("errors.lookup.config.required", ""));
       
       Set<Long> emptyIds = new HashSet<Long>(SolverPredefinedSettingDAO.getInstance().getSession().createQuery(
       		"select s.uniqueId from SolverParameterDef s where s.group.name = :group and s.visible = true and s.type = :type")
       		.setString("group", "StudentSctBasic")
       		.setString("type", "text").setCacheable(true).list());
       
       for (Iterator i=iParamValues.entrySet().iterator();i.hasNext();) {
       	Map.Entry entry = (Map.Entry)i.next();
        	Long parm = (Long)entry.getKey();
        	if (emptyIds.contains(parm)) continue;
       	String val = (String)entry.getValue();
       	if (val==null || val.trim().length()==0)
       		errors.add("parameterValue["+parm+"]", new ActionMessage("errors.required", ""));
       }
       
       return errors;
}
 
开发者ID:Jenner4S,项目名称:unitimes,代码行数:23,代码来源:StudentSolverForm.java

示例15: doGetPost

import javax.servlet.http.HttpServletRequest; //导入依赖的package包/类
public void doGetPost(MCRServletJob job) throws Exception {
  //prepare request
    HttpServletRequest req = job.getRequest();
    
    //prepare Connection
    OrcidConnector connection = new OrcidConnector();
    
    //get parameter from URL
    String orcid = getParameter(req, "id");
    
    //send request to API
    MCRContent orcidExport = connection.getPublicationsByOrcid(orcid);
    
   //transform in MODS
    MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/Orcid2mods.xsl");
    MCRContent mods = transformer.transform(orcidExport);
    
    //save results
    mods.sendTo(new File(resultsDir,"OrcidProfile_mods_OrcID" + orcid + ".xml"));
    
    connection.close();
}
 
开发者ID:ETspielberg,项目名称:bibliometrics,代码行数:23,代码来源:AskOrcidServlet.java


注:本文中的javax.servlet.http.HttpServletRequest类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。