本文整理匯總了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;
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}
示例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);
}
示例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();
}
示例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);
}
示例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();
}
}
示例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);
}
示例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;
}
示例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);
}
}
示例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);
}
示例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;
}
示例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();
}