I am fetching username from database when a user is logging in by his userid. so if userid is let’s say mat is logging then I am displaying the name as Mathews in userhome.jsp.
I have 5 jsp pages and in each page instead of writing a sql query (to fetch username from database by their id) I am defining a class Username.java and want to return userName to each jsp page. But this error is coming:
`HttpSession session1 = request.getSession(false);`
The error tells me to define a request class. How can I solve it?
public class Username {
public String getUserName(Long userId) {
HttpSession session1 = request.getSession(false);// error is coming here for request
String userid = (String)session1.getAttribute("userid");
// I want to fetch user name from database by the userid above
String userName = "";
//all my sql code here
return userName;
}
}
I am writing the following code in the jsp:
Username uName = new Username ();
uName.getUserName (userId);
The implicit object ‘request’ is only available in your JSP page. For the class that you are defining, the object is not present. You will have to define it explicitly.
One solution would be to get the Session in the JSP page and pass it as an argument (may be to a constructor) to your class.
For eg, You could define a constructor in the class like this:-
Then modify the code in JSP page like:-