本文整理匯總了Java中javax.servlet.http.HttpServletRequest.getCharacterEncoding方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpServletRequest.getCharacterEncoding方法的具體用法?Java HttpServletRequest.getCharacterEncoding怎麽用?Java HttpServletRequest.getCharacterEncoding使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.servlet.http.HttpServletRequest
的用法示例。
在下文中一共展示了HttpServletRequest.getCharacterEncoding方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: APIRequest
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
public APIRequest(HttpServletRequest request) {
this.request = request;
header = new HashMap<String, Object>();
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Object value = request.getHeader(name);
header.put(name, value);
}
params = getParamesMap(request.getParameterMap());
url = request.getRequestURL().toString();
uri = request.getRequestURI();
remoteAddr = request.getRemoteAddr();
remoteHost = request.getRemoteHost();
remotePort = request.getRemotePort();
contextPath = request.getContextPath();
localAddr = request.getLocalAddr();
characterEncoding = request.getCharacterEncoding();
localName = request.getLocalName();
localPort = request.getLocalPort();
method = request.getMethod();
queryString = request.getQueryString();
}
示例2: 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();
}
示例3: doFilter
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String servletPath = req.getServletPath() + req.getPathInfo();
xLogger.fine("Servlet path: ", servletPath);
if (req.getCharacterEncoding() == null) {
request.setCharacterEncoding(Constants.UTF8);
}
if (!(StringUtils.isNotBlank(servletPath) && servletPath.startsWith(MEDIA_ENDPOINT_URL))) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (filterChain != null) {
filterChain.doFilter(request, response);
}
}
示例4: binaryReader
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
* 讀取請求流
* @param request
* @return
* @throws IOException
*/
public static String binaryReader(HttpServletRequest request) throws IOException {
String charset = request.getCharacterEncoding();
if (charset == null) {
charset = "utf-8";
}
BufferedReader in = new BufferedReader(new InputStreamReader(request
.getInputStream(), charset));
// Read the request
CharArrayWriter data = new CharArrayWriter();
char[] buf = new char[8192];
int ret;
while ((ret = in.read(buf, 0, 8192)) != -1) {
data.write(buf, 0, ret);
}
return data.toString();
}
示例5: extractRequestParameter
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
* 從HttpServletRequest中提取請求參數(包括請求體中的參數)
* @param request
* @param loggingContext
* @return
* @throws Exception
*/
protected HttpRequestParameter extractRequestParameter(HttpServletRequest request, LoggingContext loggingContext) throws Exception {
HttpRequestParameter parameter = new HttpRequestParameter();
Map<String,String[]> originalParamMap = request.getParameterMap();
Map<String,String> paramMap = new HashMap<String,String>();
if(originalParamMap != null && !originalParamMap.isEmpty()){
for(Map.Entry<String, String[]> entry : originalParamMap.entrySet()){
paramMap.put(entry.getKey(), getStringParameterValue(entry.getValue()));
}
}
parameter.setParameter(paramMap);
MediaType contentType = loggingContext.getHttpAccessLog().getRequestContentType();
if(contentType != null){
if(isContentCachingRequest(request)){
String charset = request.getCharacterEncoding();
if(StringUtils.isEmpty(charset)){
charset = StringUtils.defaultIfEmpty(contentType.getCharset().name(), GlobalConstants.SYSTEM_DEFAULT_CHARSET);
}
ContentCachingRequestWrapper requestToUse = (ContentCachingRequestWrapper) request;
byte[] bytes = requestToUse.getContentAsByteArray();
if(bytes != null){
String body = IOUtils.toString(bytes, charset);
Object bodyObj = body;
if(MediaType.APPLICATION_JSON.getType().equals(contentType.getType())){ //目前隻處理JSON類型的數據
if(body.startsWith("[") && body.endsWith("]")){ //JSON Array String -> List<Map<String,Object>>
bodyObj = JsonUtils.json2Object(body, new TypeReference<List<Map<String,Object>>>(){});
}else if(body.startsWith("{") && body.endsWith("}")){ //JSON Object String -> Map<String,Object>
bodyObj = JsonUtils.json2Object(body, new TypeReference<Map<String,Object>>(){});
}
}
parameter.setBody(bodyObj);
}
}
}
return excludeRequestParameter(parameter, loggingContext);
}
示例6: IgnoreCharacterEncodingHttpRequestWrapper
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
* If the character encoding is not initialized, it will be set to UTF-8
*/
public IgnoreCharacterEncodingHttpRequestWrapper(HttpServletRequest request)
throws UnsupportedEncodingException {
super(request);
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding(Constants.CHARACTER_ENCODING_UTF8);
}
}
示例7: setRequest
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
public void setRequest(HttpServletRequest req)
{
_clearMap();
_requestParams = req.getParameterMap();
_encoding = req.getCharacterEncoding();
}
示例8: getEvents
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
* {@inheritDoc}
*/
@Override
public List<Event> getEvents(HttpServletRequest request) throws Exception {
BufferedReader reader = request.getReader();
String charset = request.getCharacterEncoding();
//UTF-8 is default for JSON. If no charset is specified, UTF-8 is to
//be assumed.
if (charset == null) {
LOG.debug("Charset is null, default charset of UTF-8 will be used.");
charset = "UTF-8";
} else if (!(charset.equalsIgnoreCase("utf-8")
|| charset.equalsIgnoreCase("utf-16")
|| charset.equalsIgnoreCase("utf-32"))) {
LOG.error("Unsupported character set in request {}. "
+ "JSON handler supports UTF-8, "
+ "UTF-16 and UTF-32 only.", charset);
throw new UnsupportedCharsetException("JSON handler supports UTF-8, "
+ "UTF-16 and UTF-32 only.");
}
/*
* Gson throws Exception if the data is not parseable to JSON.
* Need not catch it since the source will catch it and return error.
*/
List<Event> eventList = new ArrayList<Event>(0);
try {
eventList = gson.fromJson(reader, listType);
} catch (JsonSyntaxException ex) {
throw new HTTPBadRequestException("Request has invalid JSON Syntax.", ex);
}
for (Event e : eventList) {
((JSONEvent) e).setCharset(charset);
}
return getSimpleEvents(eventList);
}
示例9: doFilterInternal
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
示例10: encodeFormParameters
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
private byte[] encodeFormParameters(HttpServletRequest request, String defaultEncoding) {
try {
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = defaultEncoding;
}
Map<String, List<String>> formParameters = parseFormParameters(request, encoding);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outputStream, encoding);
boolean firstFormParameter = true;
for (Map.Entry<String, List<String>> formParameter : formParameters.entrySet()) {
String formParameterName = formParameter.getKey();
String encodedFormParameterName = URLEncoder.encode(formParameterName, encoding);
for (String formParameterValue : formParameter.getValue()) {
String encodedFormParameterValue = URLEncoder.encode(formParameterValue, encoding);
if (firstFormParameter) {
firstFormParameter = false;
} else {
writer.write('&');
}
writer.write(encodedFormParameterName);
writer.write('=');
writer.write(encodedFormParameterValue);
}
}
writer.close();
return outputStream.toByteArray();
} catch (Throwable error) {
LOGGER.error("failed to encode form parameters", error);
return new byte[0];
}
}
示例11: getRequestBody
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@SuppressWarnings("deprecation")
private String getRequestBody(HttpServletRequest request) throws IOException {
String charset = request.getCharacterEncoding() == null ? CHARSET_UTF_8 : request.getCharacterEncoding();
String requestBody = IOUtils.toString(request.getInputStream(), charset);
if (StringUtils.isBlank(requestBody)) {
throw new IllegalArgumentException("request-body is empty");
}
return requestBody;
}
示例12: process
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
* Process a HTTP request for a service price model
*
* @param request
* a HTTP servlet request
* @param response
* a HTTP servlet response
* @throws ServletException
* @throws IOException
*/
@Override
protected void process(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
response.setHeader("Cache-Control",
"no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
final String locale = request.getParameter(REQUEST_PARAM_LOCALE);
if (emptyString(locale)) {
errorForward(request, response, "Please enter a valid locale.");
return;
}
Map<ContextKey, ContextValue<?>> context = evaluateServicePmContext(request);
if (context != null) {
PriceModel priceModel = getPriceModel(context,
createLocaleSet(SUPPORTED_LOCALES));
if (priceModel == null) {
errorForward(request, response, "Price model not found.");
return;
}
PriceModelContent priceModelContent = getPriceModelContent(
priceModel, new Locale(locale));
if (priceModelContent != null) {
if (!generatePdfResponse(priceModelContent,
generateServicePmFileName(context), response)) {
errorForward(request, response,
"Price model found but its file type was not supported.");
}
} else {
errorForward(request, response,
"Price model neither found for specified locale nor for default locale.");
}
} else {
errorForward(request, response, "Please enter all required fields.");
}
}
示例13: doFilter
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
xLogger.fine("Entered doFilter");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String servletPath = req.getServletPath();
if (req.getCharacterEncoding() == null) {
request.setCharacterEncoding(Constants.UTF8);
}
// BACKWARD COMPATIBILITY - in case people have already bookmarked these links
if ("/index.jsp".equals(servletPath) || "/login.jsp".equals(servletPath)) {
resp.sendRedirect(isForceNewUI ? HOME_URL_NEW : HOME_URL);
return;
}
SecureUserDetails
userDetails = null;
// END BACKWARD COMPATIBILITY
if (!LOGIN_URL.equals(servletPath) && !AUTHENTICATE_URL.equals(servletPath) && (
servletPath.isEmpty() || servletPath.equals("/") || servletPath.startsWith("/s/") || (
servletPath.startsWith(TASK_URL) && StringUtils
.isBlank(req.getHeader(Constants.X_APP_ENGINE_TASK_NAME))))) {
userDetails = SecurityMgr
.getSessionDetails(req.getSession());
if (userDetails == null) { // session not authenticated yet; direct to login screen
if (!(servletPath.startsWith(TASK_ADMIN_URL) && ACTION_UPDATESYSCONFIG
.equals(request.getParameter(ACTION)))) {
if (isForceNewUI) {
resp.sendRedirect(HOME_URL_NEW); // login please
} else {
String redirectPath = LOGIN_URL;
if (servletPath.startsWith("/s/") || servletPath.startsWith(TASK_URL)) {
String rUrl = servletPath;
String queryString = req.getQueryString();
if (queryString != null && !queryString.isEmpty()) {
rUrl += "?" + queryString;
}
redirectPath += "?rurl=" + URLEncoder.encode(rUrl, "UTF-8");
}
resp.sendRedirect(redirectPath); // login please
}
return;
}
} else {
String role = userDetails.getRole();
if (SecurityConstants.ROLE_KIOSKOWNER
.equals(role)) { // Kiosk owner cannot access this interface
SessionMgr.cleanupSession(req.getSession());
resp.sendRedirect(LOGIN_URL + "?status=4");
return;
}
if ((servletPath.contains("/admin/") || servletPath.startsWith(TASK_URL))
&& !SecurityConstants.ROLE_SUPERUSER.equals(role)) { // only superuser can access
SessionMgr.cleanupSession(req.getSession());
resp.sendRedirect(LOGIN_URL + "?status=4"); // access denied
return;
}
}
}
if (userDetails != null) {
SecurityUtils.setUserDetails(userDetails);
}
try {
if (filterChain != null) {
filterChain.doFilter(request, response);
}
} finally {
if (userDetails != null) {
SecurityUtils.setUserDetails(null);
}
}
}
示例14: doFilter
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String servletPath = req.getServletPath() + req.getPathInfo();
xLogger.fine("Servlet path: ", servletPath);
if (req.getCharacterEncoding() == null) {
request.setCharacterEncoding(Constants.UTF8);
}
if (StringUtils.isNotEmpty(req.getHeader("app-name"))) {
filterChain.doFilter(request, response);
}
try {
//this is meant for internal api client
if (StringUtils.isNotBlank(req.getHeader(X_ACCESS_USER))) {
try {
SecurityMgr.setSessionDetails(req.getHeader(X_ACCESS_USER));
} catch (Exception e) {
xLogger.severe("Issue with api client authentication", e);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return;
}
} else if (StringUtils.isBlank(req.getHeader(Constants.X_APP_ENGINE_TASK_NAME)) && !(
StringUtils.isNotBlank(servletPath) && (servletPath.startsWith(ASSET_STATUS_URL)
|| servletPath.startsWith(SMS_API_URL) || servletPath.startsWith(M_AUTH_URL)))) {
String recvdCookie = getAppCookie(req);
if (appVerAvailable && recvdCookie != null && !appVersion.equals(recvdCookie)) {
resp.setHeader(ERROR_HEADER_NAME, UPGRADE_REQUIRED_RESPONSE_CODE);
resp.sendError(HttpServletResponse.SC_CONFLICT, "Upgrade required");
return;
}
if (StringUtils.isNotBlank(servletPath) && !(servletPath.startsWith(APP_STATUS_URL)
|| servletPath.startsWith(AUTHENTICATE_URL))) {
SecureUserDetails
userDetails = SecurityMgr
.getSessionDetails(req.getSession());
if (userDetails == null) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Required.");
return;
}
SecurityUtils.setUserDetails(userDetails);
String reqDomainId = SecurityUtils.getReqCookieUserDomain(req);
if (reqDomainId != null && !reqDomainId.equals(
userDetails.getUsername() + CharacterConstants.COLON + SecurityUtils
.getCurrentDomainId())) {
resp.setHeader(ERROR_HEADER_NAME, DOMAIN_CHANGE_RESPONSE_CODE);
resp.sendError(HttpServletResponse.SC_CONFLICT, "Invalid session on client");
return;
}
}
}
if (filterChain != null) {
filterChain.doFilter(request, response);
}
} finally {
SecurityUtils.setUserDetails(null);
}
}
示例15: addTextParameter
import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
* Adds a regular text parameter to the set of text parameters for this
* request and also to the list of all parameters. Handles the case of
* multiple values for the same parameter by using an array for the
* parameter value.
*
* @param request The request in which the parameter was specified.
* @param item The file item for the parameter to add.
*/
protected void addTextParameter(HttpServletRequest request, FileItem item) {
String name = item.getFieldName();
String value = null;
boolean haveValue = false;
String encoding = request.getCharacterEncoding();
if (encoding != null) {
try {
value = item.getString(encoding);
haveValue = true;
} catch (Exception e) {
// Handled below, since haveValue is false.
}
}
if (!haveValue) {
try {
value = item.getString("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
value = item.getString();
}
haveValue = true;
}
if (request instanceof MultipartRequestWrapper) {
MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
wrapper.setParameter(name, value);
}
String[] oldArray = (String[]) elementsText.get(name);
String[] newArray;
if (oldArray != null) {
newArray = new String[oldArray.length + 1];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
newArray[oldArray.length] = value;
} else {
newArray = new String[] { value };
}
elementsText.put(name, newArray);
elementsAll.put(name, newArray);
}