I am beginner at using JSP and am following a tutorial. I have a basic question. There is a simple class named NameHandler that has only one String field called name.
index.jsp looks like this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Entry Form</h1>
<form name="Name Input Form" action="response.jsp">
Enter name
<input type="text" name="name"/>
<input type="submit" value="OK" />
</form>
</body>
</html>
and response.jsp looks like this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body><jsp:useBean id="mybean" scope="session" class="org.mypackage.hello.NameHandler" />
<jsp:setProperty name= "mybean" property= "name"/>
<h1>Hello, <jsp:getProperty name="mybean" property="name" />!</h1>
</body>
</html>
My question is this: I tried to understand how this sets the name member in NameHandler class when the user enters a string. here what does name =”name” mean? I tried to understand how this sets the name member of the class. The code works correctly, so where and how does this set the name member of the class?
I also know that I can use the name of the bean and call a class function like <%=beanname.classfunction %>. So which one is better? First way or second way? What are the differences.
The tag
<jsp:setProperty name= "mybean" property= "name"/>works as the following. First it finds bean namedmybean. The it takes value ofpropertyattribute (namein your case), capitalizes it and prependsset, and constructs method name:String methodName = "get" + str.substring(0, 1).toUpperCase() + str.toLowerCase(str).Then it calls
getMethod(methodName)If this call succeeds it calls it using
method.invoke()