下面列出了javax.servlet.http.HttpServletRequest#getMethod() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
SmsAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
/**
* 覆盖授权验证方法
*/
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
Map<String, Object> map = JsonUtil.jsonToMap(body);
String username = map.get("userName")+"";
String password = map.get("password")+"";
//根据不同登录方式,生成不同类型Authentication,如这里的CaptchaAuthenticationToken
CaptchaAuthenticationToken authRequest = new CaptchaAuthenticationToken(username,password);
//其他参数,可以是一个字符串,也可以任意对象
//authRequest.setDetails("其他参数");
//将未认证Authentication交给AuthenticationManager去认证
return getAuthenticationManager().authenticate(authRequest);
}
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
SmsAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
/**
* Validate the given type-level mapping metadata against the current request,
* checking HTTP request method and parameter conditions.
* @param mapping the mapping metadata to validate
* @param request current HTTP request
* @throws Exception if validation failed
*/
protected void validateMapping(RequestMapping mapping, HttpServletRequest request) throws Exception {
RequestMethod[] mappedMethods = mapping.method();
if (!ServletAnnotationMappingUtils.checkRequestMethod(mappedMethods, request)) {
String[] supportedMethods = new String[mappedMethods.length];
for (int i = 0; i < mappedMethods.length; i++) {
supportedMethods[i] = mappedMethods[i].name();
}
throw new HttpRequestMethodNotSupportedException(request.getMethod(), supportedMethods);
}
String[] mappedParams = mapping.params();
if (!ServletAnnotationMappingUtils.checkParameters(mappedParams, request)) {
throw new UnsatisfiedServletRequestParameterException(mappedParams, request.getParameterMap());
}
String[] mappedHeaders = mapping.headers();
if (!ServletAnnotationMappingUtils.checkHeaders(mappedHeaders, request)) {
throw new ServletRequestBindingException("Header conditions \"" +
StringUtils.arrayToDelimitedString(mappedHeaders, ", ") +
"\" not met for actual request");
}
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else {
String openId = this.obtainOpenId(request);
if (openId == null) {
openId = "";
}
openId = openId.trim();
String provider = this.obtainProvider(request);
if (provider == null) {
provider = "";
}
provider = provider.trim();
OpenIdAuthenticationToken authRequest = new OpenIdAuthenticationToken(openId, provider);
this.setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求编码方式
request.setCharacterEncoding(FrameworkConstant.UTF_8);
// 获取当前请求相关数据
String currentRequestMethod = request.getMethod();
String currentRequestPath = WebUtil.getRequestPath(request);
logger.debug("[Smart] {}:{}", currentRequestMethod, currentRequestPath);
// 将“/”请求重定向到首页
if (currentRequestPath.equals("/")) {
WebUtil.redirectRequest(FrameworkConstant.HOME_PAGE, request, response);
return;
}
// 去掉当前请求路径末尾的“/”
if (currentRequestPath.endsWith("/")) {
currentRequestPath = currentRequestPath.substring(0, currentRequestPath.length() - 1);
}
// 获取 Handler
Handler handler = handlerMapping.getHandler(currentRequestMethod, currentRequestPath);
// 若未找到 Action,则跳转到 404 页面
if (handler == null) {
WebUtil.sendError(HttpServletResponse.SC_NOT_FOUND, "", response);
return;
}
// 初始化 DataContext
DataContext.init(request, response);
try {
// 调用 Handler
handlerInvoker.invokeHandler(request, response, handler);
} catch (Exception e) {
// 处理 Action 异常
handlerExceptionResolver.resolveHandlerException(request, response, e);
} finally {
// 销毁 DataContext
DataContext.destroy();
}
}
/**
* Handles a CORS request of type {@link CORSRequestType}.SIMPLE.
*
* @param request The {@link HttpServletRequest} object.
* @param response The {@link HttpServletResponse} object.
* @param filterChain The {@link FilterChain} object.
* @throws IOException an IO error occurred
* @throws ServletException Servlet error propagation
* @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple
* Cross-Origin Request, Actual Request, and Redirects</a>
*/
protected void handleSimpleCORS(final HttpServletRequest request,
final HttpServletResponse response, final FilterChain filterChain)
throws IOException, ServletException {
CorsFilter.CORSRequestType requestType = checkRequestType(request);
if (!(requestType == CorsFilter.CORSRequestType.SIMPLE ||
requestType == CorsFilter.CORSRequestType.ACTUAL)) {
throw new IllegalArgumentException(
sm.getString("corsFilter.wrongType2",
CorsFilter.CORSRequestType.SIMPLE,
CorsFilter.CORSRequestType.ACTUAL));
}
final String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
final String method = request.getMethod();
// Section 6.1.2
if (!isOriginAllowed(origin)) {
handleInvalidCORS(request, response, filterChain);
return;
}
if (!allowedHttpMethods.contains(method)) {
handleInvalidCORS(request, response, filterChain);
return;
}
addStandardHeaders(request, response);
// Forward the request down the filter chain.
filterChain.doFilter(request, response);
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
RequestUserDTO httpConn = JwtService.getConnUser(httpServletRequest);
String userId = httpConn.getUserId();
String domainId = httpConn.getDomainID();
String clientIp = httpServletRequest.getRemoteAddr();
Integer statuCd = httpServletResponse.getStatus();
String method = httpServletRequest.getMethod();
String uri = httpServletRequest.getRequestURI();
Map<String, String[]> map = httpServletRequest.getParameterMap();
Map<String, String> dt = parseJSON(map);
String dtvalue = new GsonBuilder().create().toJson(dt);
jdbcTemplate.update(SqlDefine.sys_rdbms_207, userId, clientIp, statuCd, method, uri, dtvalue, domainId);
}
/**
*/
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
Tracing.setLogRequestInfo(LogRequestInfoFactory.createFrom(req));
final String method = req.getMethod();
try {
if (method.equals("GET")) {
doGet(req, resp);
} else {
super.service(req, resp);
}
} finally {
Tracing.clearLogRequestInfo();
}
}
/**
* No handler found -> set appropriate HTTP response status.
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception if preparing the response failed
*/
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + getRequestUri(request) +
"] in DispatcherServlet with name '" + getServletName() + "'");
}
if (this.throwExceptionIfNoHandlerFound) {
throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
new ServletServerHttpRequest(request).getHeaders());
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
@Override
public ModelAndView serve(final Repository repository, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
ModelAndView result;
String reqMethod = request.getMethod();
if (METHOD_GET.equals(reqMethod)) {
_logger.info("GET statements");
result = getExportStatementsResult(repository, request, response);
} else if (METHOD_HEAD.equals(reqMethod)) {
_logger.info("HEAD statements");
result = getExportStatementsResult(repository, request, response);
} else if (METHOD_POST.equals(reqMethod)) {
String mimeType = HttpServerUtil.getMIMEType(request.getContentType());
if (Protocol.TXN_MIME_TYPE.equals(mimeType)) {
_logger.info("POST transaction to repository");
result = getTransactionResultResult(repository, request, response);
} else if (request.getParameterMap().containsKey(Protocol.UPDATE_PARAM_NAME)) {
_logger.info("POST SPARQL update request to repository");
result = getSparqlUpdateResult(repository, request, response);
} else {
_logger.info("POST data to repository");
result = getAddDataResult(repository, request, response, false);
}
} else if ("PUT".equals(reqMethod)) {
_logger.info("PUT data in repository");
result = getAddDataResult(repository, request, response, false);
} else if ("DELETE".equals(reqMethod)) {
_logger.info("DELETE data from repository");
result = getDeleteDataResult(repository, request, response);
} else {
throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Method not allowed: "
+ reqMethod);
}
return result;
}
/**
* Check the given request for supported methods and a required session, if any.
* @param request current HTTP request
* @throws ServletException if the request cannot be handled because a check failed
* @since 4.2
*/
protected final void checkRequest(HttpServletRequest request) throws ServletException {
// Check whether we should support the request method.
String method = request.getMethod();
if (this.supportedMethods != null && !this.supportedMethods.contains(method)) {
throw new HttpRequestMethodNotSupportedException(method, this.supportedMethods);
}
// Check whether a session is required.
if (this.requireSession && request.getSession(false) == null) {
throw new HttpSessionRequiredException("Pre-existing session required but none found");
}
}
private boolean isSimpleRequest(final HttpServletRequest request) {
final String method = request.getMethod();
if (SIMPLE_HTTP_METHODS.contains(method)) {
return request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER) == null;
}
return false;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
Preconditions.checkState(!requestHandled);
String contentType = request.getContentType();
boolean isMultipart = contentType != null && contentType.startsWith("multipart/form-data");
if (isMultipart) {
// Use explicit multipart string as Request.__MULTIPART_CONFIG_ELEMENT was renamed to
// MULTIPART_CONFIG_ELEMENT in Jetty 9.4.20
request.setAttribute(
"org.eclipse.jetty.multipartConfig",
new MultipartConfigElement(System.getProperty("java.io.tmpdir")));
}
if (target.equals("/" + expectedPath)) {
requestHandled = true;
requestMethod = request.getMethod();
for (Enumeration<String> headers = request.getHeaderNames(); headers.hasMoreElements(); ) {
String header = headers.nextElement();
requestHeaders.put(header, request.getHeader(header));
}
if ("application/x-www-form-urlencoded".equals(contentType) || isMultipart) {
requestParameters = request.getParameterMap();
} else {
try (BufferedReader reader = request.getReader()) {
body = CharStreams.toString(reader);
}
}
baseRequest.setHandled(true);
response.getOutputStream().write(responseBytes);
response.setStatus(HttpServletResponse.SC_OK);
}
}
@Override
public void validateMethod(HttpServletRequest request) throws OAuthProblemException {
String method = request.getMethod();
if (!OAuth.HttpMethod.GET.equals(method) && !OAuth.HttpMethod.POST.equals(method)) {
throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST)
.description("Method not correct.");
}
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if(!request.getMethod().equals("POST")){
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = this.obtainUsername(request);
String password = this.obtainPassword(request);
//加盐
String sh1Password = password + "{" + username + "}";
PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
String result = passwordEncoder.encode(sh1Password);
log.info(result);
UserInfo userDetails = (UserInfo) userDetailsService.loadUserByUsername(username);
/*this.checkValidateCode(request);*/
if(!passwordEncoder.matches(userDetails.getPassword(), result) || "0".equals(userDetails.getEnabled()) || userDetails == null){
//System.out.println("用户名或密码错误!");
throw new AuthenticationServiceException("用户名或密码错误!");
}
if(!userDetails.getRolesName().contains("ROLE_ADMIN") && !userDetails.getRolesName().contains("ROLE_TEACHER")){
throw new AuthenticationServiceException("非管理用户,操作无效!");
}
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
this.setDetails(request, authRequest);
Authentication authentication = null;
try{
authentication = this.getAuthenticationManager().authenticate(authRequest);
}catch(Exception e){
e.printStackTrace();
}
return authentication;
}
/**
* 获取当前请求的 Http Method
* @return
*/
public static String getRequestHTTPMethod() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request.getMethod();
}
@RequestMapping("/**")
String index(HttpServletRequest request) {
String path = request.getRequestURI();
String method = request.getMethod();
return String.format("OK, path = %s, method = %s", path, method);
}
/**
* Handles the special Webdav methods
*/
protected void doDispatch(SakaidavServletInfo info, HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
{
String method = req.getMethod();
if (log.isDebugEnabled())
{
String path = getRelativePath(req);
log.debug("SAKAIDAV doDispatch [" + method + "] " + path);
}
String remoteUser = req.getRemoteUser();
if (log.isDebugEnabled()) log.debug("SAKAIDAV remoteuser = " + remoteUser);
if (remoteUser == null)
{
if (log.isDebugEnabled()) log.debug("SAKAIDAV Requires Authorization");
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
if (method.equals(METHOD_PROPFIND))
{
doPropfind(req, resp);
}
else if (method.equals(METHOD_PROPPATCH))
{
doProppatch(req, resp);
}
else if (method.equals(METHOD_MKCOL))
{
doMkcol(req, resp);
}
else if (method.equals(METHOD_COPY))
{
doCopy(req, resp);
}
else if (method.equals(METHOD_MOVE))
{
doMove(req, resp);
}
else if (method.equals(METHOD_LOCK))
{
doLock(req, resp);
}
else if (method.equals(METHOD_UNLOCK))
{
doUnlock(req, resp);
}
else if (method.equals(METHOD_GET))
{
doGet(req, resp);
}
else if (method.equals(METHOD_PUT))
{
doPut(req, resp);
}
else if (method.equals(METHOD_POST))
{
doPost(req, resp);
}
else if (method.equals(METHOD_HEAD))
{
doHead(req, resp);
}
else if (method.equals(METHOD_OPTIONS))
{
doOptions(req, resp);
}
else if (method.equals(METHOD_DELETE))
{
doDelete(req, resp);
}
else
{
log.warn("SAKAIDAV:Request not supported");
resp.sendError(SakaidavStatus.SC_NOT_IMPLEMENTED);
// showRequestInfo(req);
}
}
/**
* Determines the request type.
*
* @param request
*/
protected CORSRequestType checkRequestType(final HttpServletRequest request) {
CORSRequestType requestType = CORSRequestType.INVALID_CORS;
if (request == null) {
throw new IllegalArgumentException(
sm.getString("corsFilter.nullRequest"));
}
String originHeader = request.getHeader(REQUEST_HEADER_ORIGIN);
// Section 6.1.1 and Section 6.2.1
if (originHeader != null) {
if (originHeader.isEmpty()) {
requestType = CORSRequestType.INVALID_CORS;
} else if (!isValidOrigin(originHeader)) {
requestType = CORSRequestType.INVALID_CORS;
} else if (isLocalOrigin(request, originHeader)) {
return CORSRequestType.NOT_CORS;
} else {
String method = request.getMethod();
if (method != null) {
if ("OPTIONS".equals(method)) {
String accessControlRequestMethodHeader =
request.getHeader(
REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
if (accessControlRequestMethodHeader != null &&
!accessControlRequestMethodHeader.isEmpty()) {
requestType = CORSRequestType.PRE_FLIGHT;
} else if (accessControlRequestMethodHeader != null &&
accessControlRequestMethodHeader.isEmpty()) {
requestType = CORSRequestType.INVALID_CORS;
} else {
requestType = CORSRequestType.ACTUAL;
}
} else if ("GET".equals(method) || "HEAD".equals(method)) {
requestType = CORSRequestType.SIMPLE;
} else if ("POST".equals(method)) {
String mediaType = getMediaType(request.getContentType());
if (mediaType != null) {
if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
.contains(mediaType)) {
requestType = CORSRequestType.SIMPLE;
} else {
requestType = CORSRequestType.ACTUAL;
}
}
} else {
requestType = CORSRequestType.ACTUAL;
}
}
}
} else {
requestType = CORSRequestType.NOT_CORS;
}
return requestType;
}