初识Servlet

初识Servlet_第1张图片
图片来源网络, 侵删

初识Servlet

初学Servlet,超简单的Demo

0.前期准备

IDE: eclipse
LIB: tomcat9.0
新建一个java web项目

1.三步开始Servlet

1.1.继承HttpServlet

package servlet;

import javax.servlet.http.HttpServlet;
public class ServletHello extends HttpServlet { 

}

1.2.重写Get(),Post()方法

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("dealing with Get() method...");
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();
    out.println("Hey, boy,干得好
"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("dealing with Post() method..."); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("Hey, boy, you done the post.漂亮
"); }

1.3.注册xml


    ServletHello
    servlet.ServletHello


    ServletHello
    /servlet/ServletHello

2.简单index.jsp

点我

3.问题及Solution

之前描述的都是 shit! 记录本文的目的是这里:
1.tomcat不能显示中文问题
报错大致是:Unsupported encoding: [text/html; charset=utf-8]
解决办法: 配置tomcat的utf-8编码
打开tomcat的安装目录配置文件: %安装目录%/conf/server.xml
在其中找到


修改为


2.Servlet显示页面出现问题:
错误显示

Hey, boy,???

正确显示应该是这样

Hey, boy,干得好

解决办法: 由于网上的关于 乱码 部分看得头晕,因而采取了粗暴方案,在Get()和Post()方法中,均加入:

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

4.小Conclusion

偶尔掉个小坑,感觉挺开心的
小伙伴们,是不是很简单呢?

引用

1.Tomcat7.0/8.0 详细安装配置图解,以及UTF-8编码配置

你可能感兴趣的:(初识Servlet)