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
Related
I have a test for simple Servlet which get jsp file. In this servlet action request.setAttribute("key", "value") but after call .forward() when I do request.getAttribute("key") I'm get null. Why this happen? This behavior determines forward or reason in mock object?
This is doPost of Servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final boolean success = addUserInDatabase(req);
if (success) req.setAttribute("serverAnswer", EDIT_SUCCESS.get());//this write value
else req.setAttribute("serverAnswer", ERR_UNIQUE_L_P.get());
req.getRequestDispatcher(ANSWER.get())
.forward(req, resp);
}
This is test:
//mock http.
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
when(request.getRequestDispatcher(ANSWER.get()))
.thenReturn(dispatcher);
servlet.doPost(request, response);
String result = (String) request.getAttribute("serverAnswer");//get value
Assert.assertThat(result, is(EDIT_SUCCESS.get()));// result == null
Why I get Null? Is it possible to get value of setAttribute after call forward? How to test this behavior? Thank You.
If you add String result = (String)req.getAttribute("serverAnswer"); just before calling req.getRequestDispatcher(ANSWER.get()) on your servlet and check value of result it would still be null.
The reason is your request object is not real but mocked. you have to do something like this.
when(request.getAttribute(eq("serverAnswer"))).thenReturn(EDIT_SUCCESS.get());
try request.getAttribute("serverAnswer").toString(); and use .include(request, response);.
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).
I have written the following code in service and post methods
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter p = response.getWriter();
p.println("<html><body>");
p.println("<form action = roomlog2 method = post>");
p.println("<input type = submit value = back>");
p.println("</form>");
p.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("homepage.html");
}
But when i executed the code and click the back button the post method is not executing. I am getting following exception
java.lang.NumberFormatException: null
why the post method not redirecting to the "homepage.html"?why i am getting the exception?Kindly someone can tell me the error.
Just remove your implementation of the service() method, or have it call super.service(). That's how doPost() gets called. At present you're not calling it at all.
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 am working in Netbeans IDE and i have wrote JS-code for sending HTTP Request to server:
function applyFilter(){
idFilterJS = getRadioValue();
var url = "applyfilter?action=applyfilterXML&id=" + idFilterJS;
req = initRequest();
req.open("GET", url, true);
req.onreadystatechange = applyFilterCallBack;
req.send(null);
}
Next, I had a breakpoint in ApplyFilterServlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
session = request.getSession();
String action = request.getParameter("action");
}
I have two questions:
What does MonitorRequestWraper mean for request variable during debug mode?
"request.getParameter("action");" returns null. Why?
Thanks!
It extends the request. Dig down into the attributes under "inherited" to find your attributes.
public class MonitorRequestWrapper extends HttpServletRequestWrapper