1. 程式人生 > >RequestDispatcher接口示例

RequestDispatcher接口示例

轉發 desc 信息 ava for javaee input extends bmi

在此示例中,我們驗證用戶輸入的密碼。如果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>

RequestDispatcher接口示例