§ ITPOW >> 文档 >> Java

创建第一个 Servlet,以及乱码解决

作者:vkvi 来源:ITPOW(原创) 日期:2022-10-11

src 目录下,建一个 com.example 包,建一个 Servlet 文件

package com.example;

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

import java.io.IOException;


@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("line");
        resp.getWriter().print("a");
        resp.getWriter().print("b");
    }
}

其中 @WebServlet(urlPatterns = "/hello") 这个注释很重要,不然外部访问不到它,有了上述配置,我们就可以使用形如:localhost:8082/demo/hello 这样的路径来访问它了。

注意,由于我们的配置中,hello 后面没有 /,所以访问时,后面也不能有 /,否则 404。

这是简单的写法,以前还有个麻烦的写法,是在 web/WEB-INF/web.xml 中配置:

<?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>hello</servlet-name>
        <servlet-class>com.example.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

注意:两种写法,不要共存。

在实际中,我们可能要考虑输出的编码啊、类型啊,需要额外添加一些东西,比如:

resp.setHeader("Cache-Control", "no-cache");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/plain");
resp.getWriter().write("中文abc");

如上,我们添加了 UTF-8,但是还不够,还有乱码

在菜单:File -> Settings 中,Editor -> File Encodings,全部改为 UTF-8。

要用其他编码也可以,但是 UTF-8 是最省心的,这年头,不要担心什么 UTF-8 比 XX 编码多占那么一点空间。

File Encodings

相关阅读


相关文章