JavaWeb深入剖析

6.5、HttpServletRequest


HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息

1)概述

类似于HttpServletResponse

HttpServletRequest是接口,继承自ServletRequest接口

public interface HttpServletRequest extends ServletRequest {}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

6.6、请求转发 与 重定向


  • 相同点:都会实现页面的跳转

| 区别 | 请求转发 | 重定向 |

| — | — | — |

| 操作对象 | ServletContext 和 ServletRequest | HttpServletResponse |

| 方法 | getRequestDispatcher().forward() | sendRedirect() |

| url | 地址栏url不会发生变化

作用域的数据会被携带转发,包含有 getContextPath(),不用再显示添加 | 地址栏url会发生变化

应该在 url 中加上 getContextPath() |

| WEB-INF | 可以指向WEB-INF下的页面 | 不可以指向WEB-INF下的页面,否则会报404 |

7、Cookie、Session

==========================================================================

7.1、会话


  • 会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;

  • 有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;

7.2、保存会话的两种技术


  • Cookie

客户端技术 (响应,请求)

  • Session

服务器技术,利用这个技术,可以保存用户的会话信息;可以把信息或者数据放在Session中!

7.3、Cookie


Cookie是一个类,在包package javax.servlet.http中

可复制、可序列化

package javax.servlet.http;

public class Cookie implements Cloneable, Serializable{}

1)创建Cookie

// 构造器

Cookie(String name, String value)

2)设置有效期

// 设置有效期:单位秒

cookie.setMaxAge(24 * 60 * 60);

Cookie不设有效期,或者有效期为0时,关闭浏览器后不保存

3)获取键name

cookie.getName();

4)获取值value

cookie.getValue();

5)添加Cookie

// 把Cookie添加到响应对象中,输出给浏览器

response.addCookie(cookie);

6)获取Cookie

// 获取客户端的cookies数组

Cookie[] cookies = request.getCookies();

7)存取中文

// 编码

Cookie cookie1 = new Cookie(“username”, URLEncoder.encode(“abc测试”,“utf8”));

// 解码

String name = URLDecoder.decode(cookie.getValue(),“utf8”);

cookie:一般会保存在本地的用户目录下 appdata;

  • 一个Cookie只能保存一个信息

  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie

  • Cookie大小有限制4kb

  • 浏览器上限300个cookie

7.4、Session


1)概述

  • 服务器会给每一个用户(浏览器)创建一个Seesion对象;

  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;

  • 用户登录之后,整个网站它都可以访问!–> 保存用户的信息;保存购物车的信息…

HttpSession是接口,在包package javax.servlet.http中

package javax.servlet.http;

public interface HttpSession {}

2)Session和cookie的区别

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)

  • Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)

  • Session对象由服务器创建

3)使用场景

  • 保存一个登录用户的信息

  • 购物车信息

4)获取Session

HttpSession session = request.getSession();

5)属性Attribute

public Object getAttribute(String name);

public void setAttribute(String name, Object value);

public void removeAttribute(String name);

public Enumeration getAttributeNames();

6)ID

public String getId();

7)isNew

// 判断Session是否是新创建的

public boolean isNew();

8)ServletContext

public ServletContext getServletContext();

9)失效

(1)直接失效

public void invalidate();

(2)设置有效期

  • 调用方法

//(单位:秒)

setMaxInactiveInterval(int interval);

  • web.xml中配置

5

8、JSP

===============================================================

Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!

8.1、JSP本质


JSP本质上是一个Servlet

在这里插入图片描述

8.2、JSP对应的Servlet


每个JSP文件都对应一个java文件(Servlet),保存在Tomcat服务器的work目录下

如:index.jsp —> index_jsp.java

在这里插入图片描述

在这里插入图片描述

8.3、基础语法


1)JSP表达式

<%= 开头、%> 结尾

中间是可以直接输出的值、对象…

用来将程序的输出,输出到客户端

<%= new java.util.Date()%>

2)JSP脚本片段

<% 开头、%> 结尾

中间是java代码片段,会被添加到JSP对应的java类的 _jspService() 方法中

<%

int sum = 0;

for (int i = 1; i <=100 ; i++) {

sum+=i;

}

out.println(“

Sum=”+sum+“

”);

%>

3)JSP声明

<%! 开头、%> 结尾

中间可以写java代码段,定义属性方法,会被添加到 JSP 对应的java类中,不是 _jspService() 方法中

<%!

static {

System.out.println(“Loading Servlet!”);

}

private int globalVar = 0;

public void kuang(){

System.out.println(“进入了方法Kuang!”);

}

%>

4)JSP注释

<%-- 开头、--%> 结尾

中间写注释内容

JSP的注释,不会在客户端显示,HTML就会!

<%–

JSP注释

不会在客户端显示,HTML就会!

–%>

8.4、JSP指令


<%@page args… %>

<%@include file=“” %>

<%@taglib prefix=“” %>

  • head.jsp

不用

<%@ page …%>

  • foot.jsp

不用

<%@ page …%>

  • index.jsp

不用

<%@ page …%>

<%@include file=“head.jsp”%>

<%@include file=“foot.jsp” %>

8.5、JSP标签


<jsp:include page=“”/>

<jsp:xxx />

8.6、EL表达式 ${ }


使用标签、表达式之前要导入依赖包

Tomcat运行环境中也要有相关jar包

javax.servlet.jsp.jstl

jstl-api

1.2

taglibs

standard

1.1.2

8.7、JSTL标签


JSTL标签库的使用就是为了弥补HTML标签的不足;自定义有许多标签,功能和Java代码一样!

  • 格式化标签

  • SQL标签

  • XML 标签

  • 核心标签

<c:out value=“${}”/>

<c:if test=“${}” var=“”>

<c:out value=“”/>

</c:if>

<c:choose>

<c:when test=“${}”>

</c:when>

<c:when test=“${}”>

</c:when>

<c:otherwise>

</c:when>

</c:choose>

<c:forEach var=" " items=“${}”>

</c:forEach>

8.8、内置对象


// 页面上下文

PageContext pageContext;

// 请求

HttpServletRequest request;

// 响应

HttpServletResponse response;

// session

HttpSession session;

// 项目上下文

SerlvetContext application;

// 配置

SerlvetConfigconfig;

// 输出流

JspWriter out;

// 当前页

Objext page = this;

// 异常

Exception exception;

  • 作用域Scope

  • page

保存的数据只在当前页面中有效

  • request

保存的数据只在一次请求中有效,请求转发会携带这个数据

  • session

保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器

  • application

保存的数据在服务运行时有效,从打开服务器到关闭服务器

8.9、JavaBean


1)概述

JavaBean一般就是指一个普通的实体类(pojo)

  • 必须要有一个无参构造器

  • 属性必须私有化 private

  • 必须有对应的get/set方法

一般用来和数据库的字段做映射 ORM

ORM :对象关系映射

  • 表 —> 类

  • 字段 —> 属性

  • 行记录 —> 对象

2)JSP中用法

// 调用类;当前页有效

<jsp:useBean id=“student” class=“com.tuwer.pojo.Student” scope=“page”/>

// 设置属性值

<jsp:setProperty name=“student” property=“name” value=“小张”/>

// 获取值

<jsp:getProperty name=“student” property=“name”/>

8.10、404与500配置


404

/error/404.jsp

500

/error/500.jsp

8.11、新版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”>

9、MVC

===============================================================

Model View Controller 模型、视图、控制器

在这里插入图片描述

10、过滤器Filter

======================================================================

10.1、概述


Filter接口

package javax.servlet;

public interface Filter {}

在这里插入图片描述

功能:数据过滤

  • 权限检查

  • 中文乱码

  • 不良文字、图片…

10.2、使用步骤


解决中文乱码

1)导包

导入相关的依赖包

2)定义过滤器类

实现 javax.servlet.Filter 接口

package com.tuwer;

import javax.servlet.*;

import java.io.IOException;

/**

  • @author 土味儿

  • Date 2021/12/13

  • @version 1.0

  • 字符过滤器

*/

public class CharacterFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

System.out.println(“初始化过滤器!”);

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

request.setCharacterEncoding(“utf8”);

response.setCharacterEncoding(“utf8”);

System.out.println(“过滤前…”);

// 传递给下一链

chain.doFilter(request,response);

System.out.println(“过滤后…”);

}

public void destroy() {

System.out.println(“销毁过滤器!”);

}

}

3)在web.xml中配置 Filter

characterFilter

com.tuwer.CharacterFilter

characterFilter

/h/*

10.3、Filter实现权限拦截


登录案例

  • 用户访问个人中心页面
*   如果已成功登录,可以访问
*   如果没有登录,不可以访问,跳转到登录页面

在这里插入图片描述

在这里插入图片描述

  • jsp页

index.jsp

<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

Hello World!

中人中心

login.jsp

<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

登录

账号:

登录

myhome.jsp

<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

个人中心

欢迎你,<%=session.getAttribute(“username”)%>!


注销

  • Servlet

public class LoginServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String username = req.getParameter(“username”);

if(username!=null){

// 添加用户名

req.getSession().setAttribute(“username”,username);

// 重定向至个人中心

resp.sendRedirect(req.getContextPath()+“/user/myhome.jsp”);

}else{

// 重定向至登录页面

resp.sendRedirect(req.getContextPath()+“/login.jsp”);

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGet(req, resp);

}

}

public class LogoutServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Object username = req.getSession().getAttribute(“username”);

if(username!=null){

// 移除用户名

req.getSession().removeAttribute(“username”);

// 重定向至登录页面

resp.sendRedirect(req.getContextPath()+“/login.jsp”);

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGet(req, resp);

}

}

  • Filter

package com.tuwer;

import javax.servlet.*;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

/**

  • @author 土味儿

  • Date 2021/12/14

  • @version 1.0

*/

public class loginFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

System.out.println(“启动权限过滤器!”);

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

// 强转:HttpServletRequest 可以得到session,ServletRequest 不能得到session

HttpServletRequest req = (HttpServletRequest) request;

HttpServletResponse resp = (HttpServletResponse) response;

Object username = req.getSession().getAttribute(“username”);

// 未登录

if (username == null) {

System.out.println(req.getContextPath());

// 重定向至登录页面

resp.sendRedirect(req.getContextPath()+“/login.jsp”);

}

chain.doFilter(req,resp);

}

public void destroy() {

System.out.println(“销毁权限过滤器!”);

}

}

  • web.xml

login

com.tuwer.LoginServlet

login

/login

logout

com.tuwer.LogoutServlet

logout

/logout

loginFilter

com.tuwer.loginFilter

loginFilter

/user/myhome.jsp

  • 获取项目根路径

所有的请求链接都建立在根路径基础之上

<%=application.getContextPath()%>

<%=request.getContextPath()%>

<%=session.getServletContext().getContextPath()%>

// java代码

request.getContextPath();

11、监听器Listener

========================================================================

监听某个事件/动作的发生

  • 案例:统计在线人员;session的个数就是在线人数(会话);通过监听session的创建和销毁,把数据存入项目上下文application(ServletContext)对象中

11.1、定义监听器类


实现相应的监听器接口:HttpSessionLintener接口可以监听session的创建和销毁

监听器接口有很多种

package com.tuwer;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

/**

  • @author 土味儿

  • Date 2021/12/14

  • @version 1.0

  • 统计在线人数

  • session数量就是在线人数

*/

public class OnlineCountListener implements HttpSessionListener {

/**

  • 监听session创建

  • @param se

*/

public void sessionCreated(HttpSessionEvent se) {

// 获取项目上下文对象

ServletContext context = se.getSession().getServletContext();

// 得到在线人数

Integer onlineCount = (Integer) context.getAttribute(“onlineCount”);

if (onlineCount == null) {

// 第一个用户

onlineCount = new Integer(1);

} else {

// 用户数量加1

onlineCount = new Integer(onlineCount.intValue() + 1);

}

// 存入项目上下文对象ServletContext中

context.setAttribute(“onlineCount”, onlineCount);

}

/**

  • 监听session销毁

  • @param se

*/

public void sessionDestroyed(HttpSessionEvent se) {

// 获取项目上下文对象

ServletContext context = se.getSession().getServletContext();

// 得到在线人数

Integer onlineCount = (Integer) context.getAttribute(“onlineCount”);

if (onlineCount == null) {

// 第一个用户

onlineCount = new Integer(0);

} else {

// 用户数量减1

onlineCount = new Integer(onlineCount.intValue() - 1);

}

// 存入项目上下文对象ServletContext中

context.setAttribute(“onlineCount”, onlineCount);

}

}

11.2、web.xml中配置


## 最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
CountListener implements HttpSessionListener {

/**

  • 监听session创建

  • @param se

*/

public void sessionCreated(HttpSessionEvent se) {

// 获取项目上下文对象

ServletContext context = se.getSession().getServletContext();

// 得到在线人数

Integer onlineCount = (Integer) context.getAttribute(“onlineCount”);

if (onlineCount == null) {

// 第一个用户

onlineCount = new Integer(1);

} else {

// 用户数量加1

onlineCount = new Integer(onlineCount.intValue() + 1);

}

// 存入项目上下文对象ServletContext中

context.setAttribute(“onlineCount”, onlineCount);

}

/**

  • 监听session销毁

  • @param se

*/

public void sessionDestroyed(HttpSessionEvent se) {

// 获取项目上下文对象

ServletContext context = se.getSession().getServletContext();

// 得到在线人数

Integer onlineCount = (Integer) context.getAttribute(“onlineCount”);

if (onlineCount == null) {

// 第一个用户

onlineCount = new Integer(0);

} else {

// 用户数量减1

onlineCount = new Integer(onlineCount.intValue() - 1);

}

// 存入项目上下文对象ServletContext中

context.setAttribute(“onlineCount”, onlineCount);

}

}

11.2、web.xml中配置


## 最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-SqkuSwWS-1715714866926)]

[外链图片转存中…(img-0QpZ8Iju-1715714866927)]

[外链图片转存中…(img-XvKXOena-1715714866927)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值