Problem with servlet request setAttibute and getParameter java - java

#Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("orden", 11);
System.out.println("ord "+request.getParameter("orden"));//returns null
request.getRequestDispatcher("/view/a.jsp").forward(request, response);
}
//Why does this happen?
and in my jsp is the same result = null

You are setting an attribute and trying to get a parameter
request.setAttribute("orden", 11);
request.getAttribute("orden");

attribute and parameter are different things. As you are setting attribute, use getAttribute() to get the value.
System.out.println("ord "+request.getAtribute("orden"));

Related

What wrong with HttpServletRequest after .forward(req, resp)?

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);.

How to transfer control from service to post method in servlets?

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.

Picking up redirect parameters

When sending a redirect is it possible to see what are the parameters passed from the servlet we redirected to?
For exampe:
We redirect from servlet servletA
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException {
resp.sendRedirect(req.getContextPath()+"/foo#fooMethod:val1="+val1+"&val2="+val2);
}
So what does servlet servletB need to do to pick up val1/val2/fooMethod?
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException {
}
As just like your query parameters.
String value2 = req.getParameter("val2");
And same goes for remaining too.
And I belive you need to write ? instead of # to append the query parameters to the url.
See the reference on Sun/Oracle's java servlet site:
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html
You'd essentially have to do req.getParameter("val2")
will be a String Type and you can convert it to whatever type you need.
In the future if your parameter has more than one value you'd use getParameterValues(java.lang.String). You can pass arrays of Strings, etc.
Also
/foo#fooMethod:val1= should be
/foo?doGet:val1=yourValue&val2=yourNextValue&val3=yourNextNextValue

data transfer between two servlets

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

HTTP method GET is not supported by this URL

i am having trouble with my code as i am accessing the logout servlet from a jsp page's hyperlink.
Jsp page link:
href="/logout"
logout Servlet:
public class logOut extends HttpServlet{
public void doGET(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
System.out.println("log out servlet");
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate();
}
resp.sendRedirect("/signin.jsp");
}
}
but i am having the following error :
HTTP ERROR 405
Problem accessing /logout. Reason:
HTTP method GET is not supported by this URL
please help me.....
It is called doGet, not doGET.
The #Override annotation would have told you that.
Your method needs to be called
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
in order to be recognized - the uppercase letters make it fail.

Categories

Resources