packagecom.hello.ch02.firstweb;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;public class HelloServlet extendsHttpServlet {/*** Constructor of the object.*/
publicHelloServlet() {super();
}/*** Destruction of the servlet.
*/
public voiddestroy() {super.destroy(); //Just puts "destroy" string in log//Put your code here
}/*** The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
*@paramrequest the request send by the client to the server
*@paramresponse the response send by the server to the client
*@throwsServletException if an error occurred
*@throwsIOException if an error occurred*/
public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
response.setCharacterEncoding("UTF-8"); //设置request,response编码方式
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html"); //设置文档类型
PrintWriter out = response.getWriter(); //获取out对象//输出到客户端浏览器
out.println(""-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("");
out.println("
A Servlet");out.println("
");String requestURI=request.getRequestURI();
out.println("
");out.println("请输入您的名字: ");
out.println("");
out.println("
");out.println("");
String name= request.getParameter("name");//获取浏览器提交的name参数
if(name != null && name.trim().length() > 0){
out.println("您好, " + name + ". 欢迎来到Java Web世界.");
}
out.println(" ");
out.println("");
out.flush();
out.close();//关闭out
}/*** The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
*@paramrequest the request send by the client to the server
*@paramresponse the response send by the server to the client
*@throwsServletException if an error occurred
*@throwsIOException if an error occurred*/
public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {this.doGet(request, response);
}/*** Initialization of the servlet.
*
*@throwsServletException if an error occurs*/
public void init() throwsServletException {//Put your code here
}
}