//Servlet file name 'RandomGreetings.java'.
//Run on NetBeans IDE 8.2
/*
* A Servlet that returns a randomly chosen greeting from a list of five
* different greetings. The greetings must be stored as constant strings
* in the program.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//
import java.util.Random;
//
@WebServlet(urlPatterns = {"/RandomGreetings"})
//
public class RandomGreetings extends HttpServlet
{
//Five greetings saved as constan strings
public static final String STR1 = "Good morning";
public static final String STR2 = "Good night";
public static final String STR3 = "Good afternoon";
public static final String STR4 = "Good day";
public static final String STR5 = "Welcome";
//
String[] arr = {STR1,STR2,STR3,STR4,STR5};
//
Random ran = new Random();
//
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//
int random = ran.nextInt(5);
//
String g = arr[random];
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Random Greetings</title>");
out.println("</head>");
out.println("<body>");
out.println(g);
out.println("</body>");
out.println("</html>");
}
}
No comments:
Post a Comment