-2
@RequestMapping("/returnformv2")
public String serveletTest(HttpServletRequest request){        
    String firstname = request.getParameter("fname");
    String lastname = request.getParameter("lname");
    String fullname = lastname.concat(firstname);
    request.setAttribute("fullname", fullname);     
    return "helloworld";
}

Now if I retrieve from JSP, ${fullname} is lastname.concat(firstname). Let me show some basic java code, say I call serveletTest("hello");

public String serveletTest(String myString){        
    System.out.println(myString);
    myString = myString.concat(world);
    return "bye world";
}

myString should be still "hello" right?

For me, getParameter() from HttpServletRequest makes sense but not request.setAttribute(). Could someone please explain how this works?

felixC
  • 91
  • 2
  • 9
  • request.setAttribute("fullname", fullname); sends the String object "fullname" to your jsp. If HttpServletRequest makes sense to you than request.setAttribute() should also make sense. – AchillesVan Sep 25 '16 at 09:05
  • 1
    If you assign back to the `myString`, you will see the updated `myString`. Like `myString=myString.concat(world);`. Same applies to `fullName` scenario as well. – Madhusudana Reddy Sunnapu Sep 25 '16 at 09:10
  • Please check in this question: http://stackoverflow.com/questions/5243754/difference-between-getattribute-and-getparameter – Shweta Gulati Sep 25 '16 at 10:11
  • `myString` will still be `hello` because strings are immutable. `String.concat` does not alter a string, but returns a new string which is the result of concating strings. – Brandon Sep 25 '16 at 12:56

1 Answers1

0

I found the answer I was looking for. X( RequestDispatcher was doing all the magic...

According to javadoc,

void javax.servlet.ServletRequest.setAttribute(String name, Object o)

Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher.

web.xml --> Configure Spring MVC Dispatcher Servlet and Set up URL mapping

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
felixC
  • 91
  • 2
  • 9