How to Use Session in Jsp Pages to Get Information

How to use session in JSP pages to get information?

JSP implicit objects likes session, request etc. are not available inside JSP declaration <%! %> tags.

You could use it directly in your expression as

<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>

On other note, using scriptlets in JSP has been long deprecated. Use of EL (expression language) and JSTL tags is highly recommended. For example, here you could use EL as

<td>Username: </td>
<td><input type="text" value="${username}" /></td>

The best part is that scope resolution is done automatically. So, here username could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as

<td><input type="text" value="${requestScope.username}" /></td> or,
<td><input type="text" value="${sessionScope.username}" /></td> or,
<td><input type="text" value="${applicationScope.username}" /></td>

How do you show session contents in a jsp page?

session.getAttribute("attributeName")

Try look here: How to use session in jsp pages to get information?

And try to google it more next time. I typed "java jsp get session" and it gave me the link above.

How to use the values from session variables in jsp pages that got saved using @Scope(session) in the mvc controllers

When you specify @Scope("session") for the controller, Spring will now ensure that there is a unique instance of the controller for every session, and so you will be able to keep a session specific state like sessionUser as a instance variable.

However to expose a variable to the UI, that variable has to be a part of the model/session attributes, you can do that either with @ModelAttribute("sessionUser") or @SessionAttribute("sessionUser")

@Controller
@SessionAttribute("sessionUser")
public class SignupController {
@RequestMapping("/SignupService")
public ModelAndView signUp(@RequestParam("userid") String userId,
@RequestParam("password") String password,@RequestParam("mailid") String emailId, Model model){
...
try {

signUpService.registerUser(userId, password,emailId);
sessionUser = userId; //adding the sign up user to the session
model.addAttribute("sessionUser", sessionUser);

return new ModelAndView("userHomePage","loginResult","Success");
//Navigate to user Home page if everything goes right
....
}
}


Related Topics



Leave a reply



Submit