當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。