Java 怎么实现HelloWorld servlet,随机显示六种不同问候语之一

2019年8月17日22:07:10 评论 24

1.简介

Java 怎么实现HelloWorld servlet,随机显示六种不同问候语之一?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class HelloServlet extends HttpServlet
{
    public void doGet(HttpServletRequest request,
      HttpServletResponse response) throws IOException, ServletException{
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String msg = getGreeting();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>HelloWorld Servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>");
        out.println(msg);
        out.println("</h1>");
        out.println("</body>");
        out.println("</html>");
    }

    public void doPost(HttpServletRequest request,
      HttpServletResponse response)
        throws IOException, ServletException
    {
    doGet(request, response);
  }

    private String getGreeting()
    {
        String msg = "";
        int rand = (int)(Math.random() * (6)) + 1;
        switch (rand)
        {
      case 1:
        return "Hello, World!";
      case 2:
        return "Greetings!";
      case 3:
        return "Felicitations!";
      case 4:
        return "Yo, Dude!";
      case 5:
        return "Whasssuuuup?";
      case 6:
        return "Hark!";
    }
    return null;
  }
}

 

3.总结

示例代码演示了 Java 怎么实现HelloWorld servlet,随机显示六种不同问候语之一,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: