Servlet与JSP进阶笔记(二)

解决中文乱码

web应用的中文乱码

  • Tomcat默认使用字符集ISO-8859-1,属于西欧字符集
  • 解决乱码的核心思路是将ISO-8859-1转换为UTF-8
  • Servlet中请求与响应都需要设置UTF-8字符集

解决POST请求中文乱码

POST请求具有请求体,在请求中可以设置:

request.setCharacterEncoding("utf-8");

该方法可以将请求体中的字符集转换为UTF-8

对于响应设置中文的方法:

response.setContentType("text/html;charset=utf-8");

示例程序如下:

charset_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/servlet_advanced/charset" method="post">
        姓名: <input type="text" name="username">
        地址: <input type="text" name="address">
        <input type="submit" value="提交">
    </form>
</body>
</html>

CharsetServlet

@WebServlet("/charset")
public class CharsetServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 将请求体中的字符集转换为UTF-8;POST请求具有请求体,GET方法则没有
        request.setCharacterEncoding("utf-8");

        String username = request.getParameter("username");
        String address = request.getParameter("address");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(username + ":" + address);

    }
}

页面显示结果:



解决GET请求与响应中文乱码

示例程序:

charset_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/servlet_advanced/charset" method="get">
        姓名: <input type="text" name="username">
        地址: <input type="text" name="address">
        <input type="submit" value="提交">
    </form>
</body>
</html>

CharsetServlet

@WebServlet("/charset")
public class CharsetServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 将请求体中的字符集转换为UTF-8;POST请求具有请求体,GET方法则没有
        request.setCharacterEncoding("utf-8");
        doGet(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 对于Tomcat8.x以后版本来说,默认GET请求发送中文就是UTF-8的编码格式,无需转换
        String username = request.getParameter("username");
        String address = request.getParameter("address");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(username + ":" + address);
    }
}

页面显示结果:



Web.xml配置详解

web.xml常用配置

  • 修改web应用默认首页
  • Servlet通配符映射及初始化参数
  • 设置404,500等状态码默认页面

web.xml常用配置

url-pattern模糊匹配

示例,通过URL打印出所有员工的信息:
在地址栏中末尾输入员工的编号id,通过输入的URL不同,页面显示出不同的员工信息

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>pattern</servlet-name>
        <servlet-class>pattern.PatternServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>pattern</servlet-name>
        <url-pattern>/pattern/*</url-pattern>
    </servlet-mapping>
</web-app>

在web.xml配置中,url-pattern映射的地址利用*实现了模糊匹配,只要是URL为:http://localhost:8080/servlet_advanced/pattern/XXX都可以跳转到PatternServlet进行处理

PatternServlet

public class PatternServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 通过url打印出员工的信息
        // 1:张三 2:李四 3:王五
        String url = req.getRequestURL().toString();
        String empId = url.substring(url.lastIndexOf("/") + 1);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("<h1>"+empId+"</h1>");
        if(empId.equals("1")){
            writer.println("<h1>张三</h1>");
        }else if(empId.equals("2")){
            writer.println("<h1>李四</h1>");
        }else if(empId.equals("3")){
            writer.println("<h1>王五</h1>");
        }else{
            writer.println("<h1>查无此人</h1>");
        }
    }
}

页面显示如下:


除了使用web.xml的url-pattern进行模糊的地址匹配,还可以使用更简洁的注解的方式:
在PatternServlet类上添加注解:

@WebServlet("/pattern/*")

即可。

context-param的设置

可以通过web.xml文件来设置ServletContext的初始化参数
示例程序如下:

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">

    <context-param>
        <param-name>title1</param-name>
        <param-value>This is title1</param-value>
    </context-param>
    <context-param>
        <param-name>title2</param-name>
        <param-value>This is title2</param-value>
    </context-param>

</web-app>

通过ServletContext的对象的getInitParameter方法来获取web.xml文件中配置的参数

ServletContextInit

@WebServlet("/servlet_context/init")
public class ServletContextInit extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = request.getServletContext();
        String title1 = context.getInitParameter("title1");
        String title2 = context.getInitParameter("title2");
        context.setAttribute("title1",title1);
        context.setAttribute("title2",title2);
        response.getWriter().println("init success");
    }
}

获取ServletContext设置的属性值

ServletContextDefault

@WebServlet("/servlet_context/default")
public class ServletContextDefault extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = request.getServletContext();
        String title1 = (String) servletContext.getAttribute("title1");
        String title2 = (String)servletContext.getAttribute("title2");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("<h1>" + title1 + "</h1>");
        response.getWriter().println("<h1>" + title2 + "</h1>");
    }
}

页面显示结果如下:



error-page指定错误页面

示例如下:
404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>找不到资源</h1>
</body>
</html>

web.xml

 <error-page>
    <error-code>404</error-code>
    <location>/error/404.html</location>
 </error-page>

当输入非法的URL时,页面会跳转到404.html上
如:


JSP内置对象

JSP九大内置对象

web应用程序打包与发布

  • Java Web应用采用war包进行发布
  • 发布路径为{TOMCAT_HOME}/webapps

IDEA打包普通web项目

全部评论

相关推荐

牛客52811839...:实习要写出来业务和产出,你这写的像流水账没人看。项目经历也没有,换个极简简历试试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 春招至今,你的战绩如何? #
9135次浏览 83人参与
# 你的实习产出是真实的还是包装的? #
1689次浏览 40人参与
# MiniMax求职进展汇总 #
23748次浏览 307人参与
# 军工所铁饭碗 vs 互联网高薪资,你会选谁 #
7398次浏览 42人参与
# 简历第一个项目做什么 #
31507次浏览 327人参与
# 重来一次,我还会选择这个专业吗 #
433312次浏览 3926人参与
# 巨人网络春招 #
11297次浏览 223人参与
# 当下环境,你会继续卷互联网,还是看其他行业机会 #
186904次浏览 1120人参与
# 牛客AI文生图 #
21399次浏览 238人参与
# 不考虑薪资和职业,你最想做什么工作呢? #
152272次浏览 887人参与
# 研究所笔面经互助 #
118859次浏览 577人参与
# 简历中的项目经历要怎么写? #
309957次浏览 4189人参与
# AI时代,哪些岗位最容易被淘汰 #
63328次浏览 799人参与
# 面试紧张时你会有什么表现? #
30479次浏览 188人参与
# 你今年的平均薪资是多少? #
212986次浏览 1039人参与
# 你怎么看待AI面试 #
179809次浏览 1230人参与
# 高学历就一定能找到好工作吗? #
64296次浏览 620人参与
# 你最满意的offer薪资是哪家公司? #
76415次浏览 374人参与
# 我的求职精神状态 #
447963次浏览 3128人参与
# 正在春招的你,也参与了去年秋招吗? #
363202次浏览 2637人参与
# 腾讯音乐求职进展汇总 #
160566次浏览 1110人参与
# 校招笔试 #
470114次浏览 2961人参与
牛客网
牛客网在线编程
牛客网题解
牛客企业服务