在helloapp目录下加入index.htm文件,这个文件仅仅用来显示一串带链接的字符”Welcome to HelloApp”, 它链接到login.jsp文件。以下是index.htm文件的代码:
<html><head><title>helloapp</title></head><body ><p><font size="7">Welcome to HelloApp</font></p><p><a href="login.jsp language=English">English version </a></body></html>
package mypack;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;public class DispatcherServlet extends HttpServlet{ private String target = "/hello.jsp"; public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // If it is a get request forward to doPost() doPost(request, response); } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the username from the request String username = request.getParameter("username"); // Get the password from the request String password = request.getParameter("password"); // Add the user to the request request.setAttribute ("USER", username); request.setAttribute ("PASSWORD", password); // Forward the request to the target named ServletContext context = getServletContext(); System.out.println ("Redirecting to " + target); RequestDispatcher dispatcher = context.getRequestDispatcher(target); dispatcher.forward(request, response); } public void destroy() { }}
package mypack;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.TagSupport;public class HelloTag extends TagSupport{ public void HelloTag() { } // Method called when the closing hello tag is encountered public int doEndTag() throws JspException { try { // We use the pageContext to get a Writer // We then print the text string Hello pageContext.getOut().print("Hello"); } catch (Exception e) { throw new JspTagException(e.getMessage()); } // We want to return SKIP_BODY because this Tag does not support // a Tag Body return SKIP_BODY; } public void release() { // Call the parent's release to release any resources // used by the parent tag. // This is just good practice for when you start creating // hierarchies of tags. super.release(); }}