Servlet總結


第一章:JavaEE概述
1.什么是javaEE?
    javaEE是一個開發分布式企業級應用的規范和標准

2.javaME:手機開發
   javaSE:標准版(java核心類,集合,jdbc,IO,網絡編程),適用於桌面系統的開發
   javaEE:企業版(javaSE,Servlet,ejb) 開發分布式企業應用標准和規范
  
3.快捷鍵:
    ctrl+1  提示操作
    ctrl+D 刪除當前行
    ctrl+shift+O  組織導包
    ctrl+shift+M  單獨導包    
    ctrl+M 最大化當期窗體
    Alt+Shift+R 重命名    ctrl+shift+F 格式化當前文本
    ctrl+shift+F4 關閉當前打開的所有文件
      
4.獲得站點的根路徑:request.getContextPath(); 在指定圖片的路徑和response.sendRedirect()時經常


5.JavaEE體系結構分為表示層、中間層、數據層
    三層功能:
       表示層:由用戶界面和用於生成界面的代碼組成
       中間層:包含系統的業務和功能代碼
       數據層:負責完成存取數據庫的數據和對數據進行封裝
    三層技術:
       表示層:HTML、JavaScript、Ajax
       中間層:JSP、Servlet、JSTL、JavaBean、框架技術(Struts:Struts主要是擴展了Servlet)
       數據層:JDBC、數據庫框架技術(Hibernate:提供了以對象的形式操作關系型數據庫數據的功能)

6.表單的兩種提交方式區別:
    GET提交數據在地址欄內顯示,不安全;而POST不顯示,相對安全
    GET提交數據量有限制(255個字符);而POST沒有
    GET請求的頁面可以設置為書簽或使用郵件發送;而POST不可以

7.HTTP協議是無狀態協議,當瀏覽器向服務器發送一個請求后,服務器對該請求做出響應,當響應結束后,就斷開連接,彼此並不保持連接信  息。當下次請求時,服務器能夠區分是哪一個用戶是通過存儲在客戶端Cookie中的sessionID

8.三層好處:
    一個組件的更改不會影響其他兩個組件。
    由於表示層和數據層相互獨立,因而可以方便地擴充表示層,是系統具有更好的擴展性。
    代碼重復減少。
    方便分工和協作。不同的小組能夠獨立地開發應用程序的不同部分,並充分發揮各自的長處和優勢
  缺點:效率相對不高


第二章:Servlet基礎
1.什么是Servlet
    Servlet是在服務器端運行以處理客戶端請求並作出響應的程序(頁面和模型層的中介)

2.Servlet中實現向瀏覽器中輸出指定內容
   PrintWriter out=response.getWriter();
   out.println("<html>");

3.為了客戶端無論使用什么方法提交請求程序都能正確地接收到數據,把處理代碼都寫在doGet()方法中,之后在doPost()方法中調用doGet()方法

4.Servlet生命周期
    加載和實例化:當客戶端發送一個請求時,Servlet容器(Tomcat)會查找內存中是否存在Servlet實例,如果不存在,就創建一個Servlet實例。如果存在Servlet實例,就直接從內存中取出該實例來響應請求。
    初始化:初始化Servlet時,可以設置數據庫連接參數,建立JDBC連接,或是建立對其他資源的引用。初始化階段,init()方法被調用。
     服務:Servlet初始化后,就處於響應請求的就緒狀態。
     銷毀:銷毀由容器完成,銷毀調用Servlet的destroy()方法。

5.重定向:response.sendRedirect("/show.jsp"); 在瀏覽器中地址為:http://localhost:8080/show.jsp                   
   請求轉發:request.getRequestDispatcher("/login.jsp").forward(request,response);在瀏覽器中地址為:http://localhost:8080/f0806/login.jsp

6.中文亂碼問題
   get 提交
          String name = request.getParameter("name");
          new String(name.getBytes("ISO-8859-1"),"UTF-8");
   
   post 提交
          request.setCharacterEncoding("UTF-8")

  頁面編碼:
    1.pageEncoding="UTF-8" 源文件編碼
    2.contentType="text/html;charset=utf-8" 響應編碼
        contentType="image/jpeg"
    3.瀏覽器編碼 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      


第三章:基於Servlet的會話跟蹤(一)
1.在Web項目中使用session,是為了跟蹤用戶狀態,並區分不同的用戶

2.會話是Web容器創建的,而不是程序員創建的。當客戶端瀏覽器第一次訪問服務器的時候,服務器為客戶端創建一個session

3.session結束有3種方式
   ●瀏覽器關閉。
   ●兩次訪問的間隔時間大於非活動時間(超時)。
   ●調用HttpSession的invalidate()方法。
  在session結束時,服務器會清空當前瀏覽器相關的數據信息

4.HttpSession用setAttribute()保存數據,用getAttribute()獲取數據

5.設置session超時
    ●代碼中 session.setMaxInactiveInterval(60*60*2)  超時兩小時
    ●web.xml
      <session-config>
 <session-timeout>30分鍾</session-timeout>
      </session-config>
      
6.創建會話(在購物車時經常用到)
   HttpSession session=request.getSession(boolean value);
   HttpSession session=request.getSession();
   第一種方法,布爾值為true時,如果存在與當前會話關聯的會話,就返回該會話,否則創建一個新的會話,並把該會話返回。
                           布爾值為false時,如果存在與當前請求關聯的會話,就返回該會話,否則返回null,不創建新的會話
    第二種方法等同於第一種方法中布爾值為true的情況

7.獲取application對象
    ServletContext application=this.getServletContext();


第四章:基於Servlet的會話跟蹤(二)
1.購物車可以使用(List、Map、Set) ,但最好使用Map,因為查找數據方便
    Map 的方法:put(key,value)、 object get(key)、Collection values()

2.Java中常用的集合接口有List、Set和Map
   ●常用的List接口的實現類有ArrayList類、LinkedList類
   ●常用的Set接口的實現類有HashSet
   ●常用的Map接口的實現類有HashMap類、Properties類

3.設置價格格式
   <%@ page import="java.text.*"%> 
   price=book.getPrice();
   <%=new DecimalFormat("0.00").format(price)%>

4.在Servlet中獲取當前提交頁面的名稱(使用過濾器時用到)
    String path=request.getServletPath();
    if(path.equals("/login.jsp") ){
            chain.doFilter(req,res);
    }
   

第五章:基於Servlet的MVC設計模式
1.什么時設計模式?
    設計模式是一套反復使用、成功的代碼設計經驗的總結。

2.MVC的三個模塊
   模型(Model):對應的組件是JavaBean(Java類)。
   視圖(View):對應的組件是JSP或HTML文件。
   控制器(Controller):對應的組件是Servlet。


第六章:高級JDBC
1.數據庫連接的三種方式:
   ● 編碼方式,把數據庫配置信息直接寫入Java代碼中。
   ● .properties文件,把數據庫配置信息寫在屬性文件中,用程序讀取。
   ● 數據源,使用JNDI來獲取DataSource對象,從而得到Connection對象。

2.為什么要使用數據庫連接池?
    數據庫連接是非常占用系統資源的,為了提高應用程序的性能,優化數據庫的連接,出現了數據庫連接池。

3.什么是JNDI?
    JNDI是將對象和名字綁定的技術,容器生產出對象,這些對象都和唯一的名字綁定。外部程序都可以通過名字來獲得該對象。

4.JNDI配置
   ● 如果想用全局配置,在tomcat的context.xml中配置
   ● 如果只想在某個項目中用,在META-INF下新建一個context.xml

    第一步:在context.xml中
    <Context reloadable="true">
            <WatchedResource>WEB-INF/web.xml</WatchedResource>
            <Resource name="jdbc/books" auth="Container" 
       type="javax.sql.DataSource" maxActive="100" maxIdle="30" 
       maxWait="10000" username="sa" password="123" 
              driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
       url="jdbc:sqlserver://localhost:1433;DataBaseName=books"
              />
    </Context>

    reloadable="true" 表示該xml內容改動后,重新加載該xml
    <WatchedResource>WEB-INF/web.xml</WatchedResource>監聽web.xml是否改動,如果改動,重新加載web.xml

   第二步:在web.xml中
   <web-app>
              <resourc-ref>
         <description>E-Books DataSource</description>
         <res-ref-name>jdbc/books</res-ref-name>
                    <res-type>javax.sql.DataSource</res-type>   --->一定要在<res-auth>之前
         <res-auth>Container</res-auth>
              </resource-ref>
   </web-app>

  第三步:將數據庫驅動拷貝到tomcat的common\lib下面

   第四步:   
   代碼中獲取數據庫連接
    import java.sql.*;
    import java.naming.Context;
    import java.naming.InitialContext;
    import javax.naming.NamingException;
    import java.sql.DataSource;

    public class DBManager{                
                public Connection   getConn(){
             Connection conn=null;
                        try{
            Context ic = InitialContext();
            DataSource source=(DataSource) ic.lookup("java:comp/env/jdbc/books");
            conn=source.getConnection();
             }catch(NamingException e){
            e.printStackTrace();
             }
             return conn;
                }
    }

5.屬性文件的數據庫配置(.properties文件形式只能保存String類型信息)
   第一步:
     在項目默認路徑(src)下創建文件,名稱為db.properties(名稱可自定以,后綴名不行)
     在db.properties中寫入如下內容
     driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
     url=jdbc:sqlserver://localhost:1433;DatabaseName=books
     user=sa
     password=sa 
  
   第二步:
       import java.io.InputStream;
       import java.util.Properties;

       public class Env extends Properties {
     private static Env instance;
     //只創建一個實例
     public static Env getInstance() {
        if (instance != null)
           return instance;
        else {
           makeInstance();
           return instance;
        }
     }
     //同步方法,保證在同一時間,只能被一個人調用
     private static synchronized void makeInstance() {
        if (instance == null) {
           instance = new Env();
        }
     } 

     private Env() {
        InputStream is = getClass().getResourceAsStream("/db.properties");//加載db.properties文件
        try {
           load(is);//取得屬性列表
        } catch (Exception e) {
           System.err.println("錯誤:沒有讀取屬性文件,請確認db.property文件是否存在");
        }
     }
       }

   第三步:
       public static synchronized Connection getConn(){
     String driverClassName = Env.getInstance().getProperty("driver");
     String url = Env.getInstance().getProperty("url");
     String user = Env.getInstance().getProperty("user");
     String password = Env.getInstance().getProperty("password");
     try {
             Class.forName(driverClassName);
             conn = DriverManager.getConnection(url, user, password);
      } catch (Exception ex) {
              ex.printStackTrace();
      }
     return conn;
       }

6.自定義異常:在編寫程序時,由於錯誤信息位置不夠具體和准確,從而不能很快找到錯誤,所以需要自定義異常
    public class MyException extends Exception {
   protected Exception throwable;
 
   public MyException(){
      super();
   }
 
   public MyException(String message){
      super(message);
   }
 
   public MyException(String message,Exception throwable){
      super(message);
      this.throwable=throwable;
   }
 
   public Exception getCause(){
      return throwable;
   }
    }   

   使用自定義異常
    public static synchronized Connection getConn() throws MyException{
     String driverClassName = Env.getInstance().getProperty("driver");
     String url = Env.getInstance().getProperty("url");
     String user = Env.getInstance().getProperty("user");
     String password = Env.getInstance().getProperty("password");
     try {
             Class.forName(driverClassName);
             conn = DriverManager.getConnection(url, user, password);
      } catch (Exception ex) {
             throw new MyException("獲取數據庫連接失敗");
      }
     return conn;
       }


第七章:標准動作
1.JavaBean 要滿足一下要求三個要求
    →是一個公有類,並提供無參的公有的構造方法
    →屬性私有
    →具有公有的訪問屬性的getter和setter方法

2.JSP標准動作
  ●  jsp:useBean 動作用來裝載一個將在jsp頁面上使用的JavaBean,相當於創建了一個對象
      <jsp:useBean id="name" class="package.class" scope="scope">

     scope的值
      page   JavaBean只能在當前頁面中使用。當加載新頁面時就會將其銷毀。
      request JavaBean在用戶對其發出請求時存在。
      session JavaBean一直存在會話中,直至其終止或被刪除為止。
      application JavaBean在整個應用程序中均可使用。

      例:<jsp:useBean id="order" class="y2javaee.sg.ch07.order" scope="request">
    
  ● jsp:setProperty 動作用於設置useBean中指定的JavaBean的屬性值。
     <jsp:setProperty name="BeanName" property="PropertyName" value="Value" param="Parameter">
   
     name 為useBean中使用的JavaBean的id,property 為要設置值的JavaBean的屬性名稱
     如果property和param的名字一樣,則可用<jsp:setProperty name="BeanName" propertyName="*"> 代替 

     例:<jsp:setProperty name="order" property="username" value="accp">   
 
  ● jsp:getProperty 動作獲取JavaBean中指定的屬性值
     <jsp:getProperty name="beanName" property="propertyName">
     name 為useBean中使用的JavaBean的id,property為要獲取值的JavaBean的屬性名稱

    例:<jsp:getProperty name="order" property="username">

  ● <jsp:include page="head.jsp" /> 動態包含 將運行后的結果包含的指定的頁面。
      <%@ include file="head.jsp" %>  靜態包含 將頁面的源代碼包含到指定的頁面。

  ● <jsp:forward page="/url"><jsp:param name="參數名" value="參數值"/></jsp:forward>
     <jsp:forward>實質是使用RequestDispatcher對象的forward方法實現轉發的
      在瀏覽器中地址為:http://localhost:8080/webapps/...


第八章:EL和JSTL
1.EL表達式是為了解決JavaBean中的屬性是對象時的讀取

2.在EL表達式中獲取應用程序的根路徑 ${pageContext.request.contextPath()}
    獲取session的Id ${pageContext.session.id}

3.EL隱式對象
    ${param.name} 相當於request.getParameter("name");
    ${paramValues.name} 相當於request.getParameterValues("name");    
    ${param.name} 如果沒有值,輸出“”,不會是null

    pageContextScope、requestScope、sessionScope、applicationScope
 
4.${empty param.loginName} 判斷表單提交的loginName是否為空或“” 如果為空,則為true
    例:
        <c:if test="${!empty requestScope.detailsInfo}">
        <c:set var="foodDetail" value="${requestScope.detailsInfo}" />
        </c:if> 

 

5.如果在標准動作中定義的變量,可以在EL表達式中可以直接訪問到。
   在小腳本中或者servlet中定義的變量則必須通過域才能訪問${requestScope.num}
   如果${num},則程序從前往后找不同域中是否有num,找到后,則不往下找,一般取數據時要指定域

6.JSTL:解決 java 腳本的邏輯判斷
            通用標簽:set、remove、out
   核心標簽庫: 條件標簽:if
                 迭代標簽:forEach

   SQL標簽庫:update、param、query
 
  使用JSTL標簽
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
   <c:set var="example" value="${100+1}" scope="session">
   <c:out value="${example}">
   <c:remove var="example" scope="session">

   <c:out value="value" default="100"> 當值不存在時,輸出100
   <c:out value="${<a href='ww.baidu.com'>test</a>}" escapeXml="false"> 輸出為一個鏈接

   <c:if test="${!empty requestScope.detailsInfo}"></c:if>
    多分支:
       <c:choose>
          <c:when test="條件運算">
      ....
   </c:when>
    <c:when test="條件運算">
      ....
   </c:when>
   <c:otherwise>
     ....
   </c:otherwise>
       </c:choose>
   <c:forEach item="${sessionScope.bookTitles}" var="currentBook" varStatus="status"></forEach> varStatus="status"相當於for中的i變量
   <c:forEach var="j" begin="1" end="10" step="2"></forEach> 輸出1、3、5、7、9

7.SQL標簽使用
   增、刪、該
   <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
   <sql:setDataSource driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
        url="jdbc:sqlserver://localhost:1433;DatabaseName=restrant" user="sa" 
         password="sa" var="conn"/>
     <sql:update var="order" dataSource="${conn}">
  insert into foodOrderInfo values(?,?,?,?,?,?,?)
  <sql:param value='${param["name"]}'/>
  <sql:param value='${param["addr"]}'/>
  <sql:param value='${param["zip"]}'/>
  <sql:param value='${param["tel"]}'/>
  <sql:param value='${param["mov"]}'/>
  <sql:param value='${param["bz"]}'/>
  <sql:param value='${sessionScope.total}'/>
      </sql:update>
      <c:if test="${order==1}">
  <% session.removeAttribute("food"); %>
  <c:redirect url="/seeYou.jsp"/>
      </c:if>
   
   查
    <sql:setDataSource driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
        url="jdbc:sqlserver://localhost:1433;DatabaseName=restrant" user="sa" 
         password="sa" var="conn"/>

    <sql:query var="rs" dataSource="${conn}">
 select * from foodOrderInfo
    </sql:query>   
    <c:forEach var="row" items="${rs.rows}">     
           <tr>
 <td>${row.customerName }</td>
 <td>${row.address }</td>
 <td>${row.zipCode }</td>
 <td>${row.telephone }</td>
 <td>${row.movePhone }</td>
 <td>${row.notice }</td>    
 <td>${row.totalPrice }</td>
           </tr>   
    </c:forEach>

8.格式化標簽:
  <%@taglib  uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
  格式時間:
      <fmt:formatDate value="${now}" pattern="yyyy-MM-dd hh:mm:ss"/>
  格式數值:
      <fmt:formatNumber value="100000" type="currency" ></fmt:formatNumber>

9. 函數標簽:
   <%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
    ${fn:toUpperCase('abc')}

    
第九章:Web服務
1.使用XFire創建和發布Web服務的步驟如下。
   ● 添加XFire庫
   ● 添加XFire-all-1.2.6.jar包
   ● 創建服務接口和實現類
   ● 配置servies.xml文件
   ● 配置web.xml文件
   ● 添加xalan.jar包,測試web服務是否正常工作
   ● 創建客戶端程序訪問Web服務 

2.web.xml
   <servlet>
    <servlet-name>XFireServlet</servlet-name>
    <servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>XFireServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>

3.在META-INF文件夾下新建services.xml
    <service>
 <name>CreditCard</name>
 <namespace>www.sss.com.cn</namespace>
    <serviceClass>
  y2javaee.sg.ch09.IProcessCredit
 </serviceClass>
 <implementationClass>
  y2javaee.sg.ch09.ProcessCreditCard 
 </implementationClass>
    </service>

4.public int ramGain() {
   Service serviceModel = new ObjectServiceFactory().create(Iweather.class);
   XFire xfire = XFireFactory.newInstance().getXFire();
   XFireProxyFactory factory = new XFireProxyFactory(xfire);
   String url = "http://localhost:8080/restrant/services/weatherService";
   Iweather client = null;
   try {
      client = (Iweather) factory.create(serviceModel, url);   
   } catch (Exception e) {
      System.out.println("客戶端調用異常" + e.toString());
   }
  
   int num = 0;
   try {
      num = client.getRanNum();
   } catch (Exception e) {
      System.out.println("獲取隨機數錯誤" + e.toString());
   }
   return num;
   }

5.單元測試JUnit4 :優點是不再需要將所有的方法命名為 testFoo()、testBar(),等等
   import org.junit.Test;
   import junit.framework.TestCase;
   public class AdditionTest extends TestCase {
      private int x = 1;
      private int y = 1;
  
      @Test  public void testAddition() {
          int z = x + y;
          assertEquals(2, z);
       }
   }

  只要用 @Test 來注釋測試方法,就可以將測試方法放到任何類中。但是您需要導入 junit.Assert 類以訪問各種 assert 方法,如下所示:
   import org.junit.Assert;
   public class AdditionTest {
     private int x = 1;
     private int y = 1;
  
     @Test public void addition() {
          int z = x + y;
          Assert.assertEquals(2, z);
       }
   }

  您也可以使用 JDK 5 中新特性(static import),使得與以前版本一樣簡單:

  import static org.junit.Assert.assertEquals;
  public class AdditionTest {
      private int x = 1;
      private int y = 1;
  
      @Test public void addition() {
          int z = x + y;
          assertEquals(2, z);
       }  
  }

  在 JUnit 4 中,您仍然可以在每個測試方法運行之前初始化字段和配置環境。然而,完成這些操作的方法不再需要叫做 setUp(),只要用     @Before 注釋來指示即可,如下所示:

  @Before protected void initialize() { 
      System.setErr(new PrintStream(new ByteArrayOutputStream()));        
      inputDir = new File("data");
      inputDir = new File(inputDir, "xslt");
      inputDir = new File(inputDir, "input");        
   }

  在 JUnit 4 用 @After 代替 JUnit3 中的tearDown() 
   @After protected void disposeDocument() {
      doc = null;
      System.gc();   
   }

   測試異常

   異常測試是 JUnit 4 中的最大改進。舊式的異常測試是在拋出異常的代碼中放入 try 塊,然后在 try 塊的末尾加入一個 fail() 語句。例如,該方法測試被零除拋出一個 ArithmeticException:

   public void testDivisionByZero() {
        try {
            int n = 2 / 0;
            fail("Divided by zero!");
        }
        catch (ArithmeticException success) {
            assertNotNull(success.getMessage());
        } 
    }


該方法不僅難看,而且試圖挑戰代碼覆蓋工具,因為不管測試是通過還是失敗,總有一些代碼不被執行。在 JUnit 4 中,您現在可以編寫拋出異常的代碼,並使用注釋來聲明該異常是預期的:

   @Test(expected=ArithmeticException.class) 
    public void divideByZero() {
           int n = 2 / 0;
     }


補充:
1.過濾器:設置網頁編碼的過濾器  
  ● Servlet 中
    public class EncodingFilter extends HttpServlet implements Filter {
   private String charset=null;
 
   public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
      req.setCharacterEncoding(charset);  
      res.setCharacterEncoding("GBK");
      chain.doFilter(req, res);
   }

   public void init(FilterConfig config) throws ServletException {
      charset=config.getInitParameter("charset");
      if(charset==null)
        charset="GBK";
   }
     }

   ● web.xml文件中
   <filter>
    <filter-name>Encoding</filter-name>
    <filter-class>web.EncodingFilter</filter-class>
    <init-param>
      <param-name>charact</param-name>
      <param-value>GBK</param-value>
    </init-param>
   </filter>
   <filter-mapping>
    <filter-name>Encoding</filter-name>
    <url-pattern>/*</url-pattern>
   </filter-mapping>

2.監聽器:獲取數據庫連接和關閉數據庫連接
   ●Servlet 中
   public class ContextListener extends HttpServlet implements ServletContextListener {
   public void contextDestroyed(ServletContextEvent sce) {
      DBManager.closeConnection();
   }

   public void contextInitialized(ServletContextEvent sce) {
      ServletContext context = sce.getServletContext();
      String driver = context.getInitParameter("driver");
      String url = context.getInitParameter("url");
      String user = context.getInitParameter("user");
      String password = context.getInitParameter("password");
      DBManager.getConn(driver, url, user, password);
   }
   }

   ●web.xml中
   <context-param>
    <param-name>driver</param-name>
    <param-value>com.microsoft.sqlserver.jdbc.SQLServerDriver</param-value>
  </context-param>
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:sqlserver://localhost:1433;DatabaseName=restrant</param-value>
  </context-param>
  <context-param>
    <param-name>user</param-name>
    <param-value>sa</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>sa</param-value>
  </context-param>
  <listener>
    <listener-class>web.ContextListener</listener-class>
  </listener>

3. 判斷用戶是否登錄的Servlet
    public class IsLogin extends HttpServlet implements Filter {
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
      String path = request.getServletPath();
      String pathFormate = path.substring(path.lastIndexOf(".") + 1,path.length()).toLowerCase();
       //如果是以下條件,不需要判斷是否已經登錄
      if (path.equals("/ch07/checkLogin.jsp") || path.equals("/ch07/checkOut.jsp") || path.equals("/ch07/login.jsp")
        || path.equals("/ch07/middle.jsp") || path.equals("/ch07/show.jsp")  || pathFormate.equals("css")
        || path.equals("/login.jsp") || path.equals("/LoginServlet") || pathFormate.equals("gif")
        || pathFormate.equals("jpg") || pathFormate.equals("js")) {
         chain.doFilter(req, res);
      } else {
         HttpSession session = request.getSession(false);
       if (session != null) {
          if (session.getAttribute("login") == null) {
             response.sendRedirect(request.getContextPath()+ ("/login.jsp"));
             return;
          } else {
             chain.doFilter(req, res);
          }
       } else {
          response.sendRedirect(request.getContextPath() + ("/login.jsp"));
          return;
       }
    }
  }
  web.xml中
    <filter>
       <filter-name>IsLogin</filter-name>
       <filter-class>web.IsLogin</filter-class>
    </filter>
     <filter-mapping>
         <filter-name>IsLogin</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>

4.Servlet 中下載
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.setContentType("text/html");
     HttpSession session = request.getSession();
     Cart cart = null;
     if (session.getAttribute("food") != null) {
        cart = (Cart) session.getAttribute("food");
        CreateExcel.createXls(cart.getAllCart());
        // 新建一個SmartUpload對象
        SmartUpload su = new SmartUpload();
        // 初始化
        su.initialize(null);
        // 設定contentDisposition為null以禁止瀏覽器自動打開文件
        su.setContentDisposition(null);
        try {
           su.downloadFile("c:\\1.xls");
        } catch (SmartUploadException e) {
           e.printStackTrace();
        }
      }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM