=-=代码基本和老师给的相同,只不过我在登陆的时候加了一个密码的验证。登陆成功后,发现查看用户信息时的中文用户名是乱码状态。我觉得应该是将用户名保存进cookie时出现了乱码,但存入cookie的方法是老师说的那种。主要代码贴出,请指教
这是dologin.jsp的内容
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.net.*" %> <jsp:useBean id="loginUser" class="com.po.Users" scope="page"/> <jsp:useBean id="userDAO" class="com.dao.UsersDAO" scope="page"/> <jsp:setProperty name="loginUser" property="*"/> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'dologin.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>登录判断</h1> <% response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); String[] isUseCookie = request.getParameterValues("isUseCookie"); if(userDAO.usersLogin(loginUser)) { if(isUseCookie !=null && isUseCookie.length>0) { String username = URLEncoder.encode(request.getParameter("username"),"utf-8"); //使用URLEncoder解决无法在Cookie当中保存中文字符串问题 String password = URLEncoder.encode(request.getParameter("password"),"utf-8"); Cookie usernameCookie = new Cookie("username",username); Cookie passwordCookie = new Cookie("password",password); usernameCookie.setMaxAge(864000); passwordCookie.setMaxAge(864000);//设置最大生存期限为10天 response.addCookie(usernameCookie); response.addCookie(passwordCookie); } else { Cookie[] cookies = request.getCookies(); if(cookies!=null && cookies.length>0) { for(Cookie c:cookies) { if(c.getName().equals("username") || c.getName().equals("password")) { c.setMaxAge(0); response.addCookie(c); } } } } request.getRequestDispatcher("login_success.jsp").forward(request, response); } else { response.sendRedirect("login_failure.jsp"); } %> </body> </html>
login.jsp和user.jsp的内容与老师给的是一样的
修改server.xml文档,在Connector标签里面添加URIEncoding="utf-8"应该能够解决
跟你一样,原来的样例直接拷贝,结果上面这三行没删:
<jsp:useBean id="loginUser" class="com.po.Users" scope="page"/> <jsp:useBean id="userDAO" class="com.dao.UsersDAO" scope="page"/> <jsp:setProperty name="loginUser" property="*"/>
就造成一直乱码,怀疑是javaBeans做处理时,更改了编码。
猜想因为前面表单中的username password,正好被上面配置的javabean给自动匹配上了。所以这个阶段处理时,编码发生了转换。
=-=使用复制粘贴不断进行对比后,发现问题竟然是出在
<jsp:useBean id="loginUser" class="com.po.Users" scope="page"/>
<jsp:useBean id="userDAO" class="com.dao.UsersDAO" scope="page"/>
<jsp:setProperty name="loginUser" property="*"/>
这段声明中,若是把这段代码删去,编码就没有问题。这是何等奇葩的现象,真心求解……
你数据库编码对不对