在繼承于HttpServlet,進行實際的HTTP開發中,可以獲得很多來自父類功能的封裝。
來自于GenericServlet的部分函數
getInitParameter(java.lang.String name)
相當于ServletConfig.getInitParameter(String name)。
public ServletConfig getServletConfig()
拿到ServletConfig對象(原始init系統傳入的)
public ServletContext getServletContext()
拿到整個應用的上下文對象。
======================================
系統傳入Service方法中的ServletRequest和ServletResponse對象要研究一下。
getInputStream/getReader,允許自己對頭部信息進行解析,不過這和getParameter/getRemoteAddr/getRemoteHost/getScheme相關分別確定信息的方法,只能調用一個,掉用過后,就會清空。
傳遞數據,setAttribute/getAttribute。
設置字符集,setCharacterEncoding,可以在過濾器中使用。
------------
HttpServletRequest 擴展功能
getServletPath 地址欄:http://localhost:8080/myjsp/findall.do 返回/findall.do
這web.xml中配置的url-pattern有關系
絕對匹配和擴展名匹配,都能完全取道完整的用戶輸入地址.
對于/view/*
*的部分必須通過下面的方法:
getPathInfo()
public java.lang.String getContextPath(),用于得到應用的名稱。很容易用于JSP的可移植上,比如JSP中的鏈接,不應該硬編碼到頁面里,而是應該<%=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)
有一個布爾參數,主要判斷是否創建新的Session.
getSession() 等同于 getSession(true)
public boolean isRequestedSessionIdValid()
public boolean isRequestedSessionIdFromCookie()
public boolean isRequestedSessionIdFromURL()
public java.lang.String getRequestedSessionId()
輔助方法。
-----------------------------------------
ServletResponse
getWriter()
獲得輸出,但要注意,必須先指定頭部信息,再獲得輸出,否則無效。
例如應該有個順序:
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,以便以后的通訊可以確定服務器為該用戶開辟的Session空間,如果客戶端關閉瀏覽器,就不能在使用該空間,因為SessionId丟失,因為那個保存SessionId的Cookie,的MaxAge為-1,表示只限當前窗口有效(IE,Linux上的Mazilia瀏覽器對于Cookie的理解略有不同)。
下邊為一個登陸的控制Servlet,它就是先創建新的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);
}
}
這種方式,是不太實際的,應該利用Session的Attribute來判斷是否合法,這樣更靈活。
posted on 2006-02-25 22:11
北國狼人的BloG 閱讀(250)
評論(0) 編輯 收藏