第一個Servlet應用

web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  Copyright 2004 The Apache Software Foundation

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>GreetingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GreetingServlet</servlet-name>
<url-pattern>/servlet/GreetingServlet</url-pattern>
</servlet-mapping>
</web-app>

index.html:
<html>
<head>
<title>Projava Registration</title>
</head>
<body>
<H1>Welcome</H1>
<form action="/greeting/servlet/GreetingServlet" METHOD="POST">
<p>Your Name <input type="text" size="40" name="name"></p>
<p>Your Email <input type="text" size="40" name="email">
<input type="submit" value="Submit"></p>
</form>
</body>
</html>

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

public class GreetingServlet extends HttpServlet{
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        String name=request.getParameter("name");
        String email=request.getParameter("email");

        String message=null;
        GregorianCalendar calendar=new GregorianCalendar();
        if(calendar.get(Calendar.AM_PM)==Calendar.AM){
            message="Good Morning";        
        }else{
            message="Good Afternoon";
        }

        response.setContentType("text/html");
        PrintWriter out=response.getWriter();

        out.println("<html>");
        out.println("<body>");
        out.println("<p>"+message+", "+name+"</p>");
        out.println("<p> Thanks for registering your email ("+email+") with us.</p>");
        out.println("<p> - The Pro java Team.</p>");
        out.println("</body>");
        out.println("</html>");
        out.close();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章