尚硅谷最新版JavaWeb全套教程,java web零基础入门完整版(四)
生活随笔
收集整理的這篇文章主要介紹了
尚硅谷最新版JavaWeb全套教程,java web零基础入门完整版(四)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文件的上傳和下載
文件上傳的介紹
<?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"><servlet><servlet-name>UploadServlet</servlet-name><servlet-class>com.atguigu.servlet.UploadServlet</servlet-class></servlet><servlet-mapping><servlet-name>UploadServlet</servlet-name><url-pattern>/uploadServlet</url-pattern></servlet-mapping> </web-app> package com.atguigu.servlet;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;public class UploadServlet extends HttpServlet {/*** 用來處理文件生成* @param req* @param resp* @throws ServletException* @throws IOException*/@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("文件上傳過來了");} } <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body><%-- form:post --%><form action="http://localhost:8080/jstl/uploadServlet" method="post" enctype="multipart/form-data">用戶名 :<input type="text" name="username"> <br>頭像 :<input type="file" name="photo"> <br><input type="submit" value="上傳"></form> </body> </html>
上傳的http協議介紹
- 以流的形式上傳和接收
- 所以如果用getPraramter沒有用
上傳合用到的類和方法介紹
使用fileupload解析上傳的數據
選中整行以后 command + option + t 快捷鍵
然后選擇 try catch,然后手動改成Exception
文件下載的實現
輸入后敲回車,直接就下載文件了
使用URLEncoder解決谷歌和IE瀏覽器中文下載名亂碼問題
可以和原文件名不同,下載下來顯示的名稱就是filename
如果filename=中國.jpg,文件名會無法識別
因此,要對中文進行URL編碼
Base64編解碼操作
如果是火狐瀏覽器不支持上面這種方式
發現這個類和URLEncode類不同,不是靜態方法,因此要先new
Base64編解碼操作 解決 火狐瀏覽器的附近中文名問題
將原先那個setHeader換成resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode("中國.jpg".getBytes("UTF-8")) + "?=");
使用User-Agent請求頭判斷,動態切換不同的方案解決所有瀏覽器附件中文亂碼問題
書城項目
- command + shift + R 可以查找替換(可以先選中目錄)
動態的base標簽值
表單提交失敗的錯誤回顯
合并LoginServlet和RegistServlet程序為UserServlet程序
使用反射優化大量else if代碼
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("action"); try {// 獲取 action 業務鑒別字符串,獲取相應的業務 方法反射對象 Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // System.out.println(method); // 調用目標業務 方法 method.invoke(this, req, resp); } catch (Exception e) {e.printStackTrace(); } }抽取 BaseServlet 程序
public abstract class BaseServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("action"); try {// 獲取 action 業務鑒別字符串,獲取相應的業務 方法反射對象 Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // System.out.println(method); // 調用目標業務 方法 method.invoke(this, req, resp); } catch (Exception e) { e.printStackTrace(); } } }數據的封裝和抽取 BeanUtils 的使用
- command + option + t 選擇代碼的環繞方式
MVC概念
Cookie
什么是Cookie
Cookie的創建
<!-- Cookie.html --> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie</title><!-- 因為是html頁面 --><base href="http://localhost:8080/cookie/"> <style type="text/css">ul li {list-style: none;}</style> </head> <body><iframe name="target" width="500" height="500" style="float: left;"></iframe><div style="float: left;"><ul><li><a href="cookieServlet?action=createCookie" target="target">Cookie的創建</a></li><li><a href="cookieServlet?action=getCookie" target="target">Cookie的獲取</a></li><li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li><li>Cookie的存活周期</li><li><ul><li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默認存活時間(會話)</a></li><li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即刪除</a></li><li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小時)</a></li></ul></li><li><a href="cookieServlet?action=testPath" target="target">Cookie的路徑設置</a></li><li><a href="" target="target">Cookie的用戶免登錄練習</a></li></ul></div> </body> </html> package com.atguigu.servlet;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method;public abstract class BaseServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 解決post請求中文亂碼問題// 一定要在獲取請求參數之前調用才有效req.setCharacterEncoding("UTF-8");// 解決響應中文亂碼問題resp.setContentType("text/html; charset=UTF-8");String action = req.getParameter("action");try {// 獲取action業務鑒別字符串,獲取相應的業務 方法反射對象Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // System.out.println(method);// 調用目標業務 方法method.invoke(this, req, resp);} catch (Exception e) {e.printStackTrace();}}} package com.atguigu.servlet;import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;public class CookieServlet extends BaseServlet{protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1、創建Cookie對象Cookie cookie = new Cookie("key1", "value1");// 2、通知客戶端保存Cookieresp.addCookie(cookie);resp.getWriter().write("Cookie創建成功");} }
Cookie的獲取
package com.atguigu.servlet;import com.example.Cookie.CookieUtils;import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;public class CookieServlet extends BaseServlet{protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1、創建Cookie對象Cookie cookie = new Cookie("key1", "value1");// 2、通知客戶端保存Cookieresp.addCookie(cookie);resp.getWriter().write("Cookie創建成功");}protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie[] cookies = req.getCookies();// getName方法// getValue方法for (Cookie cookie : cookies) {resp.getWriter().write("Cookie[" + cookie.getName() + " = " + cookie.getValue() + "] <br>");}Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);if (iWantCookie != null) {resp.getWriter().write("找到了需要的Cookie");}} } package com.atguigu.util;import javax.servlet.http.Cookie;public class CookieUtils {/*** 查找指定名稱的cookie對象* @param name* @param cookies* @return*/public static Cookie findCookie(String name, Cookie[] cookies) {if (name == null || cookies == null || cookies.length == 0) {return null;}for (Cookie cookie : cookies) {if (name.equals(cookie.getName())) {return cookie;}}return null;} } <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie</title><!-- 因為是html頁面 --><base href="http://localhost:8080/cookie/"> <style type="text/css">ul li {list-style: none;}</style> </head> <body><iframe name="target" width="500" height="500" style="float: left;"></iframe><div style="float: left;"><ul><li><a href="cookieServlet?action=createCookie" target="target">Cookie的創建</a></li><li><a href="cookieServlet?action=getCookie" target="target">Cookie的獲取</a></li><li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li><li>Cookie的存活周期</li><li><ul><li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默認存活時間(會話)</a></li><li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即刪除</a></li><li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小時)</a></li></ul></li><li><a href="cookieServlet?action=testPath" target="target">Cookie的路徑設置</a></li><li><a href="" target="target">Cookie的用戶免登錄練習</a></li></ul></div> </body> </html><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie</title><!-- 因為是html頁面 --><base href="http://localhost:8080/cookie/"> <style type="text/css">ul li {list-style: none;}</style> </head> <body><iframe name="target" width="500" height="500" style="float: left;"></iframe><div style="float: left;"><ul><li><a href="cookieServlet?action=createCookie" target="target">Cookie的創建</a></li><li><a href="cookieServlet?action=getCookie" target="target">Cookie的獲取</a></li><li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li><li>Cookie的存活周期</li><li><ul><li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默認存活時間(會話)</a></li><li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即刪除</a></li><li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小時)</a></li></ul></li><li><a href="cookieServlet?action=testPath" target="target">Cookie的路徑設置</a></li><li><a href="" target="target">Cookie的用戶免登錄練習</a></li></ul></div> </body> </html>Cookie值的修改
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 方案一 : // 1、先創建一個要修改的同名的Cookie對象 // 2、在構造器,同時賦于新的cookie值Cookie cookie = new Cookie("key1", "newValue1"); // 3、調用resp.addCookie(cookie); ;通知 客戶端 保存修改resp.addCookie(cookie);resp.getWriter().write("key1的cookie已經修改好了");} protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie cookie = CookieUtils.findCookie("key1", req.getCookies());if (cookie != null) {cookie.setValue("newValue1");resp.addCookie(cookie);}}- 中文也是
谷歌和火狐瀏覽器如何查看Cookie
Cookie的生命設置
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie cookie = new Cookie("defaultLife", "defaultLife");cookie.setMaxAge(-1); // 設置存活時間resp.addCookie(cookie);} protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 先找到要刪除的cookie對象Cookie cookie = CookieUtils.findCookie(("key1"), req.getCookies());if (cookie != null) {// 調用setMaxAge(0);cookie.setMaxAge(0); // 表示馬上刪除,都不需要等待瀏覽器關閉// 調用addCookieresp.addCookie(cookie);resp.getWriter().write("key1的cookie已經被刪除");}}Cookie 有效路徑 Path 的設置
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie cookie = new Cookie("path1", "path1");// getContextPath 得到工程路徑cookie.setPath( req.getContextPath() + "/abc" ); // 工程路徑/abcresp.addCookie(cookie);resp.getWriter().write("創建了一個帶有Path路徑的Cookie");}Cookie 練習—免輸入用戶名登錄
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>login.jsp</title> </head> <body><form action="http://localhost:8080/cookie/loginServlet" method="get">用戶名:<input type="text" name="username" value="${ cookie.username.value }"> <br>密碼:<input type="password" name="password"> <br><input type="submit" value="登陸"></form> </body> </html> package com.atguigu.servlet;import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;public class LoginServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String username = req.getParameter("username");String password = req.getParameter("password");if ("wzg168".equals(username) && "123456".equals(password)) {Cookie cookie = new Cookie("username", username);cookie.setMaxAge(60 * 60 * 24 * 7); // 當前Cookie一周內有效resp.addCookie(cookie);System.out.println("登陸成功");} else {System.out.println("登陸失敗");}} }- 在登陸成功一次,且在cookie消亡時間之前,再次訪問login.jsp用戶名會自動顯示
總結
以上是生活随笔為你收集整理的尚硅谷最新版JavaWeb全套教程,java web零基础入门完整版(四)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL进阶教程 | 史上最易懂SQL教程
- 下一篇: JSP内置对象(request、sess