附件有源代码:
将前文中的web.xml改写如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <servlet>
- <servlet-name>FirstServlet</servlet-name>
- <servlet-class>cn.nileader.abc.FirstServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>FirstServlet</servlet-name>
- <url-pattern>/FirstServlet</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
和前面的web.xml不同的是,这里多了如下代码:
- <servlet>
- <servlet-name>FirstServlet</servlet-name>
- <servlet-class>cn.nileader.abc.FirstServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>FirstServlet</servlet-name>
- <url-pattern>/FirstServlet</url-pattern>
- </servlet-mapping>
这是配置了一个名为FirstServlet的Servlet, 表明的是这个Servlet对应的是cn.nileader.abc包中的FirstServlet这个类,并且规定了这个Servlet是用来拦截URL以 /FirstServlet的所有请求,交由cn.nileader.abc包中的FirstServlet类来处理.
编写这个Servlet
- package cn.nileader.abc;
- 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 FirstServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- }
- //这个方法是我们这个例子中要用到的
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8" );
- String _username = request.getParameter("username" );
- response.setContentType("text/html;charset=UTF-8");
- //request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.println("<!DOCTYPE HTML PUBLIC \'-//W3C//DTD HTML 4.01 Transitional//EN\'>");
- out.println("<HTML>");
- out.println(" <HEAD><TITLE>这是由Servlet中的doPost方法生成的页面</TITLE></HEAD>");
- out.println(" <BODY>");
- out.print(" This is ");
- out.print(this.getClass());
- out.println(", using the POST method");
- out.println("你的用户名是" + _username);
- out.println(" </BODY>");
- out.println("</HTML>");
- out.flush();
- out.close();
- }
- }
上面这个程序没有什么好说的,困扰新手的主要问题是中文乱码问题。
一般以下可以解决:
- response.setContentType("text/html;charset=UTF-8");
- //request.setCharacterEncoding("UTF-8");
将以上程序编译成.class文件后,连包一起放到这个目录中去即可:
Tomcat 6.0\webapps\DynamicSite\WEB-INF\classes
本文转自 nileader 51CTO博客,原文链接:http://blog.51cto.com/nileader/306305,如需转载请自行联系原作者