I have a two servlets.
In my first servlet I use sendRedirect construction, but it call doGet from second servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (someCondition()) {
resp.sendRedirect(req.getContextPath() + "/urlPattern");
} else { ... }
}
And my second servlet:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// something to do...
}
But this is not security, user may get second servlet through compose URL. This is not permissible for my case, I need replace call sendRedirect to directly use doPost in second servlet.
Please help me replace resp.sendRedirect(...) to something calling doPost. Thank You.
Related
I have a problem when i attempt to upload a file to my server, an 405 Method POST is not allowed exception appear, this exception only appear on production not locally,
Here's my servlet that handle's form post request
public class FileUploadServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
resp.setHeader("Access-Control-Allow-Headers", "*");
resp.setHeader("Access-Control-Allow-Origin", "*");
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadUrl = blobstoreService.createUploadUrl("/uploadCallback");
uploadUrl = uploadUrl.substring(uploadUrl.indexOf("_") - 1);
req.getRequestDispatcher(uploadUrl).forward(req, resp);
}
}
the servlet that handles the request from 'FileUploadServlet '
public class FileUploadedCallbackServlet extends HttpServlet {
private static BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
String blobKey = blobs.get(FileUploadInput.FILE_URL).get(0).getKeyString(); // Name of field in form where file name was entered
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print(blobKey);
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
}
I am new to Servlet programming and I have a question about wrapping response. Because I couldnt understand when to use it. For example I have filter and servlet as below.
Filter
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
chain.doFilter(req, resp);
HttpServletResponse httpServletResponse = (HttpServletResponse)resp;
httpServletResponse.getWriter().println("hi from filter");
}
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("Hi from servlet");
}
So , What is the difference between them ? I could use both of them to write by using same response object because there are full duplex way (Sincerely, same request and response instances goes to servlet and comes to filter again) between servlet and filter , aren't there ? I am little confused. I appriciate If you could give me a decent sceneraio that could obviously demonstrate the wrapper class's goal.
Thanks & Regards :)
Suppose I have a servlet that does all necessary processing in a method defined like this:
protected abstract void process(ServletRequest request, ServletResponse response);
What is the correct way to implement Servlet interface?
Wrap runtime exceptions in ServletException:
protected void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
try {
process(request, response);
} catch(Throwable t){
throw new ServletException(t);
}
}
or throw runtime exceptions as is:
protected void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
process(request, response);
}
Wrap your code only if you have to handle the exception, otherwise, wrap is not required.
I was working on a web project using java servlet and jsp pages. In one of the servlet we have RequestDispatcher method and which is calling another servlet.
#WebServlet("/Demo")
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.sendRedirect("testing"); //calling other servlet
}
}
#WebServlet("/testing")
public class TestingServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
So, now I wanted to prevent contextRoot/testing from being invoked directly from the browser but instead only let it invoked from the other servlet(Demo)
Please suggest me if there is any way to do that.
Couple of techniques exist:
Look at writing a HTTP Request Filter. You can then inspect the incoming request and the url and reject it if the pattern matches the servlet paths that you do not want to be invoked directly.
Another mechanism is to use the security constraints in your web.xml to allow access to various paths in your application only to authorized users/roles. Look at <security-constraint> tag in web.xml
Answer given by "Romin" is correct. You have to use Filters for this. what you can do is, you can set a new session variable whenever "/Demo" url is accessed and in the filter check for the condition that session exists, if it exists allow the url or else throw error. You could do something similar like this. In "Demo" servlet
#WebServlet("/Demo")
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = request.getSession() //get new session
res.sendRedirect("testing"); //calling other servlet
}
}
In Filter class add the below code
#WebFilter("/login")
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpRequest request = (HttpRequest) req;
HttpResponse respone = (HttpResponse) res;
HttpSession session = request.getSession(false) //get the existing session object
if(null != session) {
chain.doFilter(req, resp);
} else {
"redirect to some error page or home page"
}
}
public void destroy() {}
}
One approach is to check the caller's ip using ServletRequest.getRemoteAddr() and rejects it if it's not called locally
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
if(!req.getRemoteAddr().equals("127.0.0.1")) { // reject }
}
However this method wouldn't work legitimate caller (eg: proxy) is also using the same ip.
My servet work fine for get requests but when I call POST (using jquery ajax $.post) I get error 405 (Method Not Allowed)
Here is my code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class init extends HttpServlet {
public init() { }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("GET");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalStateException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
out.print("POST");
}
}
This happened to me when my method call
"super.doGet(req, resp)" or "super.doPost(req, resp)" .
After i removed above super class calling from the doGet and doPost it worked fine.
Infact those super class calling codes were inserted by the Eclipse IDE template.
Are you sure that you actually override the doPost Method?
The signature looks like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
but you specify it like this:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, IllegalStateException
I am not sure whether this is allowed:
Overriding Java interfaces with new checked exceptions
Try the following steps:
Add the #Override Annotation
Remove the throws IllegalStateException (shouldn't be a problem as it is a runtime exception)