Display the UserName and the localTime in a JSP
I am working in a JSP/Servlet project (Java EE) with Eclipse. I want to display the current user logged in the page and the localTime. My JSP of LOG IN worked well开发者_开发技巧 but I have no idea how to display the user name in the jsp where he is logged.
How is the user logging in? Typically the user's log in id/username can be saved on the server-side once you've verified their credentials in the session and the jsp can then reference that session variable when needed.
Servlet:
request.getSession().setAttribute("username", username);
JSP:
<%=session.getAttribute("username")%>
You normally have an User
object (javabean, entity, data transfer object, whatever).
public class User {
private Long id;
private String name;
private Integer age;
// Add/generate public getters and setters.
}
You normally have a DAO class which loads, finds, saves, updates those objects in/from the DB.
public class UserDAO {
public User find(String name, String password) {
// ...
}
public void save(User user) {
// ...
}
// ...
}
You normally have a Servlet class which controls the login. If found, then store User
in session so that your application can intercept on the login by just checking its presence in the session.
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("home");
} else {
request.setAttribute("message", "Unknown username/password combo.");
request.getRequestDispatcher("login").forward(request, response);
}
}
You normally use EL to access "backend data", i.e. all attributes which are available in page, request, session or application scopes.
<p>Welcome ${user.name}!</p>
This prints the value of user.getName()
.
Now the localtime: I bet that you mean the client time with this. You can better use JavaScript for this since the server time is fixed and may not be the same as the client's one and there's no direct way to figure that in the server side (or you must use JS/Ajax to send the client's timezone to the server side).
<script type="text/javascript">
var localTime = new Date();
alert(localTime);
var timezoneOffset = localTime.getTimezoneOffset() / 60 * -1;
alert('Timezone: UTC' + timezoneOffset); // You may want to send this to server.
</script>
I know that I've recommended you this several times before, but here it is again: leave aside this work for a while and prepare youself to learn JSP/Servlet first. Those tutorials are very good. Learn walking before running or even bicycling or even cardriving. Right now you can yet creep and you're right trying to drive a car. That would only lead to trouble.
In JSP you can use:
<s:property value="#session.username"/>
精彩评论