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);.
Related
#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"));
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 am setting an attribute to the session object in jsp page as shown below:
String remoteAddr = request.getRemoteAddr();
session.setAttribute("remoteAddr",remoteAddr);
Then, I am trying to retrieve that session attribute in the servlet filter:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String remoteIP = httpServletRequest.getSession(false).getAttribute("remoteAddr");
}
But I am getting a null value for the session object here. What is the correct way to get same session object here?
The method HttpServletRequest.html#getSession(boolean) may return null
If create is false and the request has no valid HttpSession, this method returns null.
A Filter may be invoked before a resource is requested or after it is requested depending on when you perform chain.doFilter(request, response);
In your case it seem that you query the session before the jsp is executed, i.e. doing something like this:
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String remoteIP = (String) httpServletRequest.getSession(false).getAttribute("remoteAddr");
// pass the request along the filter chain
chain.doFilter(request, response);
Changing it to
// pass the request along the filter chain
chain.doFilter(request, response);
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String remoteIP = (String) httpServletRequest.getSession(false).getAttribute("remoteAddr");
Will get it to work, but I doubt this is what you intend to do, since you probably want to check the remote IP and decide whether to allow access or deny it to the requested resource, in which case you may want to do something like this:
String remoteIP= request.getRemoteAddr();
if(remoteIP.matches("some pattern")) {
((HttpServletResponse)response).setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
// pass the request along the filter chain
chain.doFilter(request, response);
}
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
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