隨筆-159  評論-114  文章-7  trackbacks-0

          在繼承于HttpServlet,進行實際的HTTP開發(fā)中,可以獲得很多來自父類功能的封裝。

          來自于GenericServlet的部分函數(shù)

          getInitParameter(java.lang.String name)

          相當(dāng)于ServletConfig.getInitParameter(String name)。

          public ServletConfig getServletConfig()

          拿到ServletConfig對象(原始init系統(tǒng)傳入的)



          public ServletContext getServletContext()

          拿到整個應(yīng)用的上下文對象。

           

          ======================================

          系統(tǒng)傳入Service方法中的ServletRequest和ServletResponse對象要研究一下。

          getInputStream/getReader,允許自己對頭部信息進行解析,不過這和getParameter/getRemoteAddr/getRemoteHost/getScheme相關(guān)分別確定信息的方法,只能調(diào)用一個,掉用過后,就會清空。

          傳遞數(shù)據(jù),setAttribute/getAttribute。

          設(shè)置字符集,setCharacterEncoding,可以在過濾器中使用。

          ------------

          HttpServletRequest    擴展功能

          getServletPath              地址欄:http://localhost:8080/myjsp/findall.do               返回/findall.do

          這web.xml中配置的url-pattern有關(guān)系

          絕對匹配和擴展名匹配,都能完全取道完整的用戶輸入地址.

          對于/view/*

          *的部分必須通過下面的方法:
          getPathInfo()     


          public java.lang.String getContextPath(),用于得到應(yīng)用的名稱。很容易用于JSP的可移植上,比如JSP中的鏈接,不應(yīng)該硬編碼到頁面里,而是應(yīng)該<%=request.getContextPath()%>/servlet/index.do


          public Cookie[] getCookies()

          返回所有的Cookie對象。

          自己寫方法,可以方便取得自己要的Cookie

              private String getCookie(HttpServletRequest request, String name)
              
          {
                  Cookie[] cookies 
          = request.getCookies();
                  
          if (cookies == null)
                  
          {
                      
          return "";
                  }


                  
          for (int i = 0; i < cookies.length; i++)
                  
          {
                      
          if (cookies[i].getName().equals(name))
                      
          {
                          
          return cookies[i].getValue();
                      }

                  }

                  
          return "";
              }


          public HttpSession getSession(boolean create)

          有一個布爾參數(shù),主要判斷是否創(chuàng)建新的Session.

          getSession()   等同于    getSession(true)



          public boolean isRequestedSessionIdValid()

          public boolean isRequestedSessionIdFromCookie()

          public boolean isRequestedSessionIdFromURL()

          public java.lang.String getRequestedSessionId()

          輔助方法。

          -----------------------------------------

          ServletResponse

          getWriter()

          獲得輸出,但要注意,必須先指定頭部信息,再獲得輸出,否則無效。

          例如應(yīng)該有個順序:

          response.setCharacterEncoding("gb2312");

          PrintWriter out = response.getWriter();

          out.println("<html..");


          public void setCharacterEncoding(java.lang.String charset)

          public void setContentLength(int len)

          public void setContentType(java.lang.String type)

          response.setContentType("text/html");


          ====================

          Session,是基于Cookie的,必須客戶端支持Cookie,才能保存SessionID,以便以后的通訊可以確定服務(wù)器為該用戶開辟的Session空間,如果客戶端關(guān)閉瀏覽器,就不能在使用該空間,因為SessionId丟失,因為那個保存SessionId的Cookie,的MaxAge為-1,表示只限當(dāng)前窗口有效(IE,Linux上的Mazilia瀏覽器對于Cookie的理解略有不同)。

          下邊為一個登陸的控制Servlet,它就是先創(chuàng)建新的Session。

          /*
           * Created on 2004-11-28
           * 
           * By Alan,All Rights Reserved.
           
          */

          package alan.servlet;

          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;

          public class LoginCtrlServlet extends HttpServlet
          {
              
          public static final String    SESSION_KEY_USER    = "LOGIN_PROJECT_USER";

              
          public static final String    SESSION_KEY_PASS    = "PASSWORD";

              
          public void service(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, IOException
              
          {
                  String servletPath 
          = request.getServletPath();

                  String actionName 
          = servletPath.substring(servletPath.indexOf("/"+ 1, servletPath.length());
                  actionName 
          = actionName.substring(0, actionName.indexOf(".do"));

                  String nextPage 
          = "";

                  
          if (actionName.equalsIgnoreCase("tologin"))
                  
          {
                      nextPage 
          = "/view/loginview";
                  }
           else if (actionName.equalsIgnoreCase("login"))
                  
          {
                      String user 
          = request.getParameter("user");
                      String pass 
          = request.getParameter("pass");

                      
          if (!user.equals(getInitParameter("user")) || !pass.equals(getInitParameter("pass")))
                      
          {
                          nextPage 
          = "/view/error";
                          request.setAttribute(
          "message""no such user");
                      }
           else
                      
          {
                          
          if (request.getParameter("rem"!= null)
                          
          {
                              Cookie userCookie 
          = new Cookie("user", user);
                              userCookie.setMaxAge(
          60 * 60 * 24 * 365);
                              Cookie passCookie 
          = new Cookie("pass", pass);
                              passCookie.setMaxAge(
          60 * 60 * 24 * 365);
                              response.addCookie(userCookie);
                              response.addCookie(passCookie);
                          }


                          HttpSession session 
          = request.getSession(true);
                          session.setAttribute(LoginCtrlServlet.SESSION_KEY_USER, user);
                          session.setAttribute(LoginCtrlServlet.SESSION_KEY_PASS, pass);

                          
          //response.sendRedirect(request.getContextPath() + "/post.do");
                          response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/post.do"));
                          
          return;
                      }

                  }
           else if (actionName.equalsIgnoreCase("post"))
                  
          {
                      nextPage 
          = "/view/postlogin";
                  }
           else if (actionName.equalsIgnoreCase("info"))
                  
          {
                      nextPage 
          = "/view/logininfoview";
                  }


                  RequestDispatcher dispatcher 
          = getServletContext().getRequestDispatcher(nextPage);
                  dispatcher.forward(request, response);

              }

          }

          受保護頁面判斷Session是否存在,保護資源安全。

          /*
           * Created on 2004-11-28
           * 
           * By Alan,All Rights Reserved.
           
          */

          package alan.servlet;

          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;

          public class LoginInfoViewServlet extends HttpServlet
          {
              
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              
          {
                  HttpSession session 
          = request.getSession(false);
                  
          if (session == null)
                  
          {
                      response.sendRedirect(request.getContextPath() 
          + "/tologin.do");
                      
          return;
                  }


                  response.setContentType(
          "text/html");
                  PrintWriter out 
          = response.getWriter();

                  out.println(
          "<html>");
                  out.println(
          "<head><title>postlogin</title></head>");
                  out.println(
          "<body>");
                  out.println(
          "   <h3 align=\"center\">User Infomation View From Session</h1>");
                  out.println(
          "   <hr/>");
                  out.println(
          "    Your user name is : " + session.getAttribute(LoginCtrlServlet.SESSION_KEY_USER));
                  out.println(
          "    and password is : " + session.getAttribute(LoginCtrlServlet.SESSION_KEY_PASS));
                  out.println(
          "    <a href=\"" + request.getContextPath() + "/tologin.do\"><br>Click Here</a> to login again!");
                  out.println(
          "</body>");
                  out.println(
          "</html>");
              }


              
          public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              
          {
                  doGet(request, response);
              }

          }

          這種方式,是不太實際的,應(yīng)該利用Session的Attribute來判斷是否合法,這樣更靈活。




           



          posted on 2006-02-25 22:11 北國狼人的BloG 閱讀(252) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 东明县| 西和县| 邵武市| 兴和县| 永靖县| 祁连县| 包头市| 泰宁县| 句容市| 余姚市| 平陆县| 简阳市| 婺源县| 奉贤区| 新和县| 喜德县| 峨眉山市| 昔阳县| 眉山市| 乡宁县| 子洲县| 云霄县| 龙山县| 凯里市| 台安县| 新余市| 上思县| 疏附县| 布尔津县| 金湖县| 瑞昌市| 铁岭市| 凌海市| 阿勒泰市| 车致| 北川| 鸡泽县| 庆城县| 灌阳县| 古田县| 承德市|