jakartaee / servlet Goto Github PK
View Code? Open in Web Editor NEWJakarta Servlet
Home Page: https://eclipse.org/ee4j/servlet
License: Other
Jakarta Servlet
Home Page: https://eclipse.org/ee4j/servlet
License: Other
Web.xml can be programmatically created using Servlet 3.0. But features like , < session-timeout> still needs to be configured in a web.xml.Can you provide a way to programmatically create these as well? Especially, error-page configuration.
As discussed in the mailing list[1] a suggestion on how to extend the current api to expose information about the underlying connectors/sockets.
This is just the first idea that came into my head. Please suggest better ideas if you can think of any. Since I was just targeting to expose something like the https port to the application, I did't thought of better changes.
public interface ServletContext {
// existing members
public Set getConnectors();
}
public interface ServletConnector{
public int getPort();
public String getProtocol();
public boolean isSecure();
}
[1] http://java.net/projects/servlet-spec/lists/users/archive/2012-08/message/7
In section of 3.2 of Servlet 3.0 spec, servlet container process multipart/form-data for file uploaded when @MultipartConfig is annotated with the corresponding servlet.
This is not correct as one also need to consider the multipart-config element in web.xml.
The design and implementation of SerlvetInputStream.readLine has some design and implementation problems.
Firstly it is a strange method to have on a byte input stream, as a "line" may have no meaning or different meanings depending on content type. Many content types will not have the concept of a line, so this method will just strangely search for a \n byte. Other content types such as EBCDIC or UCS-2 may have different meanings of a \n byte, which still having the concept of a line.
Also, even with ASCII, UTF-8 text, lines may be terminated by \r, \r\n or just \n. Currently the implementation of this method will ignore \r and will return the \r in a \r\n sequence as part of the line.
The implementation is also not very efficient as it reads a single byte at a time.
Considering that this functionality is safely provided by BufferedReader, I believe that we should deprecate readLine - but also improve it's specification and implementation to:
servlet 3.0
The Javadoc for sendRedirect() is quite clear that a URL starting with '/' should be treated as relative to the server root. However, that precludes the use of protocol relative URLs that start with '//'. See [1] for details of why these might be useful. While there are clearly arguments for and against protocol relative URLs, I don't think we should preclude their use and therefore the Javadoc for sendRedirect should be amended to allow for them.
[1] http://blog.httpwatch.com/2010/02/10/using-protocol-relative-urls-to-switch-between-http-and-https/
In Section 8.1.1 of Servlet 3.0, we have the following:
If the same servlet class is declared in the deployment descriptor under a different name, a new instance of the servlet MUST be instantiated. If the same servlet class is added to the ServletContext via the programmatic API defined in Section 4.4.1, "Programmatically adding and configuring Servlets" on page 4-31 the values declared via the @WebServlet annotation MUST be ignored and a new instance of the servlet with the name specified MUST be created.
Both sentence should referred to adding the same servlet class with the "different name".
So, the second sentence should be modified as follows:
If the same servlet class is added with the different name to the ServletContext via the programmatic API defined in Section 4.4.1, "Programmatically adding and configuring Servlets" on page 4-31, the attribute values declared via the @WebServlet annotation MUST be ignored and a new instance of the servlet with the name specified MUST be created.
See:
https://issues.apache.org/bugzilla/show_bug.cgi?id=52135
http://stackoverflow.com/questions/12854768/jetty-servlet-3-0-and-error-page
It appears the jsr315 spec group may have wanted to make a new feature of having error-pages without defining a code or exception name. Unfortunately there is no text about this in the 3.0 final specification. See section 10.9.2 Error Pages. This is not mentioned.
Nor is there any comment in the web-common.xsd schema.
The only information on this feature can be found on a blog from someone from oracle:
https://blogs.oracle.com/arungupta/entry/totd_136_default_error_page
If this is indeed a new feature that was added in servlet 3.0, this must be documented in the specification.
Jan
The specification is unclear for some or all of the above methods how the following should be handled.
It is possible to create an infinite loop within an application if a wrapper is passed to its own ServletRequestWrapper.setRequest() method. The same problem can occur with ServletResponseWrapper and the HTTP variants.
It would be helpful if the spec required that this was not permitted. The check should probably go further and check for loops (A wraps B wraps C wraps A).
Currently there are significant ambiguities in the servlet specification with regards to how sessions should be distributed:
should changes made to the attibute value objects after the setAttribute be reflected in the persisted/distributed state? Is setAttribute pass-by-reference or pass-by-value ?
when is a session attribute persisted/distributed? When setAttribute is called? when the current request completes? when all simultaneous requests complete? at regular intervals? on container shutdown?
the requirement that only a single instance of a session is active in a cluster is difficult to efficiently implement. Can concurrent instances be allowed?
are sessions persisted/serialized attribute by attribute or as a single session blob?
There are a range of status codes that a developer might want to use with sendRedirect (302,303,307). Currently, sendRedirect() always issues 302s. It would be helpful to extend the API to allow the developer to control which status code is used.
Section 12.1 states that prefix mapping is done by stepping down the path tree on directory at a time. However, given a path "/foo/", it does not mention how to deal with the trailing "/". This is significant given that "/foo" (no trailing slash) matches "/foo/" as shown later in that chapter (which is a bit confusing if "/" is naively converted in to a regexp).
The use of "/" with the intended semantics is somewhat misleading since it can match any number of paths, including zero. Ant uses "*" to match arbitrary number of directories (including none). IMO, a better syntax for servlet mapping would be:
/.../* => /.../** (path prefix)
(ii) .ext => /****/.ext (extension mapping)
For example,
(1) match(/a/, /a/b/c/d) = (/a, /b/c/d)
(2) match(/a/, /a) = (/a, null) (since ** matches 0 directories)
and
(3) match(/*/.ext, /a/b/c.ext) = (/a/b/c.ext, null)
Changing the syntax would obviously be backward incompatible, but perhaps an alternate syntax could be consider in future revisions of the spec.
If a filter modifies the response body it may cause problems for a servlet if the servlets set a content length or respond correctly to range requests.
The specification currently implies that wrapping the response is necessary if the response body is modified. This issue requests that filters that modify the response body are required to correctly handle (which will almost certainly mean wrapping the response) range requests and the content-length of the response.
There is no notification event for client close.
Is it possible to add AsyncListener#onClose() when the client is disconnected ? This will be
useful for long running connections like server-sent events connection.
On the other hand, SE socket API itself doesn't provide that option. So there may be no way to get client close notification when there is no pending i/o.
IDEs often unpack JAR files into the classes directory. This breaks the static resources from JAR files feature of Servlet 3.0. Allowing static resources to be read from the classes dir would address this.
Servlet Spec 3.0 does not make clear what relationship exists between metadata-complete setting in web.xml and the discovering and invocation of ServletContainerInitializers.
The stated purpose of ServletContainerInitializers is to allow for pluggable framework initialization, and the given example is initializing the JSP container. This implies that a setting of metadata-complete=true is irrelevant to the finding and calling of ServletContainerInitializers.
If so, even if metata-complete==true for a given webapp, then we are forced to scan every class available to the webapp in the case that a discovered ServletContainerInitializer has a @HandlesTypes annotation - if the HandlesTypes specifies an annotation, then we will scan every class for that annotation, or if HandlesTypes specifies a class, then we need to scan for that class and its descendants. This can take a significant amount of time for a webapp with a large number of jars in WEB-INF/lib.
Please clarify if this is correct, or if metatadata-complete==true means that all ServletContainerInitializers are ignored.
The specification is not explicit regarding the order of welcome file processing and filter mapping. This has caused limited user confusion.
My own expectation is that welcome files are processed first and then filter mappings. Previous conversations with Servlet 3.0 EG members confirmed this. It would be help to get a short note of this added to the Servlet 3.1 spec.
Title says it all. This looks like an oversight in the original ServletRegistration API.
The Javadoc for HttpServletResponse#encodeURL() states that "The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL."
The Javadoc gives one example of a test. Another possible test that may be performed is "Is the URL part of the web application?". If it is not, the session ID does not need to be encoded in the URL.
That highlights the question of how relative URLs should be treated. The options I see are:
a) relative URLs are always assumed to be part of the web application
b) relative URLs are always relative the current HttpServletRequest
c) container specific
d) something else
My current expectation is that b) is the intended behaviour and that it was not explicitly stated since it was viewed as the only possible option. It would be helpful of this expectation could be confirmed or denied and either way if a clarification could be added to the Javadoc for 3.1 onwards (and earlier versions where possible).
Note the same issue exists for encodeRedirectURL()
This question was triggered by https://issues.apache.org/bugzilla/show_bug.cgi?id=53469
Section 9.7.2 describes a set of request attributes that contain the path values of the original request, so that they may be accessed by a servlet called as a result of a AsyncContext.dispatch(...)
However, this implies that these attributes are only set after a AsyncContext.dispatch(...), which means that they are not available to a thread that might be acting as part of a startAsync().... AsyncContext.complete() pattern.
Note that a thread cannot access the original request paths via AsyncContext.getRequest().getServletPath() because the value returned from that can be affected by forwards that happen before and/or after the startAsync call, or even a forward after an async dispatch. The path methods are inherently volatile.
I think that the ASYNC request parameters should be set when startAsync is called, so that those values are available for the entire async life cycle and not only during async dispatch.
If the ServletContext passed to the ServletContextListener's
contextInitialized method was neither declared in web.xml or
webfragment.xml nor annotated with @weblistener then an
UnsupportedOperationException MUST be thrown for all the
methods defined for programmatic configuration of servlets,
filters and listeners.
This sentence is misleading; leaving out the relative clause gives:
If the ServletContext was neither declared in web.xml or webfragment.xml nor annotated with @weblistener [...]
The ServletContext is created by the Servlet container and can neither be declared in web.xml or webfragment nor annotated, but the ServletListenerContext can be. So, if
neither declared in web.xml or webfragment.xml nor annotated with @weblistener
refers to ServletContextListener, please make that clear.
Still, I don't understand, why and when an UnsupportedOperationException must be thrown. Must it be thrown when that ServletContextListener is added via ServletContext#addListener? What sense would it make to throw an exception here? If that listener had been declared in web.xml or webfragment.xml or annotated, there would be no need to add it programmatically in the first place.
Servlets currently support the @Runas and @DeclareRoles from the common security annotations defined in JSR 250. Missing is the @RolesAllowed annotation.
I would like to propose supporting the @RolesAllowed annotation on Servlets for the following reasons:
To facilitate a graceful shutdown of resources that does not rely on GC (which may not happen for some time) it would be helpful if there was a way to signal to JNDI resources that they were no longer required.
The suggestion is that on application stop, the resource is checked for a zero argument close() method and that this method is called if it is present.
EDR text, section 2.3.3.3 pg 11:
"Dispatching from a synchronous servlet to an asynchronous servlet would be illegal.
However the decision of throwing an IllegalStateException is differed to the
point when the application calls startAsync. This would allow a servlet to either
function as a synchronous or an asynchronous servlet."
I think "differed" should be "deferred".
Currently no validation is required when setting a response HTTP header or value. Should the specification require that invalid values are rejected? Should the specification provide a mechanism for escaping header names and values? What about values that cannot be escaped such as UTF-8 values?
If an url pattern is not covered by security-constraint, then the default behavior is "permit all".
One would like to configure the default behavior to be "deny all".
In javadoc of javax.servlet.AsyncContext#dispatch(), we have
...
getRequestDispatcher("/url/B").forward(request,response);
...
getRequestDispatcher("/url/B").forward(request,response);
It should be
request.getRequestDispatcher("/url/B").forward(request,response);
or
servletContext.getRequestDispatcher("/url/B").forward(request,response);
In p.15 of spec pdf file, there is a similar issue.
Also, one may like to add "//" for comment and additional information from javadoc.
While the pluggability support in Servlet 3.0 was a great improvement, I do still find it to be a somewhat limited. In 3.0, all resources have to be bundled inside META-INF/resources in a jar in WEB-INF/lib in the deployed war. I think this is a bit rigid and that we would benefit from adding more flexibility in how resources can be loaded.
I suggest adding a provider interface to the servlet API which will allow implementors to load resources from arbitrary locations. That could be the file system, the network, OSGi bundles, the classpath, some generated in-memory representation or any other source which can locate and load resources.
How would this be useful? Our particular use case is to support plugin based architectures on the Servlet/JSP platform. For these kinds of applications, it it desirable to distribute apps and plugins independently. It is inconvenient having to reassemble the application war file just to add or upgrade a plugin. It should be possible to add it simply by dropping it in a folder. In the same way, would like to add and remove plugins at runtime. Both of these requirements are impossible to implement with Servlet 3.0, but should be easy to implement with the proposed API.
Other use cases that comes to mind might be: sharing of resources across contexts, loading resources from source during development and being able to separate downloadable application data from the application itself.
Also note that the current Servlet 3.0 way of loading resources from /META-INF/resources on the classpath could be implemented as a resource loader in the suggested design. Likewise, the normal resource loading from the war file could also be modeled as a resource loader. So in a way, we already have multiple ways of loading resources, we just don't have a well defined name and concept around it that people can use. (Or rather framework developers, I don't see this as something the average developer will commonly have to deal with directly, they'll probably use a framework/library which supports it)
For the purpose of discussion, I'll throw out an initial design idea here:
package javax.servlet.ResourceLoader;
interface ResourceLoader {
URL getResource(String path);
Set getResourcePaths(String path);
InputStream getResourceAsStream(String path);
}
(The methods will behave similar to their cousins in javax.servlet.ServletContext, just being scoped to a single ResourceLoader. "path" is the path being looked up.)
New method addResourceLoader(ResourceLoader resourceLoader) in javax.servlet.ServletContext which will register a ResourceLoader for use in the servlet context.
New web.xml / web-fragment.xml syntax:
I'm very interested in hearing objections, ideas for alternative/improved/simpler designs, security concerns or other considerations. There's probably no shortage of things I haven't thought about
See https://issues.apache.org/bugzilla/show_bug.cgi?id=49779 for an example of why this would be useful.
From javadoc, ServletResponse#reset will clear any data that exists in the buffer as well as the status code and headers. If the response has been committed, this method throws an IllegalStateException.
Once the headers are cleared, so is the charset in Content-Type.
If the getWriter() is already called, then according to javadoc of ServletResponse#setCharacterEncoding, one cannot set the encoding. In other words, only the default charset (in a given implementation) can used in this case.
Currently the Cookie class defaults to supporting RFC 2019 cookies.
RFC2019 was obsoleted by RFC2965 in 2000, which in turn was obsoleted by RFC6265 in 2011
The latest RFC appears to be well supported by browsers (eg Google cookies often contain commas which are not allowed by 2019, but are by 6265).
One has the following:
javax.servlet.ServletRequestWrapper.java:
public boolean isWrapperFor(Class wrappedType) {
javax.servlet.ServletResponseWrapper.java:
public boolean isWrapperFor(Class wrappedType) {
javax.servlet.annotation.HandlesTypes.java:
Class[] value();
One should use Class<?> in above.
For many applications, the it is desirable to have authentication handled by the container, while authorization must be handled by the application login. In such scenarios, it would be useful to require the a user is logged on, without having to specify roles.
There is precendence for this kind of security from other environments:
Since the last one conflicts with the current spec, maybe something like this would work:
<auth-constraint anyAuthenticatedUserAllowed="true" />
@ServletSecurity(@HttpConstraint(anyAuthenticatedUserAllowed=true))
public class Example4 extends HttpServlet {
}
I have discussed with Ronald Monzillo about the run-as in servlet.
I try to summarize his comments as follows:
a) In "A.8 Changes Since Servlet 2.3", it states
Clarification: "run-as" identity must apply to all calls from a servlet including init() and destroy() (12.7)
There is no such clarification in the section 12.7 or in the security chapter, so the clarification may have been lost, but the appendix clearly notes the intent, and thus he thinks it is required that a specified run-as identity be in effect during init() and destroy().
b) Note that section 15.3.1 Propagation of Security Identity in EJB Calls, requires that propagation occur whenever an ejb is called by a servlet (without consideration of the Servlet method form which the ejb call is made). That may be going too far, but it would at least support that run-as should be honored within init(); where it is has become common practice to invoke ejbs, and where (unlike the case of calls to ejbs from servlet context listeners), there is a mapping to a specific servlet on which to look for a run-as specification.
I think we should only propagate the security identity when Servlet#init, Servlet#destroy and Servlet#service are called.
(So, there will be no security identity propagation for Servlet#getServletConfig, Servlet#getServletInfo.)
In section of 9.4 of Servlet 3.0 spec, it has the following:
"Before the forward method of the RequestDispatcher interface returns without
exception, the response content must be sent and committed, and closed by the
servlet container."
In javadoc of AsyncContext#dispatch, it has the following:
"Control over the request and response is delegated to the dispatch target, and the response will be closed when the dispatch target has completed execution, unless ServletRequest#startAsync() or ServletRequest#startAsync(ServletRequest, ServletResponse) are called."
According to examples illustrated in javadoc of AsyncContext#dispatch, one need to update the information in section 9.4 so that it is consistent with those in AsyncContext#dispatch.
The HTTP spec allows pre-emptive authentication - i.e. sending credentials before the server asks for them. It is unclear from the Servlet spec how getRemoteUser() and friends should behave in this regard when the resource being requested does not require authentication. Should the credentials be processed or ignored?
Section 1.6.1 Listener ordering, a subsection of 1.6 Compatibility with Java Servlet Specification Version 2.5 states
Prior to this release of the specification, listeners were invoked in a random order. [...]
However, the Servlet Specification Version 2.5 already specified on page 78 in SRV.10.3.2 Deployment Declarations, SRV.10.3.3 Listener Registration and SRV.10.3.4 Notifications At Shutdown that the order is taken from the deployment descriptor:
SRV.10.3.2 Deployment Declarations
[...] [Listener classes] are listed by class name in the order in which they are to be invoked.
SRV.10.3.3 Listener Registration
The Web container registers the listener instances according to [...]
the order in which they appear in the deployment descriptor. During Web
application execution, listeners are invoked in the order of their registration.
SRV.10.3.4 Notifications At Shutdown
On application shutdown, listeners are notified in reverse order to their declarations
with notifications to session listeners preceeding notifications to context listeners.
Session listeners must be notified of session invalidations prior to context listeners
being notified of application shutdown.
See http://java.net/jira/browse/GLASSFISH-17721
"The Servlet 3.0 specification in section 8.2.3 sub part 3 describes "If a servlet is disabled using the enabled element introduced in the web.xml then the servlet will not be available at the url-pattern specified for the servlet".
The WebServletHandler.java deployment annotation handler does not support then enabled element and it should since it is part of the web.xml specification for the element."
When a request is received that requires form authentication, the server remembers the original URL (and perhaps form encoded parameters) and redirects to a login page. Once the user completes the login form a request is sent to j_security_check, which if authentication is successful a redirection is sent to the saved URL.
However, since browsers have caches, iframes and javascript that issues ajax style requests, and since users can decline to authenticate on the first presentation of a web form, it is possible that for a given session multiple requests are received that are redirected to the login form. The problem for the server is to decide if it should eventually redirect to the first of the saved URLs; to the last of the saved; or to some heuristically chosen one in between.
The behaviour on an exception is currently undefined. It would be helpful if the spec defined the expected behaviour in this case. I guess the options are:
Add forward and include events to RequestListener
Section 2.3.3.4 of the Servlet 3.0 spec gives this advice on thread safety with regards to using the request and response objects in an async scenario:
"... they should either only be used within the scope of the request handling thread or the application must ensure that access to the request and response objects are thread safe."
This makes it clear they're not thread safe but also gives the impression that as long as access to these objects is synchronized, they can be used. However, in this servlet-spec user discussion, Greg Wilkins suggests there are a number of request methods that should probably never be used from an async thread including the context path, servlet path, path info, request URI, getting a RequestDispatcher, accessing the session (and possibly others) since their values may change.
Not surprisingly the behavior of Servlet containers varies. The scenario mentioned by Greg actually works in Tomcat and Glassfish potentially leading one to believe it's portable code. Even if one didn't intend on switching containers or didn't care about writing portable code, it's still not clear if the request and response can be used reliably or if they just happen to work in some scenarios.
The spec should make it clear what parts of the request and response should not be used from an application thread in an async scenario.
Consider the following:
*.do is mapped to a servlet
welcome files are index.jsp, index.do
The intention is that the index.jsp page should be used if present and index.do (which always maps to the servlet) used if it is not. However, a strict reading of the servlet spec requires that a 404 is returned in index.jsp is not present .
One of the options for providing protection against session fixation is to change the ID of a session on authentication. It would be good if something along the lines of a changeId() method could be added to the session interface to enable custom security solutions to do this easily. An associated event for sessions listeners would also be required.
In the javadoc of httpServletRequest.getPart/getParts, it does not mention the behavior of calling these API when there is no @MultipartConfig and multipart-config in deployment descriptors.
One should exception in this case. UnsupportedOperationException? IllegalStateException?
The specification is unclear on what should happen here. Clearly, it isn't going to work but how it fails and when it fails is undefined.
My preference is for declaring that those methods throw IllegalStateException in those circumstances.
It would be useful if one could access the contents of the web.xml file, prior to the ServletContext being available.
A use case for this is in writing CDI extensions, where it would be useful to access web.xml configuration data. Currently this is not possible to achieve in a portable way, as the ServletContext has not yet started, and is not available to CDI extensions (in EE environments at least).
Since the WEB-INF folder is not on the classpath, using the context ClassLoader is not possible. Perhaps the solution to this is as simple as adding the WEB-INF folder to the application classpath?
The web.xml element was changed to remove the requirement to specify a . This results in what is referred to as a "preliminary servlet registration". The specification/javadocs describe how the ServletContext.addServlet() methods can be used to complete the registration, but does not mention whether or not a WebServletAnnotation can be used to do so.
Eg
web.xml contains:
Foo
FooServlet.java contains:
@WebServlet(urlPatterns =
{"/","/test/*"}
, name="Foo", initParams=
{@WebInitParam(name="fromAnnotation", value="xyz")}
)
public class FooServlet extends HttpServlet
Is the servlet registration for "Foo" updated with classname "FooServlet" after processing the annotation?
The following issue is raised by Jan Bartel [email protected].
See email discussion in [email protected] .
In p.141 of 13.10 "Login and Logout" of Servlet 3.0 spec, it has:
"If a developer creates a session while a user is not authenticated, and the container then authenticates the user, the session visible to developer code after login must be the same session object that was created prior to login occurring so that there is no loss of session information."
The session content rather than the session object must be kept.
So, it is a bug in the spec.
There appear to be different interpretations of the required behaviour of ServletContext.getRealPath(java.lang.String path) and HttpServletRequest.getPathTranslated() if the virtual path can be mapped to a physical path but the physical path does not exist.
My reading of the specification and the Javadoc is that the physical path does not have to exist, just that the mapping has to be possible. However, I can see how someone else could read the specification as requiring the physical path to exist and null to be returned if it does not.
This should be clarified for Servlet 3.1 and ideally the clarification included in any subsequent maintenance releases of the earlier specification versions.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.