javaweb

tomcat初使用

package com.jxb;

import javax.servlet.*;
import java.io.IOException;

public class servlet implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("bb");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
    //开发一个servlet需要实现servlet接口
}


<?xml version="1.0" encoding="UTF-8"?>
<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">
    <servlet>
        <servlet-name>helloservlet</servlet-name>
        <servlet-class>com.jxb.servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>helloservlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

代码总章

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <!--老韩小技巧: web.xml主要用来配置该web应用使用到的Servlet
        老师解读
        1. servlet-name:Servlet取名(程序员决定), 该名字唯一
        2. servlet-class: Servlet的类的全路径: Tomcat在反射生成该Servlet需要使用
        3. url-pattern: 这个就是该servlet访问的url的配置(路径)
        4. 这时我们应该这样访问servlet http://localhost:8080/servlet/helloServlet
        5. url-pattern 取名是程序员决定的
        6. load-on-startup 表示在tomcat 启动时,会自动的加载servlet实例

        小技巧: alt+r => 老师配置
    -->
    <!-- 配置HelloServlet -->
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.hspedu.servlet.HelloServlet</servlet-class>
        <!--<load-on-startup>1</load-on-startup>-->
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/helloServlet</url-pattern>
    </servlet-mapping>

<!--       &lt;!&ndash; 配置HiServlet &ndash;&gt;-->
    <!--    <servlet>-->
    <!--        <servlet-name>HiServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.HiServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>HiServlet</servlet-name>-->
    <!--        <url-pattern>/hiServlet</url-pattern>-->
    <!--    </servlet-mapping>-->
    <!--    &lt;!&ndash;这里是idea自动生成的配置&ndash;&gt;-->
    <!--    <servlet>-->
    <!--        <servlet-name>OkServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.OkServlet</servlet-class>-->
    <!--    </servlet>-->
    <!--    &lt;!&ndash;OkServlet进行url配置&ndash;&gt;-->
    <!--    <servlet-mapping>-->
    <!--        <servlet-name>OkServlet</servlet-name>-->
    <!--        <url-pattern>/okServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    &lt;!&ndash;配置CatServlet&ndash;&gt;-->
    <!--    <servlet>-->
    <!--        <servlet-name>CatServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.homework.CatServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>CatServlet</servlet-name>-->
    <!--        <url-pattern>/cat</url-pattern>-->
    <!--    </servlet-mapping>-->
    <!--    &lt;!&ndash;配置DogServlet&ndash;&gt;-->
    <!--    <servlet>-->
    <!--        <servlet-name>DogServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.homework.DogServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>DogServlet</servlet-name>-->
    <!--        <url-pattern>/dog</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    &lt;!&ndash;配置DBServlet&ndash;&gt;-->
    <!--    <servlet>-->
    <!--        <servlet-name>DBServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.DBServlet</servlet-class>-->
    <!--        &lt;!&ndash;配置信息,而不是硬编码到程序&ndash;&gt;-->
    <!--        <init-param>-->
    <!--            <param-name>username</param-name>-->
    <!--            <param-value>hsp</param-value>-->
    <!--        </init-param>-->
    <!--        <init-param>-->
    <!--            <param-name>pwd</param-name>-->
    <!--            <param-value>123456</param-value>-->
    <!--        </init-param>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>DBServlet</servlet-name>-->
    <!--        <url-pattern>/db</url-pattern>-->
    <!--    </servlet-mapping>-->
    <!--    &lt;!&ndash;配置ServletContext_&ndash;&gt;-->
    <!--    <servlet>-->
    <!--        <servlet-name>ServletContext_</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.servletcontext.ServletContext_</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>ServletContext_</servlet-name>-->
    <!--        <url-pattern>/servletContext_</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>OrderServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.servletcontext.OrderServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>OrderServlet</servlet-name>-->
    <!--        <url-pattern>/orderServlet</url-pattern>-->
    <!--    </servlet-mapping>-->
    <!--    <servlet>-->
    <!--        <servlet-name>PayServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.servletcontext.PayServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>PayServlet</servlet-name>-->
    <!--        <url-pattern>/payServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>HttpServletRequestMethods</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.request.HttpServletRequestMethods</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>HttpServletRequestMethods</servlet-name>-->
    <!--        <url-pattern>/requestMethods</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>CheckServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.request.CheckServlet</servlet-class>-->
    <!--    </servlet>-->
    <!--    <servlet-mapping>-->
    <!--        <servlet-name>CheckServlet</servlet-name>-->
    <!--        <url-pattern>/checkServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>ManageServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.request.ManageServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>ManageServlet</servlet-name>-->
    <!--        <url-pattern>/manageServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>RegisterServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.request.homework.RegisterServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>RegisterServlet</servlet-name>-->
    <!--        <url-pattern>/registerServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>ComputerServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.request.homework.ComputerServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>ComputerServlet</servlet-name>-->
    <!--        <url-pattern>/computerServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>DownServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.response.DownServlet</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>DownServlet</servlet-name>-->
    <!--        <url-pattern>/downServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>DownServletNew</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.response.DownServletNew</servlet-class>-->
    <!--    </servlet>-->

    <!--    <servlet-mapping>-->
    <!--        <servlet-name>DownServletNew</servlet-name>-->
    <!--        <url-pattern>/downServletNew</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    <servlet>-->
    <!--        <servlet-name>MyPayServlet</servlet-name>-->
    <!--        <servlet-class>com.hspedu.servlet.response.homework.MyPayServlet</servlet-class>-->
    <!--    </servlet>-->
    <!--    <servlet-mapping>-->
    <!--        <servlet-name>MyPayServlet</servlet-name>-->
    <!--        <url-pattern>/myPayServlet</url-pattern>-->
    <!--    </servlet-mapping>-->

    <!--    &lt;!&ndash;配置整个网站的信息&ndash;&gt;-->
    <!--    <context-param>-->
    <!--        <param-name>website</param-name>-->
    <!--        <param-value>http://www.hanshunping.net</param-value>-->
    <!--    </context-param>-->
    <!--    <context-param>-->
    <!--        <param-name>company</param-name>-->
    <!--        <param-value>韩顺平教育</param-value>-->
    <!--    </context-param>-->
    </web-app>

package com.hspedu.servlet;

/**
 * @author 韩顺平
 * @version 1.0
 */

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 老韩解读
 * 1. 开发一个Servlet 需要 实现Servlet接口
 * 2. 实现Servlet接口的方法5个
 */
public class HelloServlet implements Servlet {


    private int count = 0; //属性

    /**
     * 1.初始化 servlet
     * 2.当创建HelloServlet 实例时,会调用init方法
     * 3. 该方法只会被调用一次
     * @param servletConfig
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("init() 被调用");
    }

    /**
     * 返回ServletConfig 也就是返回Servlet的配置
     * @return
     */
    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * 1. service方法处理浏览器的请求(包括get/post)
     * 2. 当浏览器每次请求Servlet时,就会调用一次service
     * 3. 当tomcat调用该方法时,会把http请求的数据封装成实现ServletRequest接口的request对象
     * 4. 通过servletRequest 对象,可以得到用户提交的数据
     * 5. servletResponse 对象可以用于返回数据给tomcat->浏览器
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest,
                        ServletResponse servletResponse) throws ServletException, IOException {

        count++;
        //如果count的值,在不停的累计,说明HelloServlet是单例的
        System.out.println("hi HelloServlet~ count= " + count);
        //Tomcat每处理一次http请求,就生成一个新的线程
        System.out.println("当前线程id= " + Thread.currentThread().getId());

        //思考->从servletRequest对象来获取请求方式->
        //1. ServletRequest 没有得到提交方式的方法
        //2. ServletRequest 看看ServletRequest子接口有没有相关方法
        //3. 老师小技巧:ctrl+alt+b => 可以看到接口的子接口和实现子类
        //4. 把servletReqeust转成 HttpServletRequest引用
        //5. 仍然是Java基础的OOP
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String method = httpServletRequest.getMethod();
        if("GET".equals(method)) {
            doGet(); //用doGet() 处理GET请求
        } else if("POST".equals(method)) {
            doPost(); //用doPost() 处理POST请求
        }

    }

    /**
     * 用于响应get请求的
     */
    public void doGet() {
        System.out.println("doGet() 被调用..");
    }

    /**
     * 用于响应post请求的
     */
    public void doPost() {
        System.out.println("doPost() 被调用..");
    }

    /**
     * 返回servlet信息,使用较少
     * @return
     */
    @Override
    public String getServletInfo() {
        return null;
    }

    /**
     * 1. 该方法是在servlet销毁时,被调用
     * 2. 只会调用一次
     */
    @Override
    public void destroy() {
        System.out.println("destroy() 被调用...");
    }
}

hi HelloServlet~ count= 2
当前线程id= 26
doGet() 被调用..

tomcat入门

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class jxb {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9998);
        //在9999窗口监听
        while (!serverSocket.isClosed()) {
            System.out.println("等待监听");
            //如果没有关闭就一直等待连接
            Socket socket = serverSocket.accept();
            //等待浏览器连接得到socket
            OutputStream outputStream = socket.getOutputStream();
            //读取文件
            BufferedReader bufferedReader = new BufferedReader(new
                    FileReader("src/hello.html"));
            String buf="";
            while ((buf=bufferedReader.readLine())!=null){
                outputStream.write(buf.getBytes());
            }
            outputStream.write("hello,my dear jack".getBytes());
            //得到字节输出流,将数据返回给客户端或浏览器
            outputStream.close();
            socket.close();
        }

        serverSocket.close();
    }
}

作业

package com.hspedu.servlet.homework;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author 韩顺平
 * @version 1.0
 */
public class CatServlet implements Servlet {


    //定义一个记录访问次数的变量
    private int count = 0;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

        //一个快捷键 可以快速的在访问的文件切换  ctrl + alt + <- 回到上次访问的位置
        //ctrl + alt + -> 反向
        //访问的方式
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        System.out.println("访问的方式= " + httpServletRequest.getMethod());

        System.out.println("访问CatServlet的次数= " + (++count));
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

作业2

package com.hspedu.servlet.homework;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class DogServlet extends HttpServlet {

    //定义两个变量
    private int getCount = 0;
    private int postCount = 0;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("DogServlet doPost 访问次数= " + (++postCount));
    }

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

        System.out.println("DogServlet doGet 访问次数= " + (++getCount));
    }
}

作业3

package com.hspedu.servlet.homework;

import javax.servlet.ServletConfig;
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;

/**
 * @author 韩顺平
 * @version 1.0
 * 听老韩.
 */
@WebServlet(urlPatterns = {"/pig1", "/pig2"}, loadOnStartup = 1)
public class PigServlet extends HttpServlet {

    private int getCount = 0;
    private int postCount = 0;

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("PigServlet init() 被调用~");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //你是一个OOP程序员[潜台词是 一定要考虑使用对象方法]
        System.out.println("访问的浏览器的ip= " + req.getRemoteAddr());
        System.out.println("PigServlet 的 doPost方法被访问了 " + (++postCount));

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("访问的浏览器的ip= " + req.getRemoteAddr());
        System.out.println("PigServlet 的 doGet方法被访问了 " + (++getCount));
    }
}

配置方式注解

package com.annotation;

import javax.jws.WebService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
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(urlPatterns={"/ok1","/ok2"},initParams = @WebInitParam(name = "xx",
        value = "yy"))

//给okservlet配置多个url-pattern
public class serevlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注解doget");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注解dopost");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("注解init被调用");
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<!--load表示在tomcat启动时自动去加载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">
<!--    <servlet>-->
<!--        <servlet-name>helloservlet</servlet-name>-->
<!--        <servlet-class>com.jxb.servlet</servlet-class>-->
<!--        <load-on-startup>1</load-on-startup>-->
<!--    </servlet>-->
<!--    <servlet-mapping>-->
<!--        <servlet-name>helloservlet</servlet-name>-->
<!--        <url-pattern>/hello</url-pattern>-->
<!--    </servlet-mapping>-->
<!--    配置hservlet-->
    <servlet>
        <servlet-name>hservlet</servlet-name>
        <servlet-class>com.hservlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hservlet</servlet-name>
        <url-pattern>/hservlet</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>okservlet</servlet-name>
        <servlet-class>com.okServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>okservlet</servlet-name>
        <url-pattern>/okservlet</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>catservlet</servlet-name>
        <servlet-class>com.jxb.homework.catservlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>catservlet</servlet-name>
        <url-pattern>/cat</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>dogservlet</servlet-name>
        <servlet-class>com.jxb.homework.dogservlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>dogservlet</servlet-name>
        <url-pattern>/dog</url-pattern>
    </servlet-mapping>
</web-app>

继承类配置

package com;

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

public class hservlet extends HttpServlet {
    //重写httpservlet的doget和dopost方法
    //alt+insert



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doget");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("dopost");
    }
}

重定向

package com.hspedu.http.servlet;

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

public class t1Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//            response.sendRedirect("/http/hi.html");
response.sendRedirect("http://www.baidu.com");
    }

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

    }
}

浏览器登陆

package com.hspedu.http.servlet;

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

public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws javax.servlet.ServletException,
            IOException {
        System.out.println("jack");
        response.setContentType("text/html;charset=utf-8");
        //设置编码让浏览器显示中文
        PrintWriter writer= response.getWriter();
        writer.print("登陆成功");
        writer.flush();
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("我是帅哥");
        response.setContentType("text/html;charset=utf-8");
        //设置编码让浏览器显示中文
        PrintWriter writer= response.getWriter();
        writer.print("登陆成功");
        writer.flush();
        writer.close();
    }
}

浏览器访问次数

package com.hspedu.servlet.servletcontext;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class OrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取到ServletContext对象
        ServletContext servletContext = getServletContext();
        // System.out.println("OrderServlet servletContext= " +
        //         servletContext + " 运行类型=" + servletContext.getClass());

        // //从servletContext获取 visit_count 属性 k-v
        // Object visit_count = servletContext.getAttribute("visit_count");
        // //判断visit_count是否为null
        // if (visit_count == null) {//说明是第1次访问网站
        //     servletContext.setAttribute("visit_count", 1);
        //     visit_count = 1;
        // } else { //是第二次或以后
        //     //取出visit_count属性的值+1
        //     visit_count = Integer.parseInt(visit_count + "") + 1;
        //     //放回到servletContext
        //     servletContext.setAttribute("visit_count", visit_count);
        // }

        Integer visit_count = WebUtils.visitCount(servletContext);

        //输出显示
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("

新网站被访问的次数是" + visit_count + "

"
); writer.flush(); writer.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
package com.hspedu.servlet.servletcontext;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class PayServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取到ServletContext对象
        ServletContext servletContext = getServletContext();
        // System.out.println("PayServlet servletContext= " +
        //         servletContext + " 运行类型=" + servletContext.getClass());
        //
        // //从servletContext获取 visit_count 属性 k-v
        // Object visit_count = servletContext.getAttribute("visit_count");
        // //判断visit_count是否为null
        // if (visit_count == null) {//说明是第1次访问网站
        //     servletContext.setAttribute("visit_count", 1);
        //     visit_count = 1;
        // } else { //是第二次或以后
        //     //取出visit_count属性的值+1
        //     visit_count = Integer.parseInt(visit_count + "") + 1;
        //     //放回到servletContext
        //     servletContext.setAttribute("visit_count", visit_count);
        // }
        Integer visit_count = WebUtils.visitCount(servletContext);
        //输出显示
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("

新网站被访问的次数是" + visit_count + "

"
); writer.flush(); writer.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
package com.hspedu.servlet.servletcontext;

import javax.servlet.ServletContext;

/**
 * @author 韩顺平
 * @version 1.0
 */
public class WebUtils {

    //这个方法就是对访问的次数累积,同时返回次数
    public static Integer visitCount(ServletContext servletContext) {
        //从servletContext获取 visit_count 属性 k-v
        Object visit_count = servletContext.getAttribute("visit_count");
        //判断visit_count是否为null
        if (visit_count == null) {//说明是第1次访问网站
            servletContext.setAttribute("visit_count", 1);
            visit_count = 1;
        } else { //是第二次或以后
            //取出visit_count属性的值+1
            visit_count = Integer.parseInt(visit_count + "") + 1;
            //放回到servletContext
            servletContext.setAttribute("visit_count", visit_count);
        }

        return Integer.parseInt(visit_count + "");
    }
}

servletcontext使用方法

package com.hspedu.servlet.servletcontext;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class ServletContext_ extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取web.xml的context-parameter

        //1.获取到ServletContext对象
        ServletContext servletContext = getServletContext();
        //2. 获取website
        String website = servletContext.getInitParameter("website");
        String company = servletContext.getInitParameter("company");
        //3. 获取项目的工程路径
        String contextPath = servletContext.getContextPath();
        //4. 获取项目发布会,正在的工作路径
        //   /表示我们的项目(发布后)的 根路径 D:\hspedu_javaweb\servlet\out\artifacts\servlet_war_exploded
        String realPath = servletContext.getRealPath("/");
        System.out.println("项目路径= " + contextPath);// /servlet
        System.out.println("website= " + website);
        System.out.println("company= " + company);
        System.out.println("项目发布后的绝对路径= " + realPath);

    }

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

request入门方法

package com.hspedu.servlet.request;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class HttpServletRequestMethods extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //这里我们使用request对象,获取表单提交的各种数据
        System.out.println("HttpServletRequestMethods doPost() 被调用..");

        /***********************************
         *  获取和http请求头相关信息
         ***********************************/

        System.out.println("请求的资源路径URI= " + request.getRequestURI());
        //http://主机/uri
        System.out.println("请求的统一资源定位符(绝对路径)URL= " + request.getRequestURL());
        System.out.println("请求的客户端ip 地址= " + request.getRemoteAddr());//本地就是127.0.01
        //思考题:如发现某个ip 在10s中,访问的次数超过 100次,就封ip
        //实现思路: 1用一个集合concurrentHashmap[ip:访问次数] 2[线程/定时扫描] 3 做成处理
        // 获取http请求头的信息,可以指定其他,比如 User-Agent , Host等待 老师就举一个例子
        System.out.println("http请求头HOST= " + request.getHeader("Host"));
        // 说明,如果我们希望得到请求的头的相关信息,可以使用request.getHeader("请求头字段")
        System.out.println("该请求的发起地址是= " + request.getHeader("Referer"));
        // 请获取访问网站的浏览器是什么?
        String userAgent = request.getHeader("User-Agent");
        System.out.println("User-Agent= " + userAgent);
        // 取出FireFox, 取出最后
        String[] s = userAgent.split(" ");
        System.out.println("浏览器=" + s[s.length - 1].split("\\/")[0]);
        //获取 Cookie
        // 	JSESSIONID=8CBBD23BDE01BAE6705E03C5C8916BD1

        String cookie = request.getHeader("Cookie");
        String JSESSIONID = cookie.split("=")[1];
        System.out.println("取出JSESSIONID= " + JSESSIONID);

        //课堂练习: 要求同学们取出  Windows NT 10.0  和 Win64
        // 主要是Get / Post
        System.out.println("http请求方式~= " + request.getMethod());
        /***********************************
         *  获取和请求参数相关信息, 注意要求在返回数据前,获取参数
         ***********************************/

        //解决接收参数的中文乱码问题, 老师提示,写在 getParameter前.
        request.setCharacterEncoding("utf-8");
        //1. 获取表单的数据[单个数据]
        //username=tom&pwd=&hobby=hsp&hobby=spls
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");


        //2. 获取表单一组数据
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println("username= " + username);
        System.out.println("pwd= " + pwd);
        //增强for循环的快捷键 iter->回车即可 , 能使用快捷键,就使用快捷键
        for (String hobby : hobbies) {
            System.out.println("hobby=" + hobby);
        }

        //推而广之, 如果是 单选 , 下拉框 等等. => 作业布置

        //返回接收到的信息, 给浏览器回显
        //本质就是在http响应头,加上 Content-Type: text/html;charset=utf-8
        //说 text/html 表示返回的数据类型,浏览器会根据这个类型来解析数据
        // text/plain 表示返回的数据,请浏览器使用文本方式解析
        // application/x-tar 表示返回的是文件,浏览器就会以下载文件的方式处理
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("

提交的用户名= " + username + "

"
); writer.flush(); writer.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
HttpServletRequestMethods doPost() 被调用..
请求的资源路径URI= /servlet/methods
请求的统一资源定位符(绝对路径)URL= http://localhost:8080/servlet/methods
请求的客户端ip 地址= 127.0.0.1
http请求头HOST= localhost:8080
该请求的发起地址是= http://localhost:8080/servlet/request.html
User-Agent= Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0
浏览器=1.0
取出JSESSIONID= A130727EE668306F7E430FF23ECAF8A1; Idea-8296e770
http请求方式~= POST
username= 见下表
pwd= 456
hobby=hsp

转发请求使用

package com.hspedu.servlet.request;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class CheckServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("CheckServlet 被调用..");

        //根据用户名来确定该用户是什么身份
        String username = request.getParameter("username");
        //注意:如果是同一个request对象(请求转发),那么可以在不同的servlet中,是getParameter
        if ("tom".equals(username)) {
            //分配
            request.setAttribute("role", "管理员");
        } else {
            request.setAttribute("role", "普通用户");
        }

        //获取分发器
        //老韩解读  1. /manageServlet写的是 要转发的servlet的url
        //        2. / 会被解析成 /servlet
        //        3. forward(request, response) 表示把当前servlet的request对象和response对象,传递给下一个servlet使用

        RequestDispatcher requestDispatcher =
                request.getRequestDispatcher("/manage");

        requestDispatcher.forward(request, response);


    }

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

package com.hspedu.servlet.request;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class ManageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ManageServlet 被调用..");

        String username = request.getParameter("username");
        String role = (String) request.getAttribute("role");

        //输出信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("用户名: " + username + "
"
); writer.print("角色 : " + role); writer.flush(); writer.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }

在这里插入图片描述

重定向的使用

package com.hspedu.servlet.response;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class DownServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // System.out.println("DownServlet 被调用");
        // response.setContentType("application/x-tar;charset=utf-8");
        // PrintWriter writer = response.getWriter();
        // writer.print("hi");
        // writer.flush();
        // writer.close();

        //完成了自己业务
        //发出请求重定向-> DownServletNew
        //听老师解读
        //1. sendRedirect 本质就会 返回 302 状态码 Location: /servlet/downServletNew
        //2. 因此 302和 /servlet/downServletNew 是浏览器解析,而不是服务器
        //3. 浏览器在解析 /servlet/downServletNew => http://localhost:8080/servlet/downServletNew
        //4. 动态获取到application context
        String contextPath = getServletContext().getContextPath();
        System.out.println("contextPath= " + contextPath);
        //response.sendRedirect("/servlet/downServletNew");
        response.sendRedirect(contextPath + "/downnew");
        //response.sendRedirect("http://www.baidu.com");

        //第二种重定向的写法
        // System.out.println("第二种方式重定向...");
        // response.setStatus(302); //设置http响应的状态码
        // //设置http响应的 Location: /servlet/downServletNew
        // response.setHeader("Location", "/servlet/downServletNew");


    }

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

package com.hspedu.servlet.response;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class DownServletNew extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("DownServletNew 被调用");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("ok");
        writer.flush();
        writer.close();
    }

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

作业完成

package com.hspedu.servlet.response.homework;

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

/**
 * @author 韩顺平
 * @version 1.0
 */
public class MyPayServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("MyPayServlet 被调用...");
        //得到金额
        String money = request.getParameter("money");
        System.out.println("money= " + money.getClass());
        //转成int
        //处理一下这个异常
        int iMoney = WebUtils.parseString(money);
        ServletContext servletContext = getServletContext();
        if(iMoney > 100) {
            //重定向到payok.html
            //servletContext.getContextPath() 就是 /servlet
            response.sendRedirect(servletContext.getContextPath() + "/payok.html");
        } else {
            response.sendRedirect(servletContext.getContextPath() + "/pay.html");
        }
    }

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

package com.hspedu.servlet.response.homework;

/**
 * @author 韩顺平
 * @version 1.0
 * 编写一个转换string->int的方法,处理异常
 */
public class WebUtils {

    public static int parseString(String str) {
        int num = 0;
        //try-catch : ctrl+alt+t
        //如果不知道,老韩在说什么? 回去看到java基础 - 异常
        try {
            num = Integer.parseInt(str);//
        } catch (NumberFormatException e) {
            //这个异常不会throw 给 tomcat
            System.out.println("输入的str格式不正确...");
        }

        return num;
    }
}

web路径问题


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>b.html</title>
    <!--
        老韩解读
        1. 如果没有<base href="http://localhost:10000/hspedu_servlet/">
        2. 当点击 返回a.html 超链接,将会以当前浏览器的地址为路径来确定 路径
        3. 如果增加了<base href="http://localhost:10000/hspedu_servlet/">
        4. 将以 base 指定的href的地址为路径,来确定 超链接的路径
    -->
    <!--<base href="http://localhost:10000/hspedu_servlet/">-->
    <!--简写形式-->
    <!--使用base 标签搞定
    老韩解读
    1. 下面老师写的 base href="http://localhost:8080/webpath/"
    2. 表示的含义就是当前这个页面的访问所有资源都是以 http://localhost:8080/webpath/ 参照

    -->
    <!--<base href="http://localhost:8080/webpath/">-->
    <!--上面的写法可以简化一把-->
    <!--
        老韩解读
        1. base 标签是哪个在解析? => 浏览器
        2. 浏览器在解析 第一个 /时候,会解析成 http://localhost:8080/
        3. 浏览器 href="/webpath/" =解析=> href="http://localhost:8080/webpath/"
        4. 浏览器 <a href="a.html">返回a.html~</a> , 参考 base => 最后
          href="http://localhost:8080/webpath/a.html"

    -->
    <base href="/webpath/">

</head>
<body>
<h1>这是/d1/d2/b.html</h1>
<!--
    老韩解读
    1. 返回a.html => 使用前面的相对路径http://localhost:8080/webpath/d1/d2/
    2. ../../a.html => http://localhost:8080/webpath/a.html
    3. 相对路径会让这个项目相互调用的关系变得复杂
    4. 使用base 标签搞定

-->
<!--<a href="../../a.html">返回a.html~</a>-->
<a href="a.html">返回a.html~</a>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户页面</title>
    <!--
        1. 使用相对路径: <a href="../../login.html">点击返回登录</a>
        2. 使用相对路径是比较麻烦,即使成功,还需要考虑是直接定位到这个资源还是请求转发到这个资源
        3. 使用base 标签给一个固定的相对路径
        4. <base href="/webpath/"> 该标签是浏览器解析 http://localhost:8080/webpath/
        5. 在 base 得到的url 路径基础上 <a href="login.html">点击返回登录</a> =>
           http://localhost:8080/webpath/login.html
        6. 一定要自己 玩一把,再听评讲,才会有融合贯通.

    -->
    <base href="/webpath/">
</head>
<body>
<h1>用户页面</h1>
<a href="login.html">点击返回登录</a>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>a.html</title>
</head>
<body>
<h1>这是a.html~~~~~</h1>
<!-- 相对路径
    1. href="d1/d2/b.html" 等价于 http://localhost:8080/项目名/d1/d2/b.html
-->
<a href="d1/d2/b.html">跳转到/d1/d2/b.html</a>
<br/><br/>
<!--
老韩解析
1. 在实际开发中,往往不是直接访问一个资源的而是在服务端进行转发或者重定向来访问资源
2. 演示转发定位 b.html
3. href="servlet03" http://localhost:8080/webpath/servlet03
-->
<a href="servlet03">转发到/d1/d2/b.html</a>
</body>
</html>

路径问题代码2


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>base 标签</title>
</head>
<body>
<h1>注册用户~~</h1>
<!--
    老韩解读:
    1. 可以看到,我们原来的访问一个web资源的路径非常的麻烦
    2. 目前我们访问的是 ok的资源
    3. 我们可以使用相对路径来解决
    4. http://localhost:8080/webpath/ok => ok
    5. 如果你action="ok" 等价 http://localhost:8080/webpath/ok
-->
<form action="ok"
      method="post">
    u: <input type="text" name="username"/><br><br>
    <input type="submit" value="注册用户"/>
</form>
<h1>讨论区~</h1>
<form action="ok"
      method="post">
    讨论内容: <textarea cols="50" rows="5"></textarea><br><br>
    <input type="submit" value="发布讨论"/>
</form>
<h1>回复区~</h1>
<form action="ok"
      method="post">
    回复内容: <textarea cols="50" rows="5"></textarea><br><br>
    <input type="submit" value="回复"/>
</form>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h1>用户登录</h1>
<!--
请写出 login.html 在不通过Servlet转发情况下, 如何 通过表单提交, 找到 user.html, 把所有的写法列出来
1. 完整的url  http://localhost:8080/webpath/views/user/user.html
2. 使用相对路径 action="views/user/user.html" => 使用当前浏览器的 地址栏 ip:port/工程路径/ + ...
3. action="/webpath/views/user/user.html"
   浏览器对第一个 / 进行解析 为 http://localhost:8080/ + webpath/views/user/user.html
   同样是一个完整url
4. 这里老师提一句: 我们使用服务器渲染技术,可以动态得到 /工程路径 , 后面再说
-->
<!--<form action="/webpath/hi" method="post">-->
<form action="/webpath/redirect" method="post">
    u: <input type="text" name="username"><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

路径转发以及重定向

package com.jxb.servlet;

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

public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("HelloServlet 被调用...");

        //这个realPath 我们的项目的工作路径
        String realPath = getServletContext().getRealPath("/");
        System.out.println("realPath= " + realPath);

        //contextPath 是配置的 application context
        //这个将来可以在服务器渲染 技术jsp / thymeleaf 动态获取工程路径 application context
        String contextPath = getServletContext().getContextPath();
        System.out.println("contextPath= " + contextPath);
    }

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

package com.jxb.servlet;

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

public class HiServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //这里请求转发到 /views/user/user.html
        //System.out.println("HiServlet 被调用....");

        //使用转发
        //注意 第一个 / 被服务器解析成  /webpath/
        //    因为请求转发是发生服务器端,所以通过 /webpath/views/user/user.html
        //    可以定位该资源
        request.getRequestDispatcher("/views/user/user.html")
                .forward(request,response);
    }

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

代码继续

package com.jxb.servlet;

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

public class RedirectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("RedirectServlet 重定向4 被调用....");
        //这里如何通过重定向来定位 /views/user/user.html
        //1. 分析出 重定向是发生在 浏览器
        //2. 写法1: response.sendRedirect("http://localhost:8080/webpath/views/user/user.html");
        //3. 写法2: response.sendRedirect("/webpath/views/user/user.html");
        //4. 写法3: response.sendRedirect("views/user/user.html");
        //5. 写法4: response.sendRedirect(contextPath + "/views/user/user.html");
        //6. 推荐写法是 第4个写法,比较灵活,而且定位资源是稳定的.
        String contextPath = getServletContext().getContextPath();//contextPath=/webpath
        response.sendRedirect(contextPath + "/views/user/user.html");
    }

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

package com.jxb.servlet;

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

public class Servlet03 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //这里我们希望通过转发来定位b.html
        //老师解读
        //1. 在服务器端 解析第一个 /时,会被解析成 http://ip:port/项目名[application context]
        //   老韩再补充: 项目名=> 说成 application context
        //2. "/d1/d2/b.html" => 被解析 http://ip:port/项目名/d1/d2/b.html
        System.out.println("Servlet03 进行转发~~~ ....");
        request.getRequestDispatcher("/d1/d2/b.html").forward(request,response);
        //3. 在服务器进行转发时, 没有 / 就按照默认的方式参考定位 http://ip:port/项目名/
        //   老师建议,仍然使用上面的
        //request.getRequestDispatcher("d1/d2/b.html").forward(request,response);
    }

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

你可能感兴趣的:(javaweb,前端)