用eclipse创建的第一个tomcat项目

1. 按上一篇博客建立helloapp 的tomcat项目。

2.创建HTML文件

在helloapp->WebContent下创建login.htm文件,如下



helloapp


  
User Name:
Password:
3. 启动tomcat,在浏览器中输入 http://localhost:8080/helloapp/login.htm ,测试是否正确,如下下图显示则说明运行正常。

用eclipse创建的第一个tomcat项目_第1张图片

4. 创建servlet类。

创建名为DispatcherServler.java 的java文件,放在src 目录下,程序如下

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class DispatcherServlet extends GenericServlet {

  private String target = "/hello.jsp";

  /** 响应客户请求*/
  public void service(ServletRequest request,ServletResponse response)
    throws ServletException, IOException {

    //读取表单中的用户名
    String username = request.getParameter("username");
    //读取表单中的口令
    String password = request.getParameter("password");

    //在request对象中添加USER属性
    request.setAttribute("USER", username);
    //在request对象中添加PASSWORD属性
    request.setAttribute("PASSWORD", password);

    /*把请求转发给hello.jsp */
    ServletContext context = getServletContext();
    RequestDispatcher dispatcher =context.getRequestDispatcher(target);
    dispatcher.forward(request, response);
  }
}
用eclipse创建的第一个tomcat项目_第2张图片

5. 创建JSP文件

接下来创建hello.jsp文件,放在WebContent目录下,



  helloapp


  Hello: <%= request.getAttribute("USER") %>



用eclipse创建的第一个tomcat项目_第3张图片

6.修改web.xml文件

将WebContent->WEB-INF 目录下的web.xml文件修改如下



  helloapp
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  	dispatcher
  	DispatcherServlet
  
  
  	dispatcher
  	/dispatcher
  
7. 运行tomcat,在login页面随意输入用户名密码,显示Hello:ddd 则运行正常。





你可能感兴趣的:(用eclipse创建的第一个tomcat项目)