最先的服務器處理程序是CGI,其存在着每次須要對請求進行處理時新建一個CGI對象,因此在速度和內存方面都不是很讓人滿意;隨着JAVA語言的興起,其跨平臺的特性,使得Servlet逐漸流行起來,而且Servlet是可複用的,因此Servlet逐漸取代CGI。html
用戶編寫的Servlet繼承自HttpServlet,繼承圖以下:java
HttpServlet的內部字段以下:瞭解完Web容器對HTTP消息的處理流程後,以前提到Servlet是可複用的,那是否意味着是線程共享的,那是否會產生線程不安全呢?web
@WebServlet("/HelloController")
public class HelloController extends HttpServlet {
private static final long serialVersionUID = 1L;
private HelloModel model = new HelloModel();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(Cookie cookie : cookies) {
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
request.setAttribute("name", cookieName);
request.setAttribute("value", cookieValue);
}
}
else {
Cookie cookie = new Cookie("user", "cjc");
cookie.setMaxAge(7 * 24 * 60 *60);
response.addCookie(cookie);
}
String name = request.getParameter("user");
String message = model.doHello(name);
request.setAttribute("message", message);
request.getRequestDispatcher("HelloServlet").forward(request, response);
}
}
複製代碼
與SpringMVC一致,Controller處理完後須要返回model給View進行渲染,此處使用的是將model數據放入HttpServletRequest對象的屬性中,而後經過RequestDispatcher對象將該請求(forward)轉給HelloServlet進行處理,HelloServlet便是咱們的View; 3. View:一個Servlet,負責完善HttpServletResponse對象並返回給客戶端;安全
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
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");
String cookieName = (String)request.getAttribute("name");
String cookieValue = (String)request.getAttribute("value");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Hello!" + user + "!</h1>");
out.println(message);
out.println("<h1> cookieName" + cookieName + cookieValue + "!</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
複製代碼
至此,咱們經過Servlet實現了一個MVC框架,將處理URL的邏輯,業務邏輯和頁面渲染邏輯分離開來,本來這些是經過一個Servlet完成的,這樣可使系統解耦合,架構更加清晰,更容易維護。bash