How to check a uploaded file whether it is an image or other file?

I’m assuming that you’re running this in a servlet context. If it’s affordable to check the content type based on just the file extension, then use ServletContext#getMimeType() to get the mime type (content type). Just check if it starts with image/. String fileName = uploadedFile.getFileName(); String mimeType = getServletContext().getMimeType(fileName); if (mimeType.startsWith(“image/”)) { // It’s an …

Read more

The import org.apache.commons cannot be resolved in eclipse juno

The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you’re talking about when you say to import this and that. It can’t find them in the classpath. It’s part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib folder of the webapp project and …

Read more

Is synchronization within an HttpSession feasible?

I found this nice explanation in spring-mvc JavaDoc for WebUtils.getSessionMutex(): In many cases, the HttpSession reference itself is a safe mutex as well, since it will always be the same object reference for the same active logical session. However, this is not guaranteed across different servlet containers; the only 100% safe way is a session …

Read more

Getting “java.net.ProtocolException: Server redirected too many times” Error

It’s apparently redirecting in an infinite loop because you don’t maintain the user session. The session is usually backed by a cookie. You need to create a CookieManager before you use URLConnection. // First set the default cookie manager. CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); // All the following subsequent URLConnections will use the same cookie manager. URLConnection …

Read more

Forward HttpServletRequest to a different server

Discussions of whether you should do forwarding this way aside, here’s how I did it: package com.example.servlets; import java.net.HttpURLConnection; import java.net.URL; import java.util.Enumeration; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.example.servlets.GlobalConstants; @SuppressWarnings(“serial”) public class ForwardServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) { forwardRequest(“GET”, req, resp); } @Override public void doPost(HttpServletRequest req, …

Read more

How to get the @RequestBody in an @ExceptionHandler (Spring REST)

You can reference the request body object to a request-scoped bean. And then inject that request-scoped bean in your exception handler to retrieve the request body (or other request-context beans that you wish to reference). // @Component // @Scope(“request”) @ManagedBean @RequestScope public class RequestContext { // fields, getters, and setters for request-scoped beans } @RestController …

Read more