Encoding是解决客户端与服务端之间数据传递的乱码问题,已经URL编码原理及作用

path:总结了很多servlet中的路径问题(重要)

HttpServletResponse:

package cn.HttpServletResponse.wyx;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpServletResponseTest extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        //sendError此方法用于发送400、500开头的错误响应码
        response.sendError(404,"您访问的资源为国家机密,请获取国防权限后继续访问");
        //setStatus此方法用于发送200、300开头的响应码
        //response.setStatus(302); 
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            String username =request.getParameter("username");
            getServletContext().setAttribute("username",username );
            response.addHeader("Location", "/day_10/Aservlet");
            response.setStatus(302);
    }

}
package cn.HttpServletResponse.wyx;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Aservlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<h3>欢迎"+getServletContext().getAttribute("username")+"访问本网站:<h3>");
        String referer = request.getHeader("referer");
        System.out.println(referer);
        if(referer!=null&&referer.contains("localhost")){
            out.println("华山论剑");
        }else{
            response.sendRedirect("/day_10/index.jsp");
        }
        
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

}

HttpServletRequest:

package cn.HttpServletRequest.wyx;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpServletRequestTest extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            int length = request.getContentLength();
            System.out.println("length:"+length);
            String ContentType = request.getContentType();
            System.out.println("ContentType:"+ContentType);
            String string = request.getHeader("User-Agent");
            System.out.println("user-agent:"+string);
            Map<String, String[]>values =request.getParameterMap();
            for (String name:values.keySet()) {
                String[]value = values.get(name);
                System.out.println("name:"+name+"value:"+Arrays.toString(value));
            }
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            
    }

}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'index.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>
  <a href="/day_10/HttpServletResponseTest?username=wangyinxu&passowrd=123123">submit</a>
    <form action="/day_10/HttpServletResponseTest" method="post">
        UserName:<input type="text" name="username"/><br/>
        Password:<input type="password" name="password"/><br/>
        Hobby:<br/><input type="checkbox" name="sleep">睡觉<br/>
        <input type="checkbox" name="eat"/>吃饭<br/>
        <input type="checkbox" name="coding">打代码<br/>
        <input type="submit" value="submitForm"/>
    </form>
  </body>
</html>
package cn.HttpServletRequest.wyx;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestForward extends HttpServlet {

    /**
     * 请求转发案例
     */
    private static final long serialVersionUID = 1L;


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            String username = request.getParameter("username");
            //System.out.println(username);
            byte[]bytes = username.getBytes("ISO-8859-1");
            username = new String(bytes, "utf-8");
            System.out.println(username);
            request.setAttribute("username", username);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("核武库001");
            request.getRequestDispatcher("/WelcomeServlet").forward(request, response);
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}
package cn.HttpServletRequest.wyx;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestInclude extends HttpServlet {

    /**
     * 请求包含案例
     */
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("utf-8");
            String[]values =request.getParameterValues("password");
            int time=1;
            String hello = "核武库002:";
            response.getWriter().print(hello+"<br/>");
            for (String value:values) {
                request.setAttribute("password"+time++, value);
            }
            request.getRequestDispatcher("/WelcomeServlet").include(request, response);
    }

}
package cn.HttpServletRequest.wyx;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WelcomeServlet extends HttpServlet {

    
    /**
     * 请求转发或者包含的处理
     */
    private static final long serialVersionUID = 1L;


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            
            String username = (String)request.getAttribute("username");
//            byte[]bytes = username.getBytes("iso-8859-1");
//            username = new String(bytes,"utf-8");
            response.getWriter().println("欢迎"+username+"将军访问核武库<br/><hr/>");
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            Enumeration<String> names = request.getAttributeNames();
            while(names.hasMoreElements()){
                String name = names.nextElement();
                String password = (String)request.getAttribute(name);
                response.getWriter().print(name+":"+password+"<br/>");
            }
            
    }

}
<!DOCTYPE html>
<html>
  <head>
    <title>requestForwardOrInclude.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <h3>军情五处</h3> <br>
    <a href="/day_10/RequestForward?username=五星上将">Get</a>
    <hr/>
    <form action="/day_10/RequestInclude" method="post">
        请输入核密码:<input type="password" name="password"/><br/>
        请确认核密码:<input type="password" name="password"/><br/>
        <input type="submit" name="button" value="发射">
    </form>
  </body>
</html>

编码问题:

<!DOCTYPE html>
<html>
  <head>
    <title>Encoding.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
   <h3>军情五处</h3> <br>
    <a href="/day_10/EnCoding?username=五星上将">Get</a>
    <hr/>
    <form action="/day_10/EnCoding" method="post">
        身份确认:<input type="text" name="username" value="五星上将"/><br/>
        请输入核密码:<input type="password" name="password"/><br/>
        请确认核密码:<input type="password" name="password"/><br/>
        <input type="submit" name="button" value="发射">
    </form>
  </body>
</html>

 

package cn.enCoding.wyx;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EnCoding extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //处理get请求参数编码乱码问题
        String username = request.getParameter("username");
        username=new String(username.getBytes("ISO-8859-1"),"utf-8");
        System.out.println(username);
        //处理服务器向客户端发送数据乱码问题
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("你好");
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //post请求处理参数乱码问题
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String[] password = request.getParameterValues("password");
        System.out.println("username:"+username+"password:"+Arrays.toString(password));
        //username:五星上将password:[123, 123]
    }

}
package cn.enCoding.wyx;

public class URLEncoding {
    //模拟url编码实现原理:
    //url编码应用于jsp中,主要解决超链接中传递参数丢失字节问题,
    //form表单中不需要处理,因为浏览器会自行处理为URL编码;
    public static void fun(String string){
        byte[]bytes = string.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            int Number  = bytes[i]+256;
             String num = Integer.toHexString(Number);
             System.out.print("%"+num);
        }
    }
    public static void main(String[] args) {
        fun("中国");
    }
    //输出结果:%e4%b8%ad%e5%9b%bd
}

项目中的路径总结:

package cn.paths.wyx;

import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class Paths extends HttpServlet {
/**
 * 路径总结:
 * url路径:http://localhost:8080/day_10/index.jsp?username=wangyinxu&password=123123(首次在网页url地址中输入的网址)
 * uri路径:/day_10(项目路径)/servlet路径(重定向,或者是超链接、form表单提交需要填写此路径)
 * servlet路径:web.xml中配置 的url-patten(请求转发或者包含只需要/servlet路径)
 * ClassLoader:这个类加载的是classse目录的路径(不需要加/)
 * Class:这个类加载的是.class文件所在的路径(不需要加/)
 * */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取的是路径是项目路径,带盘符的真实路径
            String  realpath =  getServletContext().getRealPath("/index.jsp");
            InputStream in1 = getClass().getResourceAsStream("path.txt");
            IOUtils.toString(in1);
            InputStream in2 = getClass().getClassLoader().getResourceAsStream("classsepath.txt");
            IOUtils.toString(in2);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}

  文件路径读取参照图