Java Web中登录时如何记住用户名呢?
具体思路:
登录界面如下:
在后台(Servlet 或struts 的action)中进行判断,若登录成功则通过HttpServletResponse 添加一个cookie.
在登录的jsp页面中,通过request 获取cookie数组,然后遍历,若找到相应的cookie,则把cookie的value设置到表单的对应文本框中.
具体代码如下:
登录的JSP页面中(核心代码):
- <body>
- <%
- Cookie[] cookies = request.getCookies();
- String username33="";
- if (cookies != null) {
- for (Cookie c : cookies) {
- /*if ("password22".equals(c.getName())) {
- user.setPassword(URLDecoder.decode(c.getValue(), "utf-8"));
- continue;
- }*/
- if ("userEmail".equals(c.getName())) {
- username33=URLDecoder.decode(c.getValue(), "utf-8");
- break;
- }
- }
- }
- %>
- <script type="text/javascript">
- window.onload=function(){
- var username1='<%=username33 %>';
- //alert("username1:"+username1);
- if(username1){
- if(username1!='' && username1!=null &&username1!=undefined){
- document.getElementsByName("user.username")[0].value=username1;
- }
- }
- }
- </script>
- ...
- </body>
后台的action:
- if (isLogin) {
- //保存用户名(目前是邮箱)
- String emaiCookieName = "userEmail";
- HttpServletRequest request=ServletActionContext.getRequest();
- Cookie[] cookies = request.getCookies();
- boolean flag = false;
- Cookie emailCook = null;
- if (cookies != null)
- {
- System.out.println("cookie 不为空");
- for (Cookie c : cookies)
- {
- if (emaiCookieName.equals(c.getName()))
- {
- System.out.println("找到了 "+emaiCookieName);
- System.out.println("cookie的值为 "+c.getValue());
- try {
- c.setValue(URLEncoder.encode(this.user.getUsername(), "utf-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- emailCook = c;
- flag = true;
- break;
- }
- }
- }
- if (!flag)
- {
- System.out.println("没有找到 "+emaiCookieName);
- try {
- emailCook = new Cookie(emaiCookieName, URLEncoder.encode(
- this.user.getUsername(), "utf-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- if (null != emailCook)
- {
- HttpServletResponse response=ServletActionContext.getResponse();
- if(!ValueWidget.isNullOrEmpty(issave) && issave.equalsIgnoreCase("save")){
- emailCook.setMaxAge(10000000);
- response.addCookie(emailCook);
- System.out.println("保存cookie");
- }else{
- System.out.println("让 cookie 失效");
- emailCook.setMaxAge(0);
- response.addCookie(emailCook);
- }
- }
- return Action.SUCCESS;
- }
源代码见附件
说明:
该项目使用maven 构建;
IDE:eclipse
登录地址:http://localhost:8080/shop_goods/user/loginInput.action