1. 按上一篇博客建立helloapp 的tomcat项目。
2.创建HTML文件
在helloapp->WebContent下创建login.htm文件,如下
<html>
<head>
<title>helloapp</title>
</head>
<body >
<form name="loginForm" method="POST" action="dispatcher">
<table>
<tr>
<td><div align="right">User Name:</div></td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><div align="right">Password:</div></td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
<td><input type="reset" name="reset" value="reset"></td>
</tr>
</table>
</form>
</body>
</html>
3. 启动tomcat,在浏览器中输入 http://localhost:8080/helloapp/login.htm ,测试是否正确,如下下图显示则说明运行正常。
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);
}
}
5. 创建JSP文件
接下来创建hello.jsp文件,放在WebContent目录下,
<html>
<head>
<title>helloapp</title>
</head>
<body>
<b>Hello: <%= request.getAttribute("USER") %></b>
</body>
</html>
6.修改web.xml文件
将WebContent->WEB-INF 目录下的web.xml文件修改如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>helloapp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/dispatcher</url-pattern>
</servlet-mapping>
</web-app>
7. 运行tomcat,在login页面随意输入用户名密码,显示Hello:ddd 则运行正常。