📄 servletunithttprequest.java
字号:
/** * Returns the fully qualified name of the client that sent the * request. **/ public String getRemoteHost() { return "localhost"; } /** * Returns the host name of the server that received the request. **/ public String getServerName() { return "localhost"; } /** * Returns the port number on which this request was received. **/ public int getServerPort() { return 0; } /** * * @deprecated As of Version 2.1 of the Java Servlet API, * use {@link javax.servlet.ServletContext#getRealPath} instead. * */ public String getRealPath( String path ) { throwNotImplementedYet(); return ""; } /** * Returns the body of the request as a <code>BufferedReader</code> * that translates character set encodings. **/ public BufferedReader getReader() throws IOException { throwNotImplementedYet(); return null; } /** * Returns the Internet Protocol (IP) address of the client * that sent the request. **/ public String getRemoteAddr() { return LOOPBACK_ADDRESS; } /** * * Stores an attribute in the context of this request. * Attributes are reset between requests. **/ public void setAttribute( String key, Object o ) { if (o == null) _attributes.remove( key ); else _attributes.put( key, o ); }//--------------------------------- methods added to ServletRequest in Servlet API 2.2 ------------------------------------------------ /** * Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS. **/ public boolean isSecure() { return _secure; } /** * Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. * If the client request doesn't provide an Accept-Language header, this method returns the default locale for the server. **/ public Locale getLocale() { return (Locale) getPreferredLocales().firstElement(); } /** * Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, * the locales that are acceptable to the client based on the Accept-Language header. * If the client request doesn't provide an Accept-Language header, this * method returns an Enumeration containing one Locale, the default locale for the server. **/ public java.util.Enumeration getLocales() { return getPreferredLocales().elements(); } /** * Parses the accept-language header to obtain a vector of preferred locales * @return the preferred locales, sorted by qvalue */ private Vector getPreferredLocales() { if (_locales == null) { _locales = new Vector(); String languages = getHeader( "accept-language" ); if (languages == null) { _locales.add( Locale.getDefault() ); } else { StringTokenizer st = new StringTokenizer( languages, "," ); ArrayList al = new ArrayList(); while (st.hasMoreTokens()) { String token = st.nextToken(); al.add( new PrioritizedLocale( token ) ); } Collections.sort( al ); for (Iterator iterator = al.iterator(); iterator.hasNext();) { _locales.add( ((PrioritizedLocale) iterator.next()).getLocale() ); } } } return _locales; } /** * Removes an attribute from this request. This method is not generally needed * as attributes only persist as long as the request is being handled. **/ public void removeAttribute( String name ) { _attributes.remove( name ); } /** * Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. * A RequestDispatcher object can be used to forward a request to the resource or to include the * resource in a response. The resource can be dynamic or static. * * The pathname specified may be relative, although it cannot extend outside the current servlet * context. If the path begins with a "/" it is interpreted as relative to the current context root. * This method returns null if the servlet container cannot return a RequestDispatcher. * * The difference between this method and ServletContext.getRequestDispatcher(java.lang.String) * is that this method can take a relative path. **/ public RequestDispatcher getRequestDispatcher( String path ) { try { if (!path.startsWith( "/" )) path = combinedPath( getServletPath(), path ); return _servletRequest.getServlet().getServletConfig().getServletContext().getRequestDispatcher( path ); } catch (ServletException e) { return null; } } private String combinedPath( String basePath, String relativePath ) { if (basePath.indexOf( '/' ) < 0) return relativePath; return basePath.substring( 0, basePath.lastIndexOf( '/' ) ) + '/' + relativePath; }//--------------------------------- methods added to HttpServletRequest in Servlet API 2.2 ------------------------------------------------ /** * Returns a java.security.Principal object containing the name of the current authenticated user. * If the user has not been authenticated, the method returns null. **/ public java.security.Principal getUserPrincipal() { return null; } /** * Returns a boolean indicating whether the authenticated user is included in the specified * logical "role". Roles and role membership can be defined using deployment descriptors. * If the user has not been authenticated, the method returns false. **/ public boolean isUserInRole( String role ) { if (_roles == null) return false; for (int i = 0; i < _roles.length; i++) { if (role.equals( _roles[i] )) return true; } return false; } /** * Returns all the values of the specified request header as an Enumeration of String objects. **/ public java.util.Enumeration getHeaders( String name ) { Vector list = new Vector(); if (_headers.containsKey( name )) list.add( _headers.get( name )); return list.elements(); } /** * Returns the portion of the request URI that indicates the context of the request. * The context path always comes first in a request URI. The path starts with a "/" character * but does not end with a "/" character. For servlets in the default (root) context, * this method returns "". **/ public String getContextPath() { return _context.getContextPath(); }//--------------------------------------- methods added to ServletRequest in Servlet API 2.3 ---------------------------- /** * Returns a java.util.Map of the parameters of this request. * Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained * in the query string or posted form data. * * @since 1.3 **/ public Map getParameterMap() { return _requestContext.getParameterMap(); } /** * Overrides the name of the character encoding used in the body of this request. * This method must be called prior to reading request parameters or reading input using getReader(). * * @since 1.3 **/ public void setCharacterEncoding( String charset ) throws UnsupportedEncodingException { _charset = charset; _requestContext.setMessageEncoding( charset ); }//--------------------------------------- methods added to HttpServletRequest in Servlet API 2.3 ---------------------------- /** * Reconstructs the URL the client used to make the request. * The returned URL contains a protocol, server name, port number, and server path, but * it does not include query string parameters. * * Because this method returns a StringBuffer, not a string, you can modify the URL easily, for example, * to append query parameters. * * This method is useful for creating redirect messages and for reporting errors. * * @since 1.3 */ public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); try { url.append( _request.getURL().getProtocol() ).append( "://" ); url.append( _request.getURL().getHost() ); url.append( _request.getURL().getPath() ); } catch (MalformedURLException e) { throw new RuntimeException( "unable to read URL from request: " + _request ); } return url; }//--------------------------------------- methods added to ServletRequest in Servlet API 2.4 ---------------------------- public int getRemotePort() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public String getLocalName() { return "localhost"; } public String getLocalAddr() { return "127.0.0.1"; } public int getLocalPort() { return 0; //To change body of implemented methods use File | Settings | File Templates. }//--------------------------------------------- package members ---------------------------------------------- private void addCookie( Cookie cookie ) { _cookies.addElement( cookie ); if (cookie.getName().equalsIgnoreCase( ServletUnitHttpSession.SESSION_COOKIE_NAME )) { _sessionID = cookie.getValue(); } } private ServletUnitHttpSession getServletSession() { return (ServletUnitHttpSession) getSession(); } void readFormAuthentication() { if (getSession( /* create */ false ) != null) { recordAuthenticationInfo( getServletSession().getUserName(), getServletSession().getRoles() ); } } void readBasicAuthentication() { String authorizationHeader = (String) _headers.get( "Authorization" ); if (authorizationHeader != null) { String userAndPassword = Base64.decode( authorizationHeader.substring( authorizationHeader.indexOf( ' ' ) + 1 ) ); int colonPos = userAndPassword.indexOf( ':' ); recordAuthenticationInfo( userAndPassword.substring( 0, colonPos ), toArray( userAndPassword.substring( colonPos+1 ) ) ); } } static String[] toArray( String roleList ) { StringTokenizer st = new StringTokenizer( roleList, "," ); String[] result = new String[ st.countTokens() ]; for (int i = 0; i < result.length; i++) { result[i] = st.nextToken(); } return result; } void recordAuthenticationInfo( String userName, String[] roles ) { _userName = userName; _roles = roles; }//--------------------------------------------- private members ---------------------------------------------- final static private String LOOPBACK_ADDRESS = "127.0.0.1"; private WebRequest _request; private ServletMetaData _servletRequest; private WebClient.HeaderDictionary _headers; private ServletUnitContext _context; private ServletUnitHttpSession _session; private Hashtable _attributes = new Hashtable(); private Vector _cookies = new Vector(); private String _sessionID; private byte[] _messageBody; private String _userName; private String[] _roles; private void throwNotImplementedYet() { throw new RuntimeException( "Not implemented yet" ); } private void setCookiesFromHeader( Dictionary clientHeaders ) { String cookieHeader = (String) clientHeaders.get( "Cookie" ); if (cookieHeader == null) return; StringTokenizer st = new StringTokenizer( cookieHeader, ",;=", true ); String lastToken = st.nextToken(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equals( "=" )) { if (st.hasMoreTokens()) addCookie( new Cookie( lastToken.trim(), st.nextToken().trim() ) ); } lastToken = token; } } static class PrioritizedLocale implements Comparable { private Locale _locale; private float _priority; PrioritizedLocale( String languageSpec ) { int semiIndex = languageSpec.indexOf( ';' ); if (semiIndex < 0) { _priority = 1; _locale = parseLocale( languageSpec ); } else { _priority = Float.parseFloat( languageSpec.substring( languageSpec.indexOf( '=', semiIndex )+1 ) ); _locale = parseLocale( languageSpec.substring( 0, semiIndex ) ); } } private Locale parseLocale( String range ) { range = range.trim(); int dashIndex = range.indexOf( '-' ); if (dashIndex < 0) { return new Locale( range, "" ); } else { return new Locale( range.substring( 0, dashIndex ), range.substring( dashIndex+1 ) ); } } public Locale getLocale() { return _locale; } public int compareTo( Object o ) { if (!(o instanceof PrioritizedLocale)) throw new IllegalArgumentException( "may only combine with other prioritized locales" ); PrioritizedLocale other = (PrioritizedLocale) o; return _priority == other._priority ? _locale.getLanguage().compareTo( other._locale.getLanguage() ) : (_priority < other._priority ? +1 : -1 ); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -