zoukankan      html  css  js  c++  java
  • Head First Servlet and JSP 笔记 Servlet 部分

    第四章

    1、Servlet继承树

    2、LifeCycle

       1 init()  2 service() 3 doGet() or doPost()

    3、request

    You can have multiple values for a single parameter! That means you’ll need getParameterValues() that returns an array, instead of getParameter() that returns a String. 

    4、getServerPort(), getLocalPort(), and getRemotePort() 

    getServerPort() says, “to which port was the request originally SENT?” while getLocalPort() says, “on which port did the request END UP?” Yes, there’s a difference, because although the requests are sent to a single port (where the server is listening), the server turns around and finds a different local port for each thread so that the app can handle multiple clients at the same time. 

    5、ServletRequest interface
     
    6、Servlet Response Interface
    7、download a JAR file by servlet
    public class CodeReturn extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
     {
    response.setContentType(“application/jar”);
    ServletContext ctx = getServletContext();;
    InputStream is = ctx.getResourceAsStream(“/bookCode.jar”);int read = 0;;
    byte[] bytes = new byte[1024];;
    OutputStream os = response.getOutputStream();
     while ((read = is.read(bytes)) != -1) 
    {
    os.write(bytes, 0, read); 
    }
    os.flush();
    os.close();
    }
    }

    8、

    Common MIME types:

    text/html
    application/pdf

    video/quicktime

    application/java

    image/jpeg

    application/jar

    application/octet-stream

    application/x-zip 

    9、

    To make sure everything works correctly, your best practice (and in some cases a

    requirement) is to always call setContentType() first, BEFORE you call the method that gives you your output stream (getWriter() or getOutputStream()). That’ll guarantee you won’t run into conflicts between the content type and the output stream. 

    10、

    You’ve got two choices for output:

    characters or bytes 

    ServletOutputStream for bytes, or a PrintWriter for character data. 

    PrintWriter writer = response.getWriter();;
    writer.println(“some text and HTML”);;
    ServletOutputStream out = response.getOutputStream();;;;
    out.write(aByteArray);;

    11、redirect

    if (worksForMe) {
    // handle the request
    } else { response.sendRedirect(“http://www.oreilly.com”);;
    }

    相对寻址

    sendRedirect(“foo/stuff.html”);

    绝对寻址(webroot)

    sendRedirect(“/foo/stuff.html”);

    第五章 attributes and listeners

    1、servlet param

    <servlet>
      <servlet-name>BeerParamTests</servlet-name> 
      <servlet-class>TestInitParams</servlet-class>
    
      <init-param>
        <param-name>adminEmail</param-name> 
        <param-value>likewecare@wickedlysmart.com</param-value>
      </init-param>
    </servlet>
    out.println(getServletConfig().getInitParameter(“adminEmail”));;

    You can’t use servlet init parameters until the servlet is initialized 

    e.g.

    <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app xmlns=”http://java.sun.com/xml/ns/j2ee”
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd” version=”2.4”>
    
    <servlet>
      <servlet-name>BeerParamTests</servlet-name> 
      <servlet-class>com.example.TestInitParams</servlet-class>
      <init-param>
        <param-name>adminEmail</param-name>
        <param-value>likewecare@wickedlysmart.com</param-value>
      </init-param> 
      <init-param>
        <param-name>mainEmail</param-name>
        <param-value>blooper@wickedlysmart.com</param-value>
       </init-param>
    </servlet>
    
    <servlet-mapping>
      <servlet-name>BeerParamTests</servlet-name>
      <url-pattern>/Tester.do</url-pattern>
    </servlet-mapping>
    
    
    </web-app>

    2、Context init parameter

    <servlet> 
        <servlet-name>BeerParamTests</servlet-name> 
        <servlet-class>TestInitParams</servlet-class>
    </servlet>
    
    <context-param>
        <param-name>adminEmail</param-name>
        <param-value>clientheaderror@wickedlysmart.com</param-value>
    </context-param>
    out.println(getServletContext().getInitParameter(“adminEmail”));;
    
    
    
    ServletContext context = getServletContext();
    out.println(context.getInitParameter(“adminEmail”));

    diff:

    ServletConfig is one per servlet ServletContext is one per web app 

    If the app is distributed, there’s one ServletContext per JVM! 

    getServletConfig().getServletContext().getInitParameter()
    
    this.getServletContext().getInitParameter()

    3、listener

    package com.example;
     import javax.servlet.*;
    public class MyServletContextListener implements ServletContextListener 
    {
      public void contextInitialized(ServletContextEvent event) 
      {
        ServletContext sc = event.getServletContext();
        String dogBreed = sc.getInitParameter(“breed”);
        Dog d = new Dog(dogBreed);;
        sc.setAttribute(“dog”, d);
      }
    
        public void contextDestroyed(ServletContextEvent event)
        { // nothing to do here
        }
     }
    <web-app xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd” version=”2.4”>
    
    <servlet>
      <servlet-name>ListenerTester</servlet-name> 
      <servlet-class>com.example.ListenerTester</servlet-class>
    </servlet>
    
    <servlet-mapping> 
      <servlet-name>ListenerTester</servlet-name>
      <url-pattern>/ListenTest.do</url-pattern>
    </servlet-mapping>
    
    <context-param> 
      <param-name>breed</param-name> 
      <param-value>Great Dane</param-value>
    </context-param>
    
    <listener>
      <listener-class>com.example.MyServletContextListener </listener-class>
    </listener>
    
    </web-app>

    8种listener

    4、

    Context scope isn’t thread-safe! 

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException 
    {
    response.setContentType(“text/html”);
    PrintWriter out = response.getWriter();
    out.println(“test context attributes<br>”);
    synchronized(getServletContext()) 
    {
      getServletContext().setAttribute(“foo”, “22”);
      getServletContext().setAttribute(“bar”, “42”);
      out.println(getServletContext().getAttribute(“foo”));
      out.println(getServletContext().getAttribute(“bar”));
    }
    }

    Protect session attributes by

    synchronizing on the HttpSession 

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
    response.setContentType(“text/html”);
    PrintWriter out = response.getWriter();
    out.println(“test session attributes<br>”);
    HttpSession session = request.getSession();
    synchronized(session) 
    {
    session.setAttribute(“foo”, “22”);; session.setAttribute(“bar”, “42”);
    out.println(session.getAttribute(“foo”));
    out.println(session.getAttribute(“bar”));
    }
    }

    5、RequestDispatcher

    Getting a RequestDispatcher from a ServletRequest 

    RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);;

    Getting a RequestDispatcher from a ServletContext 

    RequestDispatcher view = getServletContext().getRequestDispatcher(“/result.jsp”);;

    Calling forward() on a RequestDispatcher 

    view.forward(request, response);;

    You can’t forward the request if you’ve already committed a response

    第六章 Session

    1、

    So there’s an overloaded getSession(boolean) method just for that purpose. If you don’t want to create a new session, call getSession(false), and you’ll get either null, or a pre-existing HttpSession. 

    2、

    If cookies aren’t enabled, it means the client
    will never join the session. In other words,
    the session’s isNew() method will always return true

    3、

    A client with cookies disabled will ignore “Set-Cookie” response headers 

    4、URL rewrite

    If cookies don’t work, the Container falls back to URL rewriting, but only
    if you’ve done the extra work of encoding all the URLs you send in the response. I 

     If you do encode your URLs, the Container will first attempt to use cookies for session management, and fall back to URL rewriting only if the cookie approach fails. 

    out.println(“<a href=\”” + response.encodeURL(“/BeerTest.do”) + “\”>click me</a>”);;
    response.encodeRedirectURL(“/BeerTest.do”)

    5、session timeout

    Configuring a timeout in the DD has virtually the same effect as calling setMaxInactiveInterval() on every session that’s created. 

    <web-app ...>
     <servlet>... </servlet>
    <session-config>
    <session-timeout>15</session-timeout>
    </session-config>
    </web-app>

    Timeouts in the DD are in MINUTES! 

    session.setMaxInactiveInterval(20*60);

    The argument to the method is in seconds,

     
    6、Cookie

    Creating a new Cookie 

    Cookie cookie = new Cookie(“username”, name);

    Setting how long a cookie will live on the client 

    cookie.setMaxAge(30*60);;

    setMaxAge is defined in SECONDS. This code says “stay alive on the client for 30*60 seconds” (30 minutes). Setting max age to -1 makes the cookie disappear when the browser exits.  

    Sending the cookie to the client 

    response.addCookie(cookie);;

    Getting the cookie(s) from the client request 

    Cookie[] cookies = request.getCookies();; for (int i = 0;; i < cookies.length;; i++) {
    Cookie cookie = cookies[i];;
    if (cookie.getName().equals(“username”)) {
    String userName = cookie.getValue();; out.println(“Hello “ + userName);; break;;
    } }

    There’s no getCookie(String) method... you can only get cookies in a Cookie array, and then you have to loop over the array to find the one you want. 

    7、Session related listener

    暂时省略

  • 相关阅读:
    求解整数集合的交集(腾讯笔试)
    关于屏幕适配之比例布局
    (转)注册JNI函数的两种方式
    正则表达式记录
    当年一个简单可用的多线程断点续传类
    最近用到的几个工具方法
    Android中包含List成员变量的Parcel以及Parcel嵌套写法示例
    java实现计算MD5
    一个用于去除状态栏和虚拟导航栏的BaseActivity
    MVP的模板
  • 原文地址:https://www.cnblogs.com/wxy325/p/3072324.html
Copyright © 2011-2022 走看看