下面列出了javax.servlet.http.HttpServletRequest#getServletPath() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 匿名访问地址(不用登陆,直接访问.)
*
* @param request
* @return
*/
private boolean isIgnore(HttpServletRequest request) {
String uri = request.getServletPath();
System.out.println("isIgnore()中输出:" + uri);
String[] ignorePatterns = ignorePattern.split("\\|");
for (String pattern : ignorePatterns) {
if (pattern.indexOf("*") < 0) {
if (uri.equals(pattern)) {
return true;
}
} else if (pattern.startsWith("*")) {
pattern = pattern.replace("*", "");
if (uri.endsWith(pattern)) {
return true;
}
} else if (pattern.endsWith("*")) {
pattern = pattern.replace("*", "");
if (uri.startsWith(pattern)) {
return true;
}
}
}
return false;
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
//shiro管理的session
Session session = ShiroUtil.getSession();
User user = (User)session.getAttribute(Constant.SESSION_USER);
if(user!=null){
//System.out.println(path);//path例如:/WEB-INF/html/main.html
boolean b = ShiroUtil.hasJurisdiction(path);
if(!b){
response.sendRedirect(request.getContextPath() + Constant.LOGIN);
}
return b;
}else{
//登陆过滤
response.sendRedirect(request.getContextPath() + Constant.LOGIN);
return false;
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AsyncContext ac = req.startAsync();
// Quick and dirty. Sufficient for this test but ignores lots of
// edge cases.
String target = null;
if (dispatchPath != null) {
target = req.getServletPath();
int lastSlash = target.lastIndexOf('/');
target = target.substring(0, lastSlash + 1);
if (encodePath) {
target = URLEncoder.DEFAULT.encode(target, StandardCharsets.UTF_8);
}
target += dispatchPath;
}
try {
ac.dispatch(target);
} catch (UnsupportedOperationException uoe) {
ac.complete();
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print(NULL);
}
}
@GET
@Path("{id:.*}")
public Response service(@Context HttpServletRequest req, @Context HttpServletResponse resp) {
String requestMapping = req.getContextPath() + req.getServletPath() + "/DemoService.svc";
req.setAttribute("requestMapping", requestMapping);
// create odata handler and configure it with EdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(),
new ArrayList<EdmxReference>());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new DemoEntityCollectionProcessor());
// let the handler do the work
handler.process(req, resp);
return Response.ok().build();
}
/**
* Determines the prefix for standard directory GET listings.
*/
@Override
protected String getPathPrefix(final HttpServletRequest request) {
// Repeat the servlet path (e.g. /webdav/) in the listing path
String contextPath = request.getContextPath();
if (request.getServletPath() != null) {
contextPath = contextPath + request.getServletPath();
}
return contextPath;
}
/**
* This finds the correct servlet path or returns the default one,
* will not return "" or null
* @param req the incoming request
* @return the servlet context path (/ + servletName)
*/
public static String getServletContext(HttpServletRequest req) {
String context = null;
if (req != null) {
context = req.getContextPath();
if ("".equals(context)) {
context = req.getServletPath();
}
}
if (context == null || "".equals(context)) {
context = EntityView.DIRECT_PREFIX;
}
return context;
}
/**
* Make a redirect to the login url.
*
* @param req
* HttpServletRequest object with the client request.
* @param res
* HttpServletResponse object back to the client.
* @param path
* The current request path, set ONLY if we want this to be where to redirect the user after successfull login
* @throws IOException
*/
protected void doLogin(HttpServletRequest req, HttpServletResponse res, String path) throws ToolException, IOException
{
// if basic auth is valid do that
if ( basicAuth.doAuth(req,res) ) {
log.info("BASIC Auth Request Sent to the Browser ");
return;
}
// if there is a Range: header for partial content and we haven't done basic auth, refuse the request (SAK-23678)
if (req.getHeader("Range") != null) {
sendError(res, HttpServletResponse.SC_FORBIDDEN);
return;
}
// get the Sakai session
Session session = sessionManager.getCurrentSession();
// set the return path for after login if needed (Note: in session, not tool session, special for Login helper)
if (path != null)
{
// where to go after
session.setAttribute(Tool.HELPER_DONE_URL, Web.returnUrl(req, formattedText.escapeUrl(path)));
}
// check that we have a return path set; might have been done earlier
if (session.getAttribute(Tool.HELPER_DONE_URL) == null)
{
log.warn("doLogin - proceeding with null HELPER_DONE_URL");
}
// map the request to the helper, leaving the path after ".../options" for the helper
ActiveTool tool = activeToolManager.getActiveTool("sakai.login");
String context = req.getContextPath() + req.getServletPath() + "/login";
tool.help(req, res, context, "/login");
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String appId = accessKeyUtil.extractAppIdFromRequest(request);
if (StringUtils.isBlank(appId)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId");
return;
}
List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId);
if (!CollectionUtils.isEmpty(availableSecrets)) {
String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP);
String authorization = request.getHeader(Signature.HTTP_HEADER_AUTHORIZATION);
// check timestamp, valid within 1 minute
if (!checkTimestamp(timestamp)) {
logger.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed");
return;
}
// check signature
String path = request.getServletPath();
String query = request.getQueryString();
if (!checkAuthorization(authorization, availableSecrets, timestamp, path, query)) {
logger.warn("Invalid authorization. appId={},authorization={}", appId, authorization);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return;
}
}
chain.doFilter(request, response);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
if (!Constants.JOBX_CLUSTER) {
chain.doFilter(request, response);
} else {
if (sessionStore == null) {
sessionStore = new HttpSessionStore();
}
String requestURI = request.getContextPath() + request.getServletPath();
//过滤静态资源
if (requestURI.startsWith("/static/") || requestURI.startsWith("/favicon.ico")) {
chain.doFilter(request, response);
return;
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
Cookie sessionIdCookie = getOrGenerateSessionId(request, response);
String sessionId = sessionIdCookie.getValue();
HttpSession rawSession = request.getSession();
Map sessionData = loadSessionData(sessionId);
try {
HttpSession sessionWrapper = new HttpSessionStoreWrapper(sessionStore, rawSession, sessionId, sessionData);
chain.doFilter(new HttpServletRequestSessionWrapper(request, sessionWrapper), response);
} finally {
sessionStore.setSession(sessionId, sessionData);
}
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
String view = processRequest(servletPath, request);
if (view != null) {
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
}
/**
* Determines the prefix for standard directory GET listings.
*/
@Override
protected String getPathPrefix(final HttpServletRequest request) {
// Repeat the servlet path (e.g. /webdav/) in the listing path
String contextPath = request.getContextPath();
if (request.getServletPath() != null) {
contextPath = contextPath + request.getServletPath();
}
return contextPath;
}
/**
* 获取当前用户登录的权限
* @param req
* @return
*/
public String[] getPermissions(ServletRequest req) {
String[] permissions = new String[1];
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getServletPath();
permissions[0] = path;
return permissions;
}
@Override
protected Serializable doCreate(Session session) {
HttpServletRequest request = Servlets.getRequest();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不创建SESSION
if (Servlets.isStaticFile(uri)){
return null;
}
}
super.doCreate(session);
logger.debug("doCreate {} {}", session, request != null ? request.getRequestURI() : "");
return session.getId();
}
/**
* Setup for a helper tool - all subsequent requests will be directed there, till the tool is done.
*
* @param helperId
* The helper tool id.
*/
protected void startHelper(HttpServletRequest req, String helperId, String panel)
{
if (panel == null) panel = MAIN_PANEL;
ToolSession toolSession = SessionManager.getCurrentToolSession();
toolSession.setAttribute(HELPER_ID + panel, helperId);
// the done URL - this url and the extra parameter to indicate done
// also make sure the panel is indicated - assume that it needs to be main, assuming that helpers are taking over the entire tool response
String doneUrl = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "?"
+ HELPER_ID + panel + "=done" + "&" + ActionURL.PARAM_PANEL + "=" + panel;
toolSession.setAttribute(helperId + Tool.HELPER_DONE_URL, doneUrl);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// This filter only needs to handle WebSocket upgrade requests
if (!sc.areEndpointsRegistered() ||
!UpgradeUtil.isWebSocketUpgradeRequest(request, response)) {
chain.doFilter(request, response);
return;
}
// HTTP request with an upgrade header for WebSocket present
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// Check to see if this WebSocket implementation has a matching mapping
String path;
String pathInfo = req.getPathInfo();
if (pathInfo == null) {
path = req.getServletPath();
} else {
path = req.getServletPath() + pathInfo;
}
WsMappingResult mappingResult = sc.findMapping(path);
if (mappingResult == null) {
// No endpoint registered for the requested path. Let the
// application handle it (it might redirect or forward for example)
chain.doFilter(request, response);
return;
}
UpgradeUtil.doUpgrade(sc, req, resp, mappingResult.getConfig(),
mappingResult.getPathParams());
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
if (xsrfPreventionFilterDisabled) {
chain.doFilter(req, resp);
return;
}
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String method = request.getMethod();
String path = request.getServletPath();
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
if (LOG.isDebugEnabled()) {
LOG.debug(MessageFormat.format("Filter called for {0} {1}. ", method, path));
}
// check if nonce should be generated
CookieHandler ch = new CookieHandler(request.getCookies(), XSRF_TOKEN);
if (isEntryPoint(req, path) && !ch.hasNonceCookie()) {
response.addCookie(new Cookie(XSRF_TOKEN, generateNonce(method, path)));
}
boolean doNonceCheck = !"get".equalsIgnoreCase(method) && !isException(req, path);//$NON-NLS-1$
if (doNonceCheck) {
String requestNonce = request.getHeader(XSRF_TOKEN);
boolean nonceValid = checkNonce(method, path, ch, requestNonce);
if (!nonceValid) {
logReasonForInvalidNonce(request, method, path, ch, requestNonce);
prepareResponseForInvalidNonce(response);
return;
}
} else if (LOG.isDebugEnabled()) {
LOG.debug(MessageFormat.format("Skipping nonce check for {0} {1}", method, path));
}
chain.doFilter(request, response);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse res = (HttpServletResponse) servletResponse;
if (ldapAuthModeNum >= LDAP_AUTH_MODE_SIMPLE) {
String path = req.getServletPath();
if (hasAllowedExtension(path)) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
if ("/rest-public".equals(path)) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
if ("/rest".equals(path)) {
String info = req.getPathInfo();
if (info != null) {
path = path + info;
int i = ordinalIndexOf(path, "/", 2);
if (i > 0) {
path = path.substring(0, i);
}
}
}
boolean allowedObserverPath = isAllowedPath(path, allowedObserverPaths);
boolean allowedDataAdminPath = false;
boolean allowedTesterPath = false;
String authorizePathMode = null;
if (ldapAuthModeNum >= LDAP_AUTH_MODE_FULL) {
allowedDataAdminPath = isAllowedPath(path, allowedDataAdminPaths);
allowedTesterPath = isAllowedPath(path, allowedTesterPaths);
if (allowedObserverPath) {
authorizePathMode = AUTH_PATH_MODE_OBSERVER;
} else if (allowedDataAdminPath) {
authorizePathMode = AUTH_PATH_MODE_DATAADMIN;
} else if (allowedTesterPath) {
authorizePathMode = AUTH_PATH_MODE_TESTER;
}
}
if (allowedObserverPath || allowedDataAdminPath || allowedTesterPath) {
if (ldapAuthModeNum >= LDAP_AUTH_MODE_BASIC) {
String authenticated = askUsername(req, res, authorizePathMode);
if (authenticated == null) {
res.getWriter().write("<html>Not Allowed (" + path + ")</html>");
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
} else {
res.getWriter().write("<html>Not Allowed (" + path + ")</html>");
}
}
}
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
private void log(HttpServletRequest request) {
String path = request.getServletPath();
log.info("GET " + path);
}
/**
* Process a GET request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
StringManager smClient = StringManager.getManager(
Constants.Package, request.getLocales());
// Identify the request parameters that we need
String command = request.getPathInfo();
if (command == null)
command = request.getServletPath();
String name = request.getParameter("name");
// Prepare our output writer to generate the response message
response.setContentType("text/plain; charset=" + Constants.CHARSET);
PrintWriter writer = response.getWriter();
// Process the requested command
if (command == null) {
writer.println(sm.getString("hostManagerServlet.noCommand"));
} else if (command.equals("/add")) {
add(request, writer, name, false, smClient);
} else if (command.equals("/remove")) {
remove(writer, name, smClient);
} else if (command.equals("/list")) {
list(writer, smClient);
} else if (command.equals("/start")) {
start(writer, name, smClient);
} else if (command.equals("/stop")) {
stop(writer, name, smClient);
} else {
writer.println(sm.getString("hostManagerServlet.unknownCommand",
command));
}
// Finish up the response
writer.flush();
writer.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Segment requested");
// get red5 context and segmenter
if (service == null) {
ApplicationContext appCtx = (ApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
service = (SegmenterService) appCtx.getBean("segmenter.service");
}
//get the requested stream / segment
String servletPath = request.getServletPath();
String[] path = servletPath.split("\\.");
log.trace("Path parts: {}", path.length);
//fail if they request the same segment
HttpSession session = ((HttpServletRequest) request).getSession(false);
if (session != null) {
String stream = (String) session.getAttribute("stream");
if (path[0].equals(stream)) {
log.info("Segment {} was already played by this requester", stream);
return;
}
session.setAttribute("stream", path[0]);
}
// look for underscore char
int digitIndex = path[0].lastIndexOf('_') + 1;
String streamName = path[0].substring(1, digitIndex - 1);
int sequenceNumber = Integer.valueOf(path[0].substring(digitIndex));
log.debug("Stream name: {} sequence: {}", streamName, sequenceNumber);
if (service.isAvailable(streamName)) {
response.setContentType("video/MP2T");
Segment segment = service.getSegment(streamName, sequenceNumber);
if (segment != null) {
byte[] buf = new byte[188];
ByteBuffer buffer = ByteBuffer.allocate(188);
ServletOutputStream sos = response.getOutputStream();
do {
buffer = segment.read(buffer);
//log.trace("Limit - position: {}", (buffer.limit() - buffer.position()));
if ((buffer.limit() - buffer.position()) == 188) {
buffer.get(buf);
//write down the output stream
sos.write(buf);
} else {
log.info("Segment result has indicated a problem");
// verifies the currently requested stream segment number against the currently active segment
if (service.getSegment(streamName, sequenceNumber) == null) {
log.debug("Requested segment is no longer available");
break;
}
}
buffer.clear();
} while (segment.hasMoreData());
log.trace("Segment {} had no more data", segment.getIndex());
buffer = null;
// flush
sos.flush();
// segment had no more data
segment.cleanupThreadLocal();
} else {
log.info("Segment for {} was not found", streamName);
}
} else {
//TODO let requester know that stream segment is not available
response.sendError(404, "Segment not found");
}
}