关键代码如下:
登录页面:login.jsp
<form action="doLogin.jsp" method="post"> 用户名:<input type="text" name="sname" /><br/> 密码:<input type="text" name="spass"/><br/> <input type="submit" value="登录"/> </form>
处理登录业务的doLogin.jsp
<%@page import="java.net.URLEncoder"%> <%@page import="org.dao.impl.StudentDaoImpl"%> <%@page import="org.dao.IStudentDao"%> <%@page import="org.entity.Student"%> <%@page import="org.service.impl.StudentServiceImpl"%> <%@page import="org.service.IStudentService"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% //创建Service的对象 IStudentService studentService = new StudentServiceImpl(); //解决乱码的问题 request.setCharacterEncoding("utf-8"); //获取表单的值 String sname = request.getParameter("sname"); String spass = request.getParameter("spass"); //调用service的方法进行登陆 Student stu = studentService.login(sname, spass); if(stu.getSid()!=0){ //登陆成功 //将用户名放入到Cookie里面 Cookie scook = new Cookie("sname",sname); response.addCookie(scook); //将登陆信息放在Session中 //session.setAttribute("sname",sname); request.getRequestDispatcher("index.jsp") .forward(request,response); } %>
登录成功跳转到的页面:index.jsp
<body> <h1>欢迎进入学生管理系统</h1> <% Cookie cookie[] = request.getCookies(); for(int i=0;i<cookie.length;i++){ Cookie cook = cookie[i]; if(cook.getName().equals("sname")){ %> 你好:<%=cook.getValue()%> <% } } %> <%-- <% String sname =(String)session.getAttribute("sname"); if(sname==null){ response.sendRedirect("login.jsp"); } %> <%=sname %> --%> </body>
代码都写的没问题,就是报错:
ava.lang.IllegalArgumentException: Control character in cookie value or attribute.
后来用英文的昵称登录,正常显示:
看来就是中文编码的问题了,在网上查了查,确实是编码的问题,只需要在放置cookie的时候,设置编码格式为UTF-8,并且在显示时,设置编码格式也为UTF-8,问题完美解决,修改过后的代码如下:
登录业务处理:doLogin.jsp
Cookie scook = new Cookie("sname",URLEncoder.encode(sname,"UTF-8"));
登录成功:index.jsp
<% Cookie cookie[] = request.getCookies(); for(int i=0;i<cookie.length;i++){ Cookie cook = cookie[i]; if(cook.getName().equals("sname")){ %> 你好:<%=URLDecoder.decode(cook.getValue(),"UTF-8")%> <% } } %>
切记切记,在讲中文字符往Cookie中放的时候,一定要设置编码格式。