2.第二次修改项目

2.1新建DispatcherServlet

package com.hy.servlet;

import java.io.IOException;

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

@WebServlet("*.do")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //假设url是:  http://localhost:8080/mymvc2/hello.do
        //ServletPath是Servlet的访问路径:    /hello.do
        // 思路是:
        // 第1步: /hello.do ->   hello     或者  /book.do -> book
        // 第2步: hello -> HelloController 或者  book     -> BookController
        String servletPath = request.getServletPath();     // /hello.do
        int lastDotIndex = servletPath.lastIndexOf(".do");
        servletPath = servletPath.substring(1, lastDotIndex); // hello
    }

}

 

posted @ 2022-04-12 12:45  费凡  阅读(31)  评论(0)    收藏  举报