页面跳转之转发和重定向+Servlet中文乱码问题

页面跳转之转发和重定向+Servlet中文乱码问题

一、页面跳转


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <welcome-file-list>
        <welcome-file>welcome.htmlwelcome-file>
    welcome-file-list>
web-app>

1.页面跳页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>知识点:跳转h1>

    <hr/>

    <h3>页面跳页面h3>

    <a href="page01.html">跳转到Page01页面a><br/>
    <input type="button" value="跳转到Page01页面" onclick="fun01()"/><br/>
    <form action="page01.html" method="post" style="border:red 1px solid">
        账号:<input type="text" name="username" placeholder="请输入账号"><br/>
        密码:<input type="password" name="password" placeholder="请输入密码"><br/>
        <input type="submit" value="提交按钮"/>
    form>

    <script type="text/javascript">
        function fun01() {
            location = "page01.html";
        }
    script>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>Page01页面h1>
body>
html>

2.页面跳Servlet

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h3>页面跳Servleth3>
    <a href="Servlet01?username=aaa&password=123123">跳转到Servlet01a><br/>
    <input type="button" value="跳转到Servlet01" onclick="fun02()"/><br/>
    <form action="Servlet01" method="post" style="border:red 1px solid">
        账号:<input type="text" name="username" placeholder="请输入账号"><br/>
        密码:<input type="password" name="password" placeholder="请输入密码"><br/>
        <input type="submit" value="提交按钮"/>
    form>

    <script type="text/javascript">
        function fun02() {
            location = "Servlet01?username=bbb&password=123123"
        }
    script>
body>
html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/Servlet01")
public class Servlet01 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println("Servlet01接收到客户的请求了:" + username + "--" + password);
    }
}

3.Servlet跳Servlet

1.转发

request.getRequestDispatcher(“页面.html”).forward(request, response);

2.重定向

response.sendRedirect(“页面.html”);

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

    <h3>Servlet跳Servleth3>
    <a href="Servlet02">向Servlet02发送请求 -- 转发a><br/>
    <a href="Servlet03">向Servlet03发送请求 -- 重定向a>
    <hr/>
body>
html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/Servlet02")
public class Servlet02 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset:UTF-8");

        //转发
        request.getRequestDispatcher("OtherServlet").forward(request,response);
    }
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/OtherServlet")
public class OtherServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        System.out.println("OtherServlet接受到请求了...");
    }
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/Servlet03")
public class Servlet03 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //重定向
        response.sendRedirect("OtherServlet");
    }
}

4.Servlet跳页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h3>Servlet跳页面h3>
    <a href="Servlet04">向Servlet04发送请求 -- 转发a><br/>
    <a href="Servlet05">向Servlet05发送请求 -- 重定向a>

body>
html>

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

@WebServlet("/Servlet04")
public class Servlet04 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //转发
        request.getRequestDispatcher("page02.html").forward(request,response);
    }
}

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>Page02页面h1>
body>
html>

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

@WebServlet( "/Servlet05")
public class Servlet05 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //重定向
        response.sendRedirect("page02.html");
    }
}

二、转发与重定向的区别

区别1:转发是发送1次请求,重定向是发送2次请求

区别2:转发可以访问WEB-INF下的页面(受保护的页面),重定向不可以访问

区别3:重定向可以访问外部服务器,转发不可以访问

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <a href="Servlet06">向Servlet06发送请求 -- 做实验a>

body>
html>

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

@WebServlet("/Servlet06")
public class Servlet06 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //跳转普通页面(web文件夹下的页面)
        //转发 -- yes
        //request.getRequestDispatcher("page02.html").forward(request,response);
        //重定向 -- yes
        //response.sendRedirect("page02.html");

        //跳转受保护的页面(WEB-INF文件夹下的页面)
        //注意:WEB-INF文件夹下的页面只能服务器内部访问
        //转发 -- yes
        //request.getRequestDispatcher("WEB-INF/page03.html").forward(request,response);
        //重定向 -- no(原因:客户端不能直接访问WEB-INF文件夹下的页面)
        //response.sendRedirect("WEB-INF/page03.html");

        //跳转外部服务器
        //注意:当前服务器不能访问外部服务器
        //转发 -- no
        //request.getRequestDispatcher("http://www.baidu.com").forward(request,response);
        //重定向 -- yes(原因:重定向是发送两次请求,告诉客户端去访问外部服务器)
        response.sendRedirect("http://www.baidu.com");

    }
}


DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>page03页面h1>
body>
html>

三、Servlet中文乱码问题

1.出现原因

前端后端编码不一致

浏览器默认使用UTF-8码表进行编码 ,Servlet使用ISO-8859-1码表进行编码

传输和接收方编码不一致导致乱码的产生

2.Request乱码

Request请求分为post和get,分别有不同的解决方案

1.Request乱码 - POST请求

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//给请求中的参数设置编码格式
		request.setCharacterEncoding("UTF-8");
		
		String parameter1 = request.getParameter("parameter1");
		String parameter2 = request.getParameter("parameter2");
		System.out.println(parameter1);
		System.out.println(parameter2);
}

作用:设置从 request 中取得的值,用来指定对浏览器发送来的数据进行重新编码时,使用的编码。

使用注意事项:

  • 在执行 setCharacterEncoding()之前,不能执行任何 getParameter()操作
  • 通过 setCharacterEncoding 设置的编码方式只对 POST 方式提交的表单有效,对 GET 方式无效

2.Request乱码 - GET请求(Tomcat7.X版本)

解决方案1

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
		String parameter1 = request.getParameter("parameter1");
		parameter1 = new String(parameter1.getBytes("ISO-8859-1"),"UTF-8");
		String parameter2 = request.getParameter("parameter2");
		parameter2 = new String(parameter2.getBytes("ISO-8859-1"),"UTF-8");
		
		System.out.println(parameter1);
		System.out.println(parameter2);
}

解决方案2

在Tomcat根目录/conf/server.xml中设置编码格式

<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1" 			
           connectionTimeout="20000" redirectPort="8443" 
/>

那么在启动服务器的时候就会读取到URIEncoding的属性配置,然后再调用自己的一个setURIEncoding方法完成设置,形参的值为我们设置的UTF-8

protected String URIEncoding = null;
public void setURIEncoding(String URIEncoding) {
         this.URIEncoding = URIEncoding;
         setProperty("URIEncoding", URIEncoding);
}

3.Request乱码 - GET请求(Tomcat8.X版本)

Tomcat8.x的服务器在接收GET请求时,即使参数中有中文,也不会出现乱码,作者在底层设计上的一些改动

Tomcat的连接器组件(Connector) ,Connector是Tomcat中的一个重要的组件,它负责监听Tomcat收到的请求信息,并将这些请求信息传递给Servlet规范中所定义的Request,然后将转换后的请求交给Engine组件

去处理,最后将Engine返回的Response返回给客户端 。源码中我们可以看到, URIEncoding的默认值为UTF-8,所以在Tomcat8.x中,即使GET请求包含了中文的数据,也不会出现乱码了

public class Connector extends LifecycleMBeanBase  {
    
    private Charset uriCharset = StandardCharsets.UTF_8;
   
    //查询Tomcat根目录/conf/catalina.properties配置文件中的属性
	public static final boolean RECYCLE_FACADES =
Boolean.parseBoolean(System.getProperty("org.apache.catalina.connector.RECYCLE_FACADES", "false"));   
    
    public Connector() {
        this(null);
    }
    
    public Connector(String protocol) {
        setProtocol(protocol);
        ProtocolHandler p = null;
        try {
            Class<?> clazz = Class.forName(protocolHandlerClassName);
            p = (ProtocolHandler) clazz.getConstructor().newInstance();
        } catch (Exception e) {
            log.error(sm.getString(
                    "coyoteConnector.protocolHandlerInstantiationFailed"), e);
        } finally {
            this.protocolHandler = p;
        }

        if (Globals.STRICT_SERVLET_COMPLIANCE) {
            uriCharset = StandardCharsets.ISO_8859_1;
        } else {
            uriCharset = StandardCharsets.UTF_8;
        }
    }
}

4.Response乱码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	//设置响应内容的编码格式
	response.setContentType("text/html;charset=UTF-8");
		
	response.getWriter().println("千锋吴彦祖");
}

5.跳转到中文页面路径乱码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	response.sendRedirect(URLEncoder.encode("详情页面.html", "UTF-8"));
}

四、跳转到中文名的页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h3>知识点:跳转到中文名的页面h3>
    <a href="Servlet07">跳转到中文名的页面a>
 
body>
html>

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet( "/Servlet07")
public class Servlet07 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //注意:中文名的网页一定要设置编码格式
        response.sendRedirect(URLEncoder.encode("用良心做教育.html","UTF-8"));
    }
}

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>用真心待人h1>
body>
html>

你可能感兴趣的:(JavaWeb与服务器,servlet,java,前端,javascript,tomcat)