随笔-159  评论-114  文章-7  trackbacks-0

在继承于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 阅读(242) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: