Wicket messes uo the encoding of strings from Javascript - java

In the context of a Wicket component using JavaScript, I'm sending the following string back to Wicket :
"FICHIERfichier&é'(-è_çà)=~#{[`^#]}^$ù,;!¨£%µ§êë-+¤.0²123456789.pdf"
I have to escape() this in JavaScript because otherwise Wicket interprets the ampersand as a parameter delimiter and chops the string into multiple parameters.
However, this is what I get on the Wicket side of things :
"FICHIERfichier&�'(-�_��)=~#{[`^#]}^$�,;!��%����- �.0�123456789.pdf"
Any ideas ? I've tried many unescape/decode methods to no avail...
Many Thanks !

It seems the character encoding your application uses does not support some of the sent characters.
Make sure you use a good charset in Wicket's RequestCycleSettings. By default it is UTF-8, but your application may have changed it.
In addition if you use some old version of a Servlet container then you may need to use a Servlet Filter around Wicket Filter that sets the character encoding on the HttpServletRequest. A quick googling for "Servlet filter character encoding" gives this good example: https://stackoverflow.com/a/11100412/497381.
public class CustomCharacterEncodingFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void destroy() {
}
}

Related

Disallow anything but GET for certain links in spring boot

I have a simple blog webpage with a lot of links. They are all using GetMapping. Therefore whenever I have a bot try to access those pages using POST I get an error saying
Request method 'Post' not supported.
I understand that this is caused because I use #GetMapping, and if I switch to #RequestMapping then everything will be fine. However I do not want to allow anyone to access my blog with POST. The only page that should be POST is /contact/message except that page everything should be accessed through GET.
So I have two questions:
How do I enforce people to use GET only.
How do I catch attempts to use POST and redirect them to /error?
Sidenote: I do not use spring security, there is no logging in or anything that is hidden behind an account. Also most of my mappings are using regex. Do not know if this info is of any help or not.
#GetMapping(value = {
"", "{page:^[1-9][0-9]*$}", "{section:^\\d*[a-zA-Z][a-zA-Z0-9]*[^.]+$}",
"{section:^\\d*[a-zA-Z][a-zA-Z0-9]*[^.]+$}/{page:^[1-9][0-9]*$}"})
You can add a filter in your application:
public class Tfil implements Filter {
#Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
if (!"GET".equals(req.getMethod())) {
//redirect or error page
HttpServletResponse res = (HttpServletResponse) servletResponse;
//here redirect
res.sendRedirect("redirect url");
//or return 404 code
res.setStatus(404);
}
filterChain.doFilter(servletRequest,servletResponse);
}
}

Possible misunderstanding of the doFilter method

I am actually pretty new to the Java EE specifications since I am kind of young. I never learned this things at school and I am facing a weird behaviour with the doFilter method.
Consider the following filter :
#WebFilter(filterName = "URLFilter", value = "/test")
public class URLFilter implements Filter {
public void destroy() {}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletResponse response = (HttpServletResponse) resp;
if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND)
response.sendRedirect("/");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {}
}
There is no servlet or page present in /test and in my browser, the status is obviously a 404 not found error when accessing the URL and so should be the value returned to me by the getStatus() method which isn't. (actually having a 200 status code)
Why is my filter not redirecting me to / as requested ? Do I misunderstand the use of Filters in general ?
UPDATE:
My question was about redirecting the client (using the sendRedirect()) when a page is not found. I did not understand the filter part because I didn't know that resp and req are actually filled with the new data when chain.doFilter() is called. (which I actually found strange since the doFilter is calling the next Filter chained by the COR pattern)
I've made a class inheriting the HttpServletResponseWrapper, implemented it, passed it to the Filter and it's working fine now.
Your filter is invoked before trying to access the actual resource (servlet, page, file, whatever) located at /test. So the response status can't be 404 yet at this time.
Then your filter invokes chain.doFilter(), thus telling the container to actually serve the resource at /test. Since there is no such resource, you get a 404.

Change ServletRequest server name programmatically

I need to change the serverName of the ServletRequest object in my Grails controller. I'm having trouble figuring out how to do this since the serverName is a read-only property.
The most correct thing to do is probably to set up a clever filter or redirect which "fixes" your request URL before your servlet even gets involved. I know nothing about how to do that; you should ask on serverfault.com if you want to do that.
In java, you can fake it by creating your own subclass of HttpServletRequestWrapper which provides setServerName() and overrides getServerName() while delegating all other methods to the superclass. You can then provide a filter which creates an instance of your request and sends that one down the chain.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
YourHttpServletRequest yourRequest =
new YourHttpServletRequest(request, newServerName);
chain.doFilter(yourRequest, response);
}
If I understand this correctly, CORS filter might help
I've used http://software.dzhuvinov.com/cors-filter.html in my previous project.
But you can also lookup on github for example https://github.com/eBay/cors-filter

Vanity/Fancy/Rewrite URL implementation that does not suck

I have got a website, with really badly implemented Vanity URL module and really high loads at certain periods of time. Due to some bugs in the url module, the system needs to be restarted every so often. So, I want to rewrite a bloody module to make it nice and less buggy...
Is there are a good pattern to implementing Vanity URL system ?
What is the best approach when dealing with Vanity URL's for high performance ?
What is the best library to look at the sources ?
Cheers.
Ako
I'm not sure about the specific implementation details of your application, but as a general sketch I would write a Filter mapped to the space of URL of interest (perhaps /*).
Such Filter would check if the URL is a fancy one, and in that case would forward the request to the appropiate resource (either a URL dispatcher or a named one). You will need to save the filterConfig.getServletContext() passed in init(FilterConfig) in order to create the request dispatchers. If the URL is not fancy, the filter would invoke chain.doFilter(req, resp), then serving a non-mapped resource.
public class ExceptionFilter implements Filter {
private ServletContext servletContext;
public void destroy() {}
public void doFilter(ServletRequest req,
ServletResponse resp,
FilterChain chain)
throws IOException, ServletException {
String mapping = getMappingFor((HttpServletRequest)req);
if(mapping!=null) servletContext.getRequestDispatcher(mapping).forward(req,resp);
else chain.doFilter(req, resp);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.servletContext = filterConfig.getServletContext();
}
private String getMappingFor(HttpServletRequest req) {...}
How getMappingFor is implemented, depends on the application, but it would probably open a connection to a database and ask whether URL /foo/bar is mapped, returning the mapped URL or nullif there is no mapping. If the mappings are known not to change, you may cache those mappings already retrieved.
You may go with more detailed implementations, such as setting some request attributes depending on the given URL or information from the database, and then forwarding the request to some servlet that knows what to do.

how to remove all "\n" in JSP page? (use javax.servlet.Filter?)

i want remove all "\n" for JSP page output.
i think i should be using a Filter for this.
but i dont know how to do
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
//how to remove all "\n" for output?
}
any idea? thanks for help :)
BalusC has a post showing such a filter. Check here
This question shows other options for trimming whitespaces.
To get access to the response generated by a resource, you need to wrap the HttpServletResponse object. i.e. change the response object that is passed to the doFilter()
method of the FilterChain object. The custom wrapper can buffer up all the output from your resource (JSP/Servlet) which can be accessed and changed before sending it back to the client.
You can use simple String.replaceAll() method to replace all \n's.
You can use the HttpServletResponseWrapper class to wrap the response object. Take a look at filter tutorial. This book also gives clear instructions on how to modify a response from a Filter. See section 9.9 of the book.

Categories

Resources