顺便演示了MVC的作法,以后hello.view可以移交到jsp中处理。
而MODEL和CONTROL,VIEW就实现了分享。
HelloModel.java:
package cc.openhome;import java.util.*;public class HelloModel { private Mapmessages = new HashMap (); public HelloModel() { messages.put("caterpillar", "Hello"); messages.put("Justin", "Welcome"); messages.put("momor", "Hi"); } public String doHello(String user) { String message = messages.get(user); System.out.println(message + "@@@@@@@@@@@@@@@@@"); return message + ", " + user + "!"; }}
HelloController.java:
package cc.openhome;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class HelloController */@WebServlet("/hello.do")public class HelloController extends HttpServlet { private static final long serialVersionUID = 1L; private HelloModel model = new HelloModel(); /** * @see HttpServlet#HttpServlet() */ public HelloController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String name = request.getParameter("user"); String message = model.doHello(name); System.out.println(message + "$$$$$$$$$$"); request.setAttribute("message", message); request.getRequestDispatcher("hello.view").forward(request, response); }}
HelloView.java:
package cc.openhome;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class HelloView */@WebServlet("/hello.view")public class HelloView extends HttpServlet { private static final long serialVersionUID = 1L; private String htmlTemplate = "" + " " + " " + "%s " + " " + " " + "%s
" + " " + ""; /** * @see HttpServlet#HttpServlet() */ public HelloView() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String user = request.getParameter("user"); String message = (String) request.getAttribute("message"); System.out.println(user + message + "##################"); String html = String.format(htmlTemplate, user, message); response.getWriter().print(html); }}