I was working on a project where based on the presence of a particular string in the request URL to a web application, I was trying to modify the URL of the request using a request wrapper.
I learnt that even if I override the getRequestURI, getRequestURL and getServletPath methods in the wrapper and send that wrapper from a filter, the servlet container still uses its own implementation of the ServletRequest interface to figure out which servlet to call.
I believe the container uses the stored variable for the request URI in the implementation class of ServletRequest and doesn't actually call any of the getRequestURI, getRequestURL and getServletPath methods for identifying the servlet to use (matching URL pattern).
Need all your inputs and knowledge to learn more about this topic. Please help me learn this topic better. Thanks..!!
Below are my experimental code and the request comes from the jsp for http://localhost:8080/RequestResponseListenersWebApp/pages/abcd.jsp
The Filter
#WebFilter(filterName = "AllRequestScanFilter", urlPatterns = "/*")
public class AllRequestScanFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
EmployerViewTestBusinessWrapper wrapper = new EmployerViewTestBusinessWrapper(request);
if (request.getRequestURI().contains("abcd.jsp"))
chain.doFilter(wrapper, resp);
else {
chain.doFilter(req, resp);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
The Wrapper
public class EmployerViewTestBusinessWrapper extends HttpServletRequestWrapper {
public EmployerViewTestBusinessWrapper(HttpServletRequest request) {
super(request);
}
#Override
public String getPathTranslated() {
return super.getPathTranslated();
}
#Override
public String getRequestURI() {
String currentPath=pathModified(super.getRequestURI());
return currentPath!=null?currentPath:super.getRequestURI();
}
#Override
public StringBuffer getRequestURL() {
String currentPath=pathModified(super.getRequestURL().toString());
return currentPath!=null?new StringBuffer(currentPath):new StringBuffer(super.getRequestURL());
}
#Override
public String getServletPath() {
String currentPath=pathModified(super.getServletPath());
return currentPath!=null?currentPath:super.getServletPath();
}
private String pathModified(String currentPath){
String returnPath=null;
if(currentPath.contains("pages")){
returnPath=currentPath.replaceFirst("/pages/","/pages/myapp/");
}
return returnPath;
}
}
The Servlet which is never reached
#WebServlet(name = "EmployerViewTestServlet",urlPatterns = "/pages/myapp/*")
public class EmployerViewTestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path=request.getParameter("path");
}
}
And one more thing. The Filter I have specified here is the first thing in the web app that's called when a request comes in.
I can always check the URL pattern in the filter and forward the request to the desired URL pattern using a RequestDispatcher.
However, in my app there're some Filters that are called for dispatcher type FORWARD and I don't want them to be called when a request has just come from the client.
Wouldn't be this what you're looking for?
In that case, the request.getRequestDispatcher(newURI).forward(req, res) seems to do the trick, using only the filter.
#WebFilter(filterName = "AllRequestScanFilter", urlPatterns = "/*")
public class AllRequestScanFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
//EmployerViewTestBusinessWrapper wrapper = new EmployerViewTestBusinessWrapper(request);
String URI = request.getRequestURI();
if (URI.contains("abcd.jsp") && URI.contains("pages")) {
URI = URI.replaceFirst("/pages/","/pages/myapp/");
request.getRequestDispatcher(URI).forward(req, res);
} else {
chain.doFilter(req, resp);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
Related
the filter is always checking for authentication for the login page and I don't know how to configure it.
here is the AppFilter.java (I couldn't post all the code):
#Singleton
public class AppFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
try {
final String appLocale = AppSettings.get().get(AvailableAppSettings.APPLICATION_LOCALE, null);
APP_LOCALE = appLocale == null ? null : new Locale(appLocale);
} catch (Exception e) {
}
}
public static String getBaseURL() {
return BASE_URL.get();
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
BASE_URL.set(computeBaseUrl(request));
LANGUAGE.set(request.getLocale());
try {
chain.doFilter(request, response);
} finally {
LANGUAGE.remove();
BASE_URL.remove();
}
}
}
You can modify doFilter() in order to check if the requested URL belongs to the list of predefined excluded URLs, if so then just forward the request to the next filter or servlet in the chain, otherwise do whatever you want to do.
Here is the code:
#Singleton
public class AppFilter implements Filter {
private List<String> excludedUrls;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
excludedUrls = Arrays.asList(YOUR_LOGIN_URL);
Filter.super.init(filterConfig);
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String path = ((HttpServletRequest) servletRequest).getServletPath();
if(!excludedUrls.contains(path))
{
// if url does not match your login url do what you want to do..
}
// else forward the request to the next filter or servlet in the chain.
chain.doFilter(req, resp);
}
#Override
public void destroy() {
}
}
I'm creating a servlet filter for my service and it seems like init() is not being called based on the logs.
I don't have a web.xml file, rather I added a #Provider annotation to the filter class.
#Provider
#WebFilter("/*")
public class TestFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Test filter has been initialized");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
String remote_addr = request.getRemoteAddr();
requestWrapper.addHeader("remote_addr", remote_addr);
chain.doFilter(requestWrapper, response); // Goes to default servlet.
}
#Override public void destroy() { }
}
Also added to my module:
#Provides
#Singleton
public void getTestFilter() {
return new TestFilter()
}
Looks at the logs, it seems like the init() is never called. Any ideas why?
I've got a filter:
#WebFilter(urlPatterns = "/Mvc02")
public class Filter02 implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
some code...
}
public void init(FilterConfig config) throws ServletException {
}
}
And servlet:
#WebServlet(name = "Mvc02", urlPatterns = "/Mvc02")
public class Mvc02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
some code...
}
}
When I go to my browser and type http://localhost:8080/servletjee_war_exploded/Mvc02 it gives me the servlet. Shouldn't it give me the filter first? How to run the filter?
if you want a filter to only apply to certain URL patterns (and if you are using spring), then you would have to register the filter using a FilterRegistrationBean
#Bean
public FilterRegistrationBean<Filter02> loggingFilter(){
FilterRegistrationBean<Filter02> registrationBean
= new FilterRegistrationBean<>();
registrationBean.setFilter(new Filter02());
registrationBean.addUrlPatterns("/Mvc02");
return registrationBean;
}
I have a need where certain HTTP requests must be redirected to a Spring Boot web app/service, but that on the request-side, the Spring app does nothing and acts as a passthrough between the HTTP client (another service) and the request's true destination. But when the response comes back to the Spring app (from that destination), I need the Spring app to be able to inspect the response and possibly take action on it if need be. So:
HTTP client makes a request to, say, http://someapi.example.com
Network magic routes the request to my Spring app at, say, http://myproxy.example.com
On the request, this app/proxy does nothing, and so the request is forwarded on http://someapi.example.com
The service endpoint at http://someapi.example.com returns an HTTP response back to the proxy
The proxy at http://myproxy.example.com inspects this response, and possibly sends an alert before returning the response back to the original client
So essentially, a filter that acts as a pass-through on the request, and only really does anything after the remote service has executed and returned a response.
My best attempt thus far has been to setup a servlet filter:
#Override
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response)
// How and where do I put my code?
if(responseContainsFizz(response)) {
// Send an alert (don't worry about this code)
}
}
Is this possible to do? If so, where do I put the code that inspects and acts upon the response? With my code the way it is I get exceptions thrown when trying to hit a controller from a browser:
java.lang.IllegalStateException: STREAM
at org.eclipse.jetty.server.Response.getWriter(Response.java:910) ~[jetty-server-9.2.16.v20160414.jar:9.2.16.v20160414]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
rest of stack trace omitted for brevity
Any ideas?
Per the Servlet API documentation, the reason you are getting the IllegalStateException is because you are attempting to call ServletResponse.getWriter after ServletResponse.getOutputStream has already been called on the response. So it appears that the method you need to call is ServletResponse.getOutputStream().
However, if you are trying to access the body of the response, the best solution is to wrap the response in a ServletResponseWrapper so that you can capture the data:
public class MyFilter implements Filter
{
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
#Override
public void destroy()
{
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
MyServletResponseWrapper responseWrapper = new MyServletResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
if (evaluateResponse(responseWrapper)) {
// Send an alert
}
}
private boolean evaluateResponse(MyServletResponseWrapper responseWrapper) throws IOException
{
String body = responseWrapper.getResponseBodyAsText();
// Perform business logic on the body text
return true;
}
private static class MyServletResponseWrapper extends HttpServletResponseWrapper
{
private ByteArrayOutputStream copyOutputStream;
private ServletOutputStream wrappedOutputStream;
public MyServletResponseWrapper(HttpServletResponse response)
{
super(response);
}
public String getResponseBodyAsText() throws IOException
{
String encoding = getResponse().getCharacterEncoding();
return copyOutputStream.toString(encoding);
}
#Override
public ServletOutputStream getOutputStream() throws IOException
{
if (wrappedOutputStream == null) {
wrappedOutputStream = getResponse().getOutputStream();
copyOutputStream = new ByteArrayOutputStream();
}
return new ServletOutputStream()
{
#Override
public boolean isReady()
{
return wrappedOutputStream.isReady();
}
#Override
public void setWriteListener(WriteListener listener)
{
wrappedOutputStream.setWriteListener(listener);
}
#Override
public void write(int b) throws IOException
{
wrappedOutputStream.write(b);
copyOutputStream.write(b);
}
#Override
public void close() throws IOException
{
wrappedOutputStream.close();
copyOutputStream.close();
}
};
}
}
}
The response can be easy manipulated/replaced/extended e with a filter and a response wrapper.
In the filter before the call chain.doFilter(request, wrapper) you prepare a PrintWriter for the new response content and the wrapper object.
After the call chain.doFilter(request, wrapper) is the actuall response manipulation.
The wrapper is used to get access to the response as String.
The Filter:
#WebFilter(filterName = "ResponseAnalysisFilter", urlPatterns = { "/ResponseFilterTest/*" })
public class ResponseFilter implements Filter {
public ResponseFilter() {}
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
#Override
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, wrapper);
String oldResponseString = wrapper.toString();
if (oldResponseString.contains("Fizz")) {
// replace something
String newResponseString = oldResponseString.replaceAll("Fizz", "Cheers");
// show alert with a javascript appended in the head tag
newResponseString = newResponseString.replace("</head>",
"<script>alert('Found Fizz, replaced with Cheers');</script></head>");
out.write(newResponseString);
response.setContentLength(newResponseString.length());
}
else { //not changed
out.write(oldResponseString);
}
// the above if-else block could be replaced with the code you need.
// for example: sending notification, writing log, etc.
out.close();
}
}
The Response Wrapper:
public class CharResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter output;
public String toString() {
return output.toString();
}
public CharResponseWrapper(HttpServletResponse response) {
super(response);
output = new CharArrayWriter();
}
public PrintWriter getWriter() {
return new PrintWriter(output);
}
}
The Test Servlet:
#WebServlet("/ResponseFilterTest/*")
public class ResponseFilterTest extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
response.getWriter().append(
"<html><head><title>replaceResponse filter</title></head><body>");
if (request.getRequestURI().contains("Fizz")) {
response.getWriter().append("Fizz");
}
else {
response.getWriter().append("Limo");
}
response.getWriter().append("</body></html>");
}
}
Test Urls:
https://yourHost:8181/contextPath/ResponseFilterTest/Fizz (Trigger response Replacement)
https://yourHost:8181/contextPath/ResponseFilterTest/ (response unchanged)
More Info and examples about filters:
http://www.oracle.com/technetwork/java/filters-137243.html#72674
http://www.leveluplunch.com/java/tutorials/034-modify-html-response-using-filter/
https://punekaramit.wordpress.com/2010/03/16/intercepting-http-response-using-servlet-filter/
How can I use a servlet filter to change an incoming servlet request url from
http://nm-java.appspot.com/Check_License/Dir_My_App/Dir_ABC/My_Obj_123
to
http://nm-java.appspot.com/Check_License?Contact_Id=My_Obj_123
?
Update: according to BalusC's steps below, I came up with the following code:
public class UrlRewriteFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
//
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
String requestURI = request.getRequestURI();
if (requestURI.startsWith("/Check_License/Dir_My_App/")) {
String toReplace = requestURI.substring(requestURI.indexOf("/Dir_My_App"), requestURI.lastIndexOf("/") + 1);
String newURI = requestURI.replace(toReplace, "?Contact_Id=");
req.getRequestDispatcher(newURI).forward(req, res);
} else {
chain.doFilter(req, res);
}
}
#Override
public void destroy() {
//
}
}
The relevant entry in web.xml look like this:
<filter>
<filter-name>urlRewriteFilter</filter-name>
<filter-class>com.example.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>urlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I tried both server-side and client-side redirect with the expected results. It worked, thanks BalusC!
Implement javax.servlet.Filter.
In doFilter() method, cast the incoming ServletRequest to HttpServletRequest.
Use HttpServletRequest#getRequestURI() to grab the path.
Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.
Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).
Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the #WebFilter annotation for that instead.
Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.
Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.
You could use the ready to use Url Rewrite Filter with a rule like this one:
<rule>
<from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
<to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>
Check the Examples for more... examples.
A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.
public class UrlPrettyfierFilter implements Filter {
private static final String JSF_VIEW_ROOT_PATH = "/ui";
private static final String JSF_VIEW_SUFFIX = ".xhtml";
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String requestURI = httpServletRequest.getRequestURI();
//Only process the paths starting with /ui, so as other requests get unprocessed.
//You can register the filter itself for /ui/* only, too
if (requestURI.startsWith(JSF_VIEW_ROOT_PATH)
&& !requestURI.contains(JSF_VIEW_SUFFIX)) {
request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
.forward(request,response);
} else {
chain.doFilter(httpServletRequest, response);
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
In my case, I use Spring and for some reason forward did not work with me, So I did the following:
public class OldApiVersionFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if (httpServletRequest.getRequestURI().contains("/api/v3/")) {
HttpServletRequest modifiedRequest = new HttpServletRequestWrapper((httpServletRequest)) {
#Override
public String getRequestURI() {
return httpServletRequest.getRequestURI().replaceAll("/api/v3/", "/api/");
}
};
chain.doFilter(modifiedRequest, response);
} else {
chain.doFilter(request, response);
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
#Override
public void destroy() {}
}
Make sure you chain the modifiedRequest