javaEE 進行web編程(二)

來源:互聯網
上載者:User

網站結構      

    接著上一篇,現在開始實際的練習。

          樣本是一個簡單的登入網站,資料庫使用MySQL。使用Servlet+Jsp+javaBean來完成,主要有4個jsp頁面,一個Servlet和一個javabean,網站雖然簡陋,但足以說明這種mvc開發模式。

圖1

      1所示,使用者進入的第一個頁面是login.jsp,在該頁面進行登入,如果沒有該使用者或密碼錯誤則僅進入error.jsp,在該頁面也可以進入註冊頁面reg.jsp進行註冊,不論使用者驗證或使用者註冊的行為都由ValidateServlet轉交給UserBean完成,在ValidateServlet中基本不處理商務邏輯,它僅僅負責頁面的跳轉或將內容轉交給jsp頁面顯示。

     在一些大型項目中,也基本遵循這種設計(暫不考慮直接使用SSH等成熟架構):Model層由各種javabean及其他java類組成,它們完成網站幾乎全部的實際功能的實現,資料的修改等等;View層由大量jsp或其他頁面組成,它們構成了網站全部的外觀,完成資料的不同風格的顯示;Controller層由各種Servlet組成,這些Servlet負責將jsp提出的資料請求轉交給Model層的javabean來完成,然後將Model層處理(擷取)的資料遞交給合適的jsp頁面進行顯示,並且由於Servlet在控制頁面挑戰方面優越的效能,網站大部分的頁面跳轉邏輯也由Servlet去完成,Servlet在整個網站三層模型中起到了至關重要的控製作用。

Step by step

1.首先,我們在mysql中建立一個資料庫test,該資料庫僅包含一張表person,該表包含三個欄位(id ,  name,  password)。

2.然後在eclipse中建立一個Dynamic Web Project,取名MVC,建立後工程結構2。

圖2

              在該工程下,src目錄用於放置java源檔案,而需要注意的目錄是WebContent目錄,該目錄是WebApp的根目錄,WebContent目錄下有兩個字目錄META-INF, WEB-INF,在 WEB-INF下有個web.xml文檔,該文檔是webapp的配置文檔,待會兒我們需要在這裡進行servlet的一些配置。

3.在WebContent目錄下建立上述的四個jsp檔案。

首先是login.jsp頁面,3所示。

圖3

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Login</title></head><body><!-- jump to servlet using action --><form action="validate" method="post"><tr><td align="right" height="32" width="40%">Name:</td>            <td>  <input type="text" name="logname" value="">            </td>          </tr>          <tr>             <td align="right"  height="32">Password:</td>            <td>              <input type="password" name="logpass">            </td>          </tr>          <tr>             <td align="center" colspan="2" height="32"> <br>             <!-- href jump -->  <a href="reg.jsp">Register</a> |              <input type="submit" name="login" value="Login!">            </td>          </tr>  </form></body></html>

         在這裡可以看到jsp頁面的兩種跳轉方式,使用form表單的action,和使用<a href=xxx/>。這裡form表單的action="validate",這個validate是一個servlet,我們後面會對其進行講解配置,而href跳轉到的是註冊的jsp頁面。

然後是註冊頁面reg.jsp,該頁面和登陸頁面十分類似,就不貼出代碼了,4所示。

圖4

     然後是錯誤頁面error.jsp,5。

圖5

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%>    <%    String error=(String)request.getParameter("error");    if(error==null)    error=(String)request.getAttribute("error");    %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><h1>Error</h1><body>Error: <%=error %></body></html>

        錯誤頁面比較簡單,但可以說明參數傳遞的兩種方式。錯誤頁面總是顯示不同的錯誤資訊,所以每個要跳轉到錯誤頁面的請求都要向錯誤頁面傳遞錯誤資訊。如果使用request.getParameter()方法提取的是提交表單傳遞的參數,或者參數形式URL傳遞的參數,5地址欄中的URL就是這種方式。而使用request.getAttribute()方法擷取的參數是之前使用request.setAttribute方式放入的參數。
      當登陸成功後跳轉到的是main.jsp頁面,圖6所示。

圖6

      

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%String usr=(String)session.getAttribute("name");String pwd=(String)session.getAttribute("password");%><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>main</title></head><body>Welcome, <%=usr %>, your password is: <%=pwd %></body></html>

          main.jsp頁面比較簡單,僅僅為了顯示登入成功的使用者。這裡使用了Session來儲存使用者資訊,這也是網站常用的手段,相比於使用Cookie儲存使用者登入資訊,這種方法更加安全一點。在該頁面直接使用了session對象,它其實是jsp內幾個常用的內建對象之一,常用的還用request, response,config, out等等。
4. 接著是建立控制層的Servlet

package demos.mvc.servlets;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import demos.mvc.beans.UserBean;public class ValidateServlet  extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic ServletConfig getServletConfig() {// TODO Auto-generated method stubreturn null;}@Overridepublic String getServletInfo() {// TODO Auto-generated method stubreturn null;}@Overridepublic void init(ServletConfig arg0) throws ServletException {// TODO Auto-generated method stub}@Overridepublic void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString user=request.getParameter("logname");String pwd=request.getParameter("logpass");String sign=request.getParameter("sign");String error="error";String errorContent="";if(user==null||pwd==null||user.isEmpty()||pwd.isEmpty()){errorContent= "user name or password can't be empty!";/*1.how to go another page: redirect * a.Can go to any URL * b.Can't use HttpServletRequest.setAttribute to transfer parameters, *   because this is an new http request from client browser, the attributes you put in *   have been wiped! You have to use URL with parameters to deliver parameters * c.In client browser address bar, there's the new address. *///response.sendRedirect("error.jsp?"+error+"="+errorContent);/*2.how to go another page: forward * a. Can only go to the resources on the server * b. Can use both HttpServletRequest.setAttribute and URL to transfer parameters. * c. In this way, it is the server use the current http request to ask for something, *    so, in client browser address bar, you can't see the redirect address but the previous URL */request.setAttribute(error, errorContent);request.getRequestDispatcher("error.jsp").forward(request, response);}else if(request.getParameter("sign")==null||request.getParameter("sign").isEmpty()){UserBean usr=new UserBean();usr.setName(user);usr.setPassword(pwd);if(usr.isExists()){//store the user information into SessionHttpSession hs=request.getSession();hs.setAttribute("name", user);hs.setAttribute("password", pwd);response.sendRedirect("main.jsp");}else{errorContent="User:"+user+" does not exist! Please sign in first";response.sendRedirect("error.jsp?"+error+"="+errorContent);}}else if(...){//後略}}}

           這是一個非常簡單的Servlet,它充分表現了Servlet的生命週期。

圖7

         Servlet的整個生命週期中僅調用init和destroy方法各一次,但一旦建立Servlet後,每次請求都會調用service方法。這幾個方法都來自Servlet介面,在其後裔中,比如HttpServlet,service方法中調用了doPost和doGet方法,去執行更為精細的服務。

        在該Servlet中展示了Servlet挑戰的兩種方式,使用response.sendRedirect或RequestDispatcher.forward方法,這兩種方法的區別都在注釋中闡明,不在贅述。另外,為了方便說明,這裡的控制邏輯都放到了一個Servlet中,顯得該驗證Servlet擁有較為臃腫的service方法,實際上完全可以分為多個Servlet來完成。

        在該Servlet中調用了Userbean類,該類主要用於串連並查詢資料庫,其代碼不再給出。

       可以看到,用Servlet來控制邏輯走向非常方便,而且比在jsp中直接控制邏輯顯示思路更加清晰。

        

5.配置Servlet
        下面修改web.xml文檔,配置我們的Servlet。

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>MVC</display-name>  <servlet>    <servlet-name>ValidateServlet</servlet-name>    <servlet-class>demos.mvc.servlets.ValidateServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ValidateServlet</servlet-name>    <url-pattern>/validate</url-pattern>  </servlet-mapping>  </web-app>

      這裡就可以看到,之前的jsp頁面跳轉使用的validate資源定位器是從何而來。

      總之,使用jsp+servlet+javabean的三層mvc架構使得構建大型架構的項目成為可能,而且,理解了javaee最基本的這些東西,才能更熟練地掌握javaee上那些成熟的架構,理解其精髓。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.