RequestDispatcher接口示例
在此示例中,我们验证用户输入的密码。如果password是servlet,它会将请求转发给WelcomeServlet,否则会显示错误消息:抱歉用户名或密码错误!
在此示例中,我们创建了以下文件:
login.html文件:用于从用户获取输入。
Simple.java文件:用于处理响应的servlet类。如果password是servet,它会将请求转发给welcome servlet。
WelcomeServlet.java文件:用于显示欢迎消息的servlet类。
web.xml文件:包含有关servlet信息的部署描述符文件。
login.html:
<form action="go" method="get">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Simple.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import org.xml.sax.SAXException;
public class Simple extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws SAXException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String p=request.getParameter("userPass");
if(p.equals("servlet")){
RequestDispatcher rd=request.getRequestDispatcher("welcome");
rd.forward(request, response);
}
else{
out.print("Sorry username or password error!");
RequestDispatcher rd=request.getRequestDispatcher("login.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java:
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 WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
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>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Simple</servlet-name>
<servlet-class>Simple</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Simple</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>