1. 程式人生 > >cookie亂碼處理 示例

cookie亂碼處理 示例

utf cep char title nco tor asm edi www

package com.log;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet.do")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, 

HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse 

response) throws ServletException, IOException {
       //首先設置響應和請求頁面的編碼格式:
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html charset=‘utf-8‘");
       //獲取表單控件的數據
        Enumeration
<String> nameEnu = request.getParameterNames(); //創建list對象 List<Object> list = new ArrayList<>(); while(nameEnu.hasMoreElements()) { list.add(request.getParameter(nameEnu.nextElement())); } //把數據放在session對象 HttpSession session = request.getSession(); if(list.size()>0){ session.setAttribute("uName", list.get(0)); } //第二種方式,通過Cookie保存用戶信息 Cookie cook1 = new Cookie("userName", URLEncoder.encode (list.get(0).toString(),"utf-8")); cook1.setMaxAge(3*3600); response.addCookie(cook1); // request.getRequestDispatcher("/main.jsp").forward(request, response); response.sendRedirect(request.getContextPath()+"/welcome.jsp"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } 接受頁面:
<%@page import="java.net.URLDecoder"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type"
content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <% session.setAttribute("uName", "你好"); System.out.print(session.getId()); %> <% //獲取cookie對象 Cookie[] getCooks = request.getCookies(); String user = null; if(getCooks.length > 0) { user = getCooks[0].getValue(); user = URLDecoder.decode(user, "utf-8"); } %> <body> <%=session.getAttribute("uName") %>已進入主頁! <%=user%> <button onclick="location.href=‘main.jsp?u1=<%=user %>‘" type="button">跳轉傳 參</button> </body> </html>

cookie亂碼處理 示例