servlet1

servlet 使用筆記

maven依賴

<dependencies>
  <!-- servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

  <!--配置初始化參數(shù)-->
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/database</param-value>
  </context-param>

  <!--配置servlet映射-->
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.anyi.servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

</web-app>

servlet實(shí)現(xiàn)類

構(gòu)建servlet實(shí)現(xiàn)類,實(shí)現(xiàn):輸出文本到html

public class HelloServlet extends HttpServlet { // 繼承HttpServlet
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("doGet");
    resp.setContentType("text/html"); // 設(shè)置內(nèi)容類型為html
    resp.setCharacterEncoding("utf-8"); // 設(shè)置字符編碼為utf-8
    resp.getWriter().print("我是html頁(yè)面上的一句話。"); //輸出文本到html
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("doPost");
    doGet(req, resp); //可以使用 get 的處理方式
  }
}

servletcontext

1. servlet之間數(shù)據(jù)交互

public class HelloServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("doGet");

    // 獲取servlet上下文對(duì)象 servletcontext
    ServletContext context = this.getServletContext();

    // 1.存儲(chǔ)數(shù)據(jù)
    String username = "張三";
    context.setAttribute("username", username);

    // 2.獲取數(shù)據(jù),可以不在此servlet獲取
    ServletContext context = this.getServletContext();
    String username = (String) context.getAttribute("username");

    // 輸出信息看
    System.out.println("用戶名 = " + username);
  }
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("doPost");
    doGet(req, resp);
  }
}

2. 獲取初始化參數(shù)

public class HelloServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("doGet");
    
    ServletContext context = this.getServletContext();
    
    // 獲取web.xml的初始context參數(shù)
    String url = context.getInitParameter("url"); //獲取參數(shù)名為url的數(shù)據(jù)
    
    // 輸出信息看
    System.out.println("url = " + url);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("doPost");
    doGet(req, resp);
  }
}

3. 請(qǐng)求轉(zhuǎn)發(fā)307

public class HelloServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    
    // 請(qǐng)求轉(zhuǎn)發(fā)
    // RequestDispatcher requestDispatcher
    //  = context.getRequestDispatcher("geturl");
    // requestDispatcher.forward(req,resp);
    
    context.getRequestDispatcher("/geturl").forward(req,resp); 
    //請(qǐng)求轉(zhuǎn)發(fā)到/geturl,此為web.xml中配置的url-pattern,(這里沒(méi)有配置/geturl路徑,假設(shè)它已存在)
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

4. 讀取配置文件

public class ServletDemo05 extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 通過(guò)context獲取資源輸入流,此處是從web路徑為相對(duì)路徑讀取
    InputStream is = this.getServletContext()
      .getResourceAsStream("/WEB-INF/classes/db.properties");
    // 讀取properties文件
    Properties prop = new Properties();
    prop.load(is);
    // 獲取信息,展示
    String username = prop.getProperty("username");
    String password = prop.getProperty("password");
    resp.getWriter().println("username: " + username);
    resp.getWriter().println("password: " + password);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}
image-20240513235445200.png

HttpServletResponse

1. 獲取輸出流,輸出

用于一般輸出流

ServletOutputStream outputStream = resp.getOutputStream();

用于寫出 中文 字符串

PrintWriter writer = resp.getWriter();

2. 下載文件

public class FileServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("下載文件");
    //獲取真實(shí)資源路徑,此方法x
    //String realPath = this.getServletContext().getRealPath("/水彩畫.jpg");
    String realPath = "D:\\....\\水彩畫.jpg";
    System.out.println(realPath);
    // 獲取文件名
    String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
    // 設(shè)置作為附件下載的響應(yīng)頭
    resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8")/*進(jìn)行編碼,防止中文亂碼*/);
    // 傳輸文件
    FileInputStream is = new FileInputStream(realPath); //打開(kāi)文件
    ServletOutputStream os = resp.getOutputStream(); //獲取輸出流
    int len;
    byte[] buffer = new byte[1024]; //創(chuàng)建緩沖區(qū)
    while ((len = is.read(buffer)) != -1) {
      os.write(buffer,0,len); //寫入
    }
    is.close();
    os.close();
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

3. 展示隨機(jī)數(shù)字的圖片

public class ImageServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
    // 獲取驗(yàn)證碼
    BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB); //創(chuàng)建一張圖片
    Graphics2D g = (Graphics2D) image.getGraphics();//獲取2d畫筆
    g.setColor(Color.white);//選擇顏色
    g.drawRect(0, 0, 80, 40);//畫實(shí)心矩形
    g.setColor(Color.RED);//選擇顏色
    g.setFont(new Font("楷體", Font.BOLD, 16));//設(shè)置文字的樣式
    g.drawString(getRandomStr(), 10, 16);//畫字符串

    // 設(shè)置內(nèi)容為圖片jpg
    resp.setContentType("image/jpg");
    // 設(shè)置緩存控制為:不緩存
    resp.setHeader("Cache-Control", "no-cache");
    // 讓瀏覽器每三秒刷新一次
    resp.setHeader("refresh", "3");
    // 寫入圖片
    ImageIO.write(image, "jpg", resp.getOutputStream());
  }

  /**
     * 獲取隨機(jī)數(shù)字的字符串
     * @return 4位隨機(jī)數(shù)字的字符串
     */
  private String getRandomStr() {
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < 4; i++) {
      sb.append(random.nextInt(9));
    }
    return sb.toString();
  }
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

4. 重定向302

public class RedirectServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //重定向到當(dāng)前web應(yīng)用的/image ,注意這里的uri要寫全,
    //req.getContextPath()表示當(dāng)前web應(yīng)用的路徑
    resp.sendRedirect(req.getContextPath()+"/image");
    
    /*
    *相當(dāng)于
        resp.setHeader("Location",req.getContextPath()+"/image");
        resp.setStatus(HttpServletResponse.SC_FOUND);//302
         */
  }
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req,resp);
  }
}

HttpServletRequest

1. 獲取傳遞的參數(shù)

public class LoginServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 解決兩個(gè)亂碼問(wèn)題,從req讀取 和 向resp寫入
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");

    // 獲取傳遞的參數(shù)
    String username = req.getParameter("username"); //單個(gè)參數(shù),name值
    String password = req.getParameter("password"); //單個(gè)參數(shù),name值
    String[] hobbies = req.getParameterValues("hobbies"); //多個(gè)參數(shù),name值

    // 請(qǐng)求轉(zhuǎn)發(fā)
    req.getRequestDispatcher("/success.jsp").forward(req,resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

Cookie

1. 獲取cookie

獲取所有cookie

Cookie[] cookies = req.getCookies();

2. 添加cookie

創(chuàng)建cookie

Cookie cookie = new Cookie("key","value");

添加cookie

resp.addCookie(cookie);

3. 設(shè)置有效期及刪除cookie

設(shè)置cookie有效期。不設(shè)置默認(rèn)為:關(guān)閉瀏覽器后刪除

cookie.setMaxAge(time);

刪除cookie:設(shè)置有效時(shí)間為0

cookie.setMaxAge(0);

重新添加cookie

resp.addCookie(cookie);

3. cookie信息獲取

獲取cookie名

String name = cookie.getName();

獲取cookie值

String value = cookie.getValue();


### 4. 舉例

```java
public class CookiesServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 設(shè)置編碼格式為utf-8
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");

    // 獲取所有cookie
    Cookie[] cookies = req.getCookies();

    if (cookies != null) {
      // cookies存在,查找是否有本站的cookie
      for (Cookie cookie : cookies) {
        if ("cookies-servlet-demo-1".equals(cookie.getName())) {
          // 留有此網(wǎng)站的cookie
          resp.setContentType("text/html");
          resp.getWriter().println(
            "自動(dòng)登錄成功,\ncookie: " + cookie.getValue());
          // 刪除cookie
          cookie.setMaxAge(0);// 設(shè)置有效時(shí)間為0
          resp.addCookie(cookie);// 重新添加cookie
          return;
        }
      }
    }
    // cookie不存在

    // 設(shè)置cookie
    Cookie cookie = new Cookie("cookies-servlet-demo-1", LocalDateTime.now().toString()); //創(chuàng)建cookie
    resp.addCookie(cookie); //添加cookie

    // 輸出信息
    resp.setContentType("text/html");
    resp.getWriter().println("這是你第一次登錄此網(wǎng)站,");
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

HttpSession

1. 獲取Session

從request中獲取session

HttpSession session = req.getSession();

2. 存儲(chǔ)與獲取數(shù)據(jù)

存儲(chǔ)數(shù)據(jù)到session,不一定是字符串

session.setAttribute("key", "value");

取出數(shù)據(jù),可根據(jù)存儲(chǔ)的類型 進(jìn)行類型轉(zhuǎn)換

String value = (String) session.getAttribute("key");

session信息會(huì)在服務(wù)器自動(dòng)存儲(chǔ),實(shí)際底層會(huì)自動(dòng)的將Session的id作為cookie發(fā)送給服務(wù)器,以標(biāo)識(shí)身份。

如:resp.addCookie(new Cookie("JSESSIONID",req.getSession().getId()));

獲取Session_id的方法

String id = session.getId();

3.刪除與注銷session

刪除指定信息

session.removeAttribute("key");

注銷這個(gè)session會(huì)話

session.invalidate();

4. 判斷是否為新session

服務(wù)端未保存此session,或者用戶禁止使用時(shí)返回true

boolean b = session.isNew()

5. web.xml中配置失效時(shí)間

<session-config>
  <!-- 設(shè)置有效時(shí)間為1分鐘 -->
  <session-timeout>1</session-timeout> 
</session-config>

6. 舉例

public class SessionServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html");

    HttpSession session = req.getSession();// 獲取session
    String value = null;

    // 判斷是否為新session
    if (session.isNew()) {
      // 存儲(chǔ)數(shù)據(jù),不一定是字符串
      session.setAttribute("key", "value123123122232321");
      resp.getWriter().println("歡迎新用戶到來(lái),");
    } else {
      resp.getWriter().println("你在此保留的信息為:");
      // 取出數(shù)據(jù),可根據(jù)存儲(chǔ)的類型 進(jìn)行類型轉(zhuǎn)換
      value = (String) session.getAttribute("key");
      session.removeAttribute("key");// 刪除指定信息
      session.invalidate();//注銷這個(gè)會(huì)話
    }
    resp.getWriter().println("key: " + value);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

附:

1. 中文亂碼的解決

傳輸數(shù)據(jù)時(shí)出現(xiàn)中文亂碼時(shí)使用URLEncoder和URLDecoder進(jìn)行編碼解碼

String info = "str";
String code = URLEncoder.encode(info,"UTF-8");
// 數(shù)據(jù)傳輸...
String info = URLDecoder.decode(code,"UTF-8");
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第2章 Java Web的核心技術(shù)----Servlet 2.1 編寫第一Servlet程序----HelloWo...
    歲月靜好淺笑安然閱讀 333評(píng)論 0 0
  • Servlet 即用于處理HTTP請(qǐng)求的類,該部分的類都處于javax.servlet下。 頁(yè)面跳轉(zhuǎn)方式 分為服務(wù)...
    dawsonenjoy閱讀 178評(píng)論 0 0
  • javaweb復(fù)習(xí) <!--外部引入 注意:script必須成對(duì)出現(xiàn) --> ? <!--不用顯示定義...
    拾憶11閱讀 637評(píng)論 0 0
  • 事務(wù)是一系列的操作,當(dāng)所有的步驟像一個(gè)操作一樣被完整地執(zhí)行,我們稱該事務(wù)被提交。由于其中的一部分或多步執(zhí)行失敗,導(dǎo)...
    coke_dd41閱讀 304評(píng)論 0 0
  • Web應(yīng)用程序 WEB,在英語(yǔ)中web即表示網(wǎng)頁(yè)的意思,它用于表示Internet主機(jī)上供外界訪問(wèn)的資源。Inte...
    友人Ay閱讀 1,107評(píng)論 0 0

友情鏈接更多精彩內(nèi)容