HelloServlet.java
package im.weitang;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 注意要添加下面两行代码,否则可能会出现中文乱码问题
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title></title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>这是我第一个Servlet程序</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
修改web.xml,在最后添加下面这段代码
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>im.weitang.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>
打开浏览器,在地址栏中输入http://127.0.0.1/helloServlet, 即可查看到结果。