Reputation: 33
In my project i'm using session and saving it while storing data in session variable we can validate but while retrieving how can we validate data?ex:
String studentId = (String) session.getAttribute("stdID");
How can i know that correct data is getting,please help me.
Upvotes: 0
Views: 1206
Reputation: 417672
Why do you need to validate data when getting it from the session?
You should always and only validate data before you store it in the session. And if it is not valid, do not store it in the session. That way every time when you read some data from the session, you can be sure it is valid. And of course this way you only have to validate it once.
Validating before storing it in the session:
// Lets assume student id comes from the client as a request parameter:
String studentId = request.getParameter("stdID");
// Check / validate it
if (studentId == null || studentId.isEmpty() || !existsInDb(studentId)) {
// Student id is invalid, send back error message
// or redirect to some error page or login page
}
else {
// Student id is valid, safe to store it in the session:
request.getSession().setAttribute("stdID", studentId);
}
Upvotes: 1