I am trying to pass data from one servlet to another servlet but when I fetch it from another servlet its returning null.
ViewServlet.java
#WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<a href='index.html'>Add New Employee</a>");
out.println("<h1>All Employees</h1>");
List<Employee> emp=EmpDao.getAllEmployees();
out.print("<table width='50' border='1'>");
out.print("<tr><th>Id</th><th>Username</th><th>email</th><th>country</th><th>Edit</th><th>Delete</th></tr>");
for(Employee e:emp){
System.out.println("in view "+e.getId());
out.print("<tr><td>"+e.getId()+"</td><td>"+e.getUsername()+"</td><td>"+e.getPassword()+"</td><td>"+e.getEmail()+"</td><td>"+e.getCountry()+"</td><td><a href='EditServlet?id"+e.getId()+"''>edit</a></td><td><a href='DeleteServlet?id"+e.getId()+"'>Delete</a></td></tr>");
}
out.println("</table>");
}
Here in this class I am trying to send id to my another servlet EditServlet. Inside the for loop its printing all the id's and even in html its there.
But in EditServlet its returning null.
EditServlet.java
#WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String id2=request.getParameter("id");
System.out.println("id is"+request.getParameter("id"));//Null is getting printed
int id=Integer.parseInt(id2);
System.out.println("Inside doGet id is"+id);//NumberFormatException
}}
You're missing an equals in the link. Your code is generating the URL EditServlet?id1, so the parameter sent will be id1 with no value, when you want EditServlet?id=1 so you'll get a parameter id with the value 1.
<a href='EditServlet?id"+e.getId()+"''>edit</a>
should be
<a href='EditServlet?id="+e.getId()+"'>edit</a> (note extra ' also removed)
The same applies to the delete link.
The easiest way to find parameter problems like this is to use the browser's developer tools to look at what the browser actually sends and receives. Or if the server was launched from an IDE, there should be a way to view the details of each request (the HTTP Server Monitor in NetBeans for example).
Related
I just want to understand the purpose behind returning back to the calling servlet, after the execution of forwarded servlet.
Below example simply shows that after execution of forwarded servlet, control returns back to calling servlet.
//servlet1 Code (Forwarding to servlet2)
#WebServlet("/servlet1")
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request, response);
System.out.println("Returned to Calling Servlet");
}
}
//servlet2 Code (returning control to servlet1)
#WebServlet("/servlet2")
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = "to Servlet2";
out.print("Welcome " + n);
}
}
Output ::
Welcome to Servlet2 (on Browser)
Returned to Calling Servlet (on Console)
Need clarification :
After committing response, why it's returning back to servlet1
I have Servlet which rotates me some value http://localhost:666/sg/queue?q=21343434
I want to get the value q
#WebServlet("/queue")
public class QueueServlet extends HttpServlet {
private List<String> queue;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
queue = new ArrayList<String>();
queue.add("12324543254235");
out.print(queue.size());
out.print(request.getAttribute("q").toString());
}
}
but when I write out.print(request.getAttribute("q").toString()); nothing is displayed
and when I write out.print(request.getQueryString()); displayed q=21343434
but I need to get only the very value q
Use request.getParameter() to get param of url, the getAttribute() is used to get data of posted request.
I have two servlet.
The first (doGet) shows me the form and the second (doPost) processes the form
Here is my first servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Nodes nodes = nodes_dao.start(request);
int id = nodes.getId_node();
request.setAttribute("nodes", nodes);
request.setAttribute("id", id);
request.getRequestDispatcher(VUE).forward(request, response);
}
And here is my second servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String question = null;
String result = null;
question = request.getParameter("question");
result = request.getParameter("result");
Node_dao dao = new Node_dao();
try
{
dao.insert_result(result);
int left_id = dao.select_left_id(result);
dao.insert_question(question, left_id);
}
For example, how I can retrieve the id of the first servlet in the second?
Thanks
You are already calling request.setAttribute("id", id); in th first servlet, then forwarding to the second. So all you are missing is to call int id = (int)request.getAttribute("id"); in the second servlet.
HOWEVER, there is a second problem. You cannot magically change the METHOD type by forwarding. If the original request was GET, it is still GET after the forward. So your second servlet needs to handle the request in a doGet not a doPost.
You could do this using cookies or httpsession.
This link will be interesting for you: http://www.journaldev.com/1907/java-servlet-session-management-tutorial-with-examples-of-cookies-httpsession-and-url-rewriting
I tried a simple servlet program which uses a sendredirect method in eclipse.
Here is its code:
public class Sendredirectmethod extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
response.sendRedirect("http://www.google.com");
pw.close();
}
}
Now when I am running on my tomcat server, I am getting error as shown in the screenshot url http://postimg.org/image/f9rdwwss7/ .
How to resolve this problem? What happened while executing it?
I am working on a filter, this code fails to execute/response.write if there is a 'forward' involved in the request. But it works fine for basic servlets that simply steam HTML content to the user. How can address "forwards" with this code.
For example, here is the filter that simple captures text content and attempts to manipulate that content.
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession(false);
CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
final boolean commit1 = responseWrapper.isCommitted();
final boolean commit2 = response.isCommitted();
if (!commit2) {
final String res = responseWrapper.toString().replaceAll("(?i)</form>", "<input type=\"hidden\" name=\"superval\" value=\""+superval"\"/></form>");
response.getWriter().write(res);
}
return;
}
...
This works for most basic servlets, the goal is at the line with the "replaceAll".
Now, if I create a servlet with a 'forward' the code does not work, it fails at the line with 'if (!commit2)' because the stream is already committed apparently?
For example, if I make a request to this servlet and tie the filter to this servlet, then the filter does not execute completely.
public class TestCommitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("TestCommitServlet2").forward(req, resp);
}
#Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
And here is the servlet that I am forwarding to:
public class TestCommitServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
out.println("<html><body>(v-1)testing<form action='test'><input type='submit' value='Run' /> </form></body></html>");
}
#Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Tl;dr : Do I have to make this call 'if (!commit2) {' The code works without it. Under this code, how would I avoid Response already committed or IllegalStateExceptions (around the line with response.getWriter().write(res);
More on the issue here:
https://codereview.stackexchange.com/questions/41260/capturing-content-within-a-j2ee-filter-and-then-replacing-this-text-request-for
I´m using Servlet API 3.0 to check this scenario.
What I found is the following. Using your code for the servlet and the filters when I call the TestCommitServlet2 , I´m able to see the following output.
http://localhost:8080/Question/TestCommitServlet2
(v-1)testing
Button here
com.koitoer.CharResponseWrapper#5b5b6746
When I call the servlet TestCommitServlet , Im able to see the following.
http://localhost:8080/Question/TestCommitServlet
(v-1)testing
Button here
this shown that filter is not apply to this forwarded request at all.
So, I remember that some filters can act in diverse DispatcherTypes as FORWARD, INCLUDE, ERROR, ASYNC and the commong REQUEST, what I decide is change the filter declaration to.
#WebFilter(filterName = "/MyFilter", urlPatterns = { "/TestCommitServlet2" }, dispatcherTypes = {
DispatcherType.FORWARD, DispatcherType.REQUEST })
public class MyFilter implements Filter {
Then when I excecute a GET over the servlet TestCommitServlet I got:
(v-1)testing
Button
com.koitoer.CharResponseWrapper#1b3bea22
the above shown that Filter is now applied to the forward request.
Also if I remove or comment lines for if (!commit2) { code still works, so there is no IllegalStateException as request need to pass over the filter which is who invoke the doChain method.
One note more, if you try to replace the content of the response using this.
responseWrapper.toString().replaceAll
You are doing it wrong as responseWrapper.toString() returns something like this CharResponseWrapper#5b5b6746, not the content, if you want to modify the response use a Wrapper that extends from HttpServletResponseWrapper and override the correct methos to manipulate the outpustream.