0
public class Uploadservlet extends HttpServlet
{
    
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
    {
        String name="arul";
        PrintWriter out=res.getWriter();
    if(name=="arul")
        {
        
        
            req.getRequestDispatcher("uploadfile.jsp").forward(req,res);
            
                out.println("<h3>hello world</h3>");
            
            System.out.println("hello world");
            System.out.println("hi");       }
        else
        {
           out.println("hi hello");
           System.out.println("hi hello");
        
        }
    }}
    

After forwarding the request through request dispatcher, what will happen to the below code? My out.println is not working but System.out.println after that is working, what happened to the printwriter

ARULVIJAY
  • 11
  • 2
  • Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pradeep Simha Nov 07 '22 at 09:06
  • 2
    @PradeepSimha while the String comparison will usually not work with `==`, in this piece of example code it actually will enter the `if` branch because the code uses a string literal for both sides of the `==` and the compiler replaces that with the reference to the same String object. – cyberbrain Nov 07 '22 at 09:35
  • @ARULVIJAY please describe "is not working" a little bit better. Also: where does the request dispatcher dispatch the call to? What happens there? – cyberbrain Nov 07 '22 at 09:36
  • can you put out.println("") before req.getRequestDispatcher and check if it is still failing ? – Jishnu Prathap Nov 07 '22 at 09:36
  • @cyberbrain not working in the sense, i don't know whether the code(out.println, because the request is forwarded to another jsp page) will execute or not but the system.out.println is executed, since out.println is a response, but response is already passed in forward, so what will happen in this situation and the request dispatcher dispatch the call to the same page from where it was called – ARULVIJAY Nov 07 '22 at 10:27
  • @JishnuPrathap yes it is still failing, but if i close the printwriter before the request dispatcher then it is ok – ARULVIJAY Nov 07 '22 at 10:30
  • 1
    Try to use `include` instead of `forward` since you want to continue writing after the dispatch. – Maurice Perry Nov 07 '22 at 10:44
  • Question already answered – Harsh Nov 07 '22 at 10:56
  • checkout this answer https://stackoverflow.com/a/31191237/3651739 – Jishnu Prathap Nov 07 '22 at 10:59
  • What I still don't get: if you "don't know whether the code will execute or not", how will you know that any proposed solution actually works? – cyberbrain Nov 07 '22 at 13:47

0 Answers0