#WebFilter seems to ignore included Javascript files - servlets

( this is regarding Java EE / Servlets WebFilters)
I am currently trying to write a WebFilter which catches every request made to the web application.
However, I noticed that the WebFilter does not see requests made within <script> tags.
The HTML-Page which is being served contains a stylesheet...
<link rel="stylesheet" href="/webjars/bootstrap/4.1.0/css/bootstrap.min.css">
...and three Javascript-includes...
<script src="/webjars/jquery/3.0.0/jquery.min.js"></script>
<script src="/webjars/popper.js/1.14.1/popper.min.js"></script>
<script src="/webjars/bootstrap/4.1.0/js/bootstrap.min.js"></script>
The #WebFilter, however, only sees requests to the root page (GET /) and to the stylesheet, shown in the logs created by the filter below.
12:04:51,909 INFO Init
12:04:51,909 INFO doFilter
12:04:51,909 INFO ServletRequest: HttpServletRequestImpl [ GET / ]
12:04:51,959 INFO doFilter
12:04:51,959 INFO ServletRequest: HttpServletRequestImpl [ GET /webjars/bootstrap/4.1.0/css/bootstrap.min.css ]
The Implementation of the WebFilter looks like this:
#WebFilter(filterName = "webjarFilter", urlPatterns = "/*")
public class WebJarFilter implements Filter {
private Logger logger = LoggerFactory.getLogger(getClass());
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("Init");
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.info("doFilter");
logger.info("ServletRequest: {}", servletRequest);
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
logger.info("destroy");
}
}
The web.xml file contains following mapping:
<filter-mapping>
<filter-name>webjarFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
My question now is:
Can somebody tell me why the filter does not catch the requests which should be generated from the <script> tags?
Observations and additional Info:
I am testing on Wildfly 12 with the Java EE 7
Directly opening the Javascript-Files will trigger the filter
When Javascript files with a wrong path are referenced, the filter sees the requests. Only inclusions of Javascript-files with the correct path are not seen by the filter

Looks like I figured it out myself.
This is actually a result of Firefox behavior.
When calling the same server from Chrome, the filter sees all requests.
Apparently there is some caching mechanism involved within Firefox which applies to scripts.

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource | Firebase Cloud Firestore - Java - Ionic

I'm developing an application and I'm using Ionic (Angular) for client side, java (JAX-RS) as backend and Firebase Cloud Firestore for persistence. Maybe this stack is weird but I'm new in create real applications and Firebase caughy my attention.
I want to save data in Firebase Cloud Firestore using Ionic with an REST API, I can do this with tools like postman, but i can't with Ionic, I'm getting an error No 'Access-Control-Allow-Origin' header is present on the requested resource. You will say to me that configure my server to allow requests but I do this already, I test my REST API without including the part of saving data in Firebase Cloud Firestore, and this work perfectly, I don't get that error. The problem only spends when I call a Firebase method.
Server Configuration
I add the following Java Class
package api;
public class RestCorsFilter implements Filter {
#Override
public void destroy() {
//enter code here
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Headers", "*");
resp.addHeader("Access-Control-Allow-Methods", "*");
chain.doFilter(request, resp);
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
And then, I add this fragment in web.xml
<filter>
<filter-name>RestCorsFilter</filter-name>
<filter-class>api.RestCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RestCorsFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
My application path:
#ApplicationPath("/api")
I was facing this error because every exception caused in the java application was showed in browser's console as a CORS error. The solution was look at the application log to catch and deal with the exception generated by the application.

Adding a servlet to run in Intershop 7.4 application server context

I'm trying to include a 3rd party servlet to run in our IS7 application server's context. How would I go about adding the servlet and mapping to the web.xml?
In the knowledge base I have only found information regarding Enfinity Suite 6. None of the steps provided seem to work.
EDIT:
I found a proposed solution for IS7 using Guice and binding the servlet via a specific Servlet module like
package com.intershop.test;
import com.google.inject.servlet.ServletModule;
public class MyServletModule extends ServletModule
{
#Override
protected void configureServlets()
{
bind(MyServlet.class).in(Singleton.class);
serve("/my/*").with(MyServlet.class);
}
}
I have added my ServletModule to the objectgraph.properties file but my servlet still isn't called when I try accessing it.
Any suggestions?
I know that this works in ICM 7.7 but I believe it has been around since 7.4.
You may use the Guice Servlet Extension.
1.Declare dependency to the Guice Servlet in your cartridge build.gradle. Example:
dependencies
{
...
compile group: 'com.intershop.platform', name: 'servletengine'
compile 'com.google.inject.extensions:guice-servlet'
...
}
2.Define a servlet module in the cartridge objectgraph.properties. Example:
global.modules = com.example.modules.DemoServletModule
3.Implement your servlet. Example:
public class DemoServlet extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.getWriter().append("Hello, world!");
}
}
4.Create the module implementation. Gotcha: The name should start with /servlet/ as pointed in the comments. Example:
import javax.inject.Singleton;
import com.google.inject.servlet.ServletModule;
public class DemoServletModule extends ServletModule
{
#Override
protected void configureServlets()
{
bind(DemoServlet.class).in(Singleton.class);
serve("/servlet/DEMO/*").with(DemoServlet.class);
}
}
4.Build, restart, try. Example:
GET /servlet/DEMO/hey HTTP/1.1
Host: example.com:10054
....
Reposnse:
Hello, world!
UPDATE:
If you would like that your servlet is visible through the webadapter you have to allow it.
1.Open IS_SHARE\system\config\cluster\webadapter.properties
2.Navigate to this section:
## The list of servlets, which can be accessed through the generic
## .servlet mapping. The WebAdapter forwards only requests of the form
## /servlet/<group><servlet.allow.x>...
3.Add entry for your servlet. Example:
servlet.allow.4=/DEMO
4.Access the servlet on a similar URL:
https://example.com/INTERSHOP/servlet/WFS/DEMO/hey

How to render data from a html file using servlets? [duplicate]

How do I generate an HTML response in a Java servlet?
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
#WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Our Servlets wiki page
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
Calling a servlet from JSP file on page load
How to transfer data from JSP to servlet when submitting HTML form
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to use Servlets and Ajax?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
You need to have a doGet method as:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
You can see this link for a simple hello world servlet
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}

Spring 4 upgrade broke error page filter chain

Scenario:
We have an interceptor that looks for bogus attributes in URLs and throws a NoSuchRequestHandlingMethodException if it finds one. We then display a custom 404 page.
All pages go through the same filter chain to set up the local request state, log some information, and then display the requested page. In Spring 4, it stopped going through the filter chain for the 404 page in this case. It still goes through it if you go to a completely bogus page, and the 404 works, but when we throw the NoSuchRequestHandlingMethodException, the filters don't happen.
Spring 3:
1. Runs the filter chain for the main request
2. We throw NoSuchRequestHandlingMethodException
3. Filter chain finishes
4. New filter chain starts
5. We log the error page metrics
6. We display a nice 404 page to the customer
Spring 4:
1. Runs the filter chain for the main request
2. We throw NoSuchRequestHandlingMethodException
3. Filter chain finishes
4. We try to log the error page metrics, but NPE since a second filter chain never started
5. We display a terrible blank page to the customer
Filter code in web.xml:
<!-- The filter that captures the HttpServletRequest and HttpServletResponse-->
<filter>
<filter-name>ServletObjectFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>xxxxxxx.servletObjectFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ServletObjectFilter</filter-name>
<servlet-name>springmvc</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
...
<error-page>
<error-code>404</error-code>
<location>/errors/404</location>
</error-page>
Filter code:
public void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
throws ServletException, IOException {
try {
getServletContainer().setServletObjects( request, response );
chain.doFilter( request, response );
} finally {
getServletContainer().removeAll();
}
ServletContainer:
static final ThreadLocal< HttpServletRequest > REQUESTS = new ThreadLocal< HttpServletRequest >();
static final ThreadLocal< HttpServletResponse > RESPONSES = new ThreadLocal< HttpServletResponse >();
public void setServletObjects( HttpServletRequest request, HttpServletResponse response ) {
REQUESTS.set( request );
RESPONSES.set( response );
}
public void removeAll() {
REQUESTS.remove();
RESPONSES.remove();
}
Code that then fails:
public class RequestResponseAwareBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization( Object bean, String beanName ) {
...
if ( bean instanceof RequestAware ) {
HttpServletRequest request = getServletContainer().getRequest();
if ( request == null ) {
throw new IllegalStateException( "The request object is NULL" );
}
RequestAware requestAware = (RequestAware) bean;
requestAware.setRequest( request );
}
}
I "solved" the problem by splitting up my error page #Controller into two, one where they're the targets of internal redirects and don't get the filter chain, and one where they are directly loaded, and do get the filter chain. I then added the redirect #Controller to the interceptor blacklist, so it doesn't require any logic or data from the filters. It solved this specific problem, but I'm worried that something else in my codebase also relies on this behavior.

Seam and ServletOutputStream - flush is not immediately visible

I am converting a 6 year old application to Seam 2.2.
The application is used to run in java 1.4 and weblogic 8.
It only uses jsp and servlet.
In one servlet I use:
public void doGet (HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
//...
ServletOutputStream out = = res.getOutputStream();
// displaying a lot of messages
// after each println() I do a flush()
out.println("lots of messages.....");
out.flush();
out.close();
//...
}
When running the application the messages were immediately seen in the browser.
When I run this using Seam 2.2 in Weblogic 10 and Java 1.6 the messages are not immediately seen in the browser.
Only when the servlet is finished running.
Can I change something to fix this?
I do not want to change/convert the servlet into a Seam component. The servlet is running fine. The only thing is the flushing of messages to the browser window which only happens after the servlet has stopped running.
Could it be that the reason is that the servlet now goes through the Seam filter:
<filter>
<filter-name>Seam Filter</filter-name>
<filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Seam Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The reason is probably that the request goes through the SeamFilter, as you supposed.
I think it's not the SeamFilter itself that buffer the data stream from your servlet but the Ajax4Jsf filter that is invoked in the filter chain.
If you have RichFaces in the classpath there is a seam component that registers the Ajax4jsf filter in the chain. Namely, the Seam component is org.jboss.seam.web.ajax4jsfFilter.
If you don't need RichFaces try removing it from the classpath. If you need it, I suggest that you override org.jboss.seam.web.ajax4jsfFilter in order to skip the Ajax4Jsf filter for requests directed to your servlet.
Another possible solution is converting your servlet in a filter as a Seam component (see #Filter annotation) and positioning it at the beginning of the chain with the around attribute. Something like:
#Name("FormerServlet")
#Scope(STATELESS)
#BypassInterceptors
#Filter(around = "org.jboss.seam.web.ajax4jsfFilterInstantiator")
public class FormerServletFilter implements Filter
{
protected void init(FilterConfig filterConfig) throws Exception
{
}
protected void doDestroy()
{
}
/**
* Performs the filtering for a request.
*/
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws Exception
{
if (thisRequestShoudBeManagedByMyServlet(request) )
{
// do here what you previously did in the servlet
} else
{
// go ahead with the Seam lifecycle
chain.doFilter(request, response);
}
}
You're running a servlet - there's nothing to do with Seam here. I suspect you need to re-evaluate your design, as there's not really an exact translation from servlet to Seam structure.

Resources