首页 > 技术文章 > Jsp&Servlet 学习笔记

jinss 2021-02-26 19:03 原文

第一节:Jsp 概述

 

第二节:B/S vs C/S

B/S系统是 浏览器/服务器(瘦客户端); C/S系统是 客户端/服务器(胖客户端)。

 

第三节:Tomcat 服务器

简介:百度百科。

安装及配置:百度。

目录结构:

 

第五节:问候他大爷

第一个Jsp程序:

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

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>问候Jsp他大爷</title>

</head>

<body>

问候Jsp他大爷

</body>

</html>

(在Tomcat服务器上运行,具体实现略)

 

第二章 Jsp 基础语法

第一节:page 指令介绍

Language : 用来定义要使用的脚本语言;

contentType:定义 JSP 字符的编码和页面响应的 MIME 类型;

pageEncoding:Jsp 页面的字符编码

 

 

第二节:scriptlet 标签

通过 scriptlet 标签我们可以在 Jsp 里嵌入 Java 代码;

 

脚本程序:可以包含任意量的Java语句、变量、方法或表达式。

语法格式:<% 代码片段 %>

 

JSP声明:一个声明语句可以声明一个或多个变量、方法,供后面的Java代码使用。

语法格式:<%! declaration; [ declaration; ]+ ... %>

JSP表达式:一个JSP表达式中包含的脚本语言表达式,先被转化成String,然后插入到表达式出现的地方。

语法格式:<%= 表达式 %>

 

第三节:Jsp 注释

<!-- --> Html 注释 客户端源码可见

<%-- --%> Jsp 注释 客户端源码不可见

// java 单行注释

/* */ java 多行注释

 

 

第四节:Jsp 包含指令

<%@ include file=”要包含的文件”%> 静态包含:先包含,后编译处理;

<h1>静态包含</h1>

<%@ include file="common/head.jsp" %>

<p>content</p>

<%@ include file="common/foot.jsp" %>

<jsp:include page=”要包含的文件”/> 动态包含:先编译处理,后包含;

<h1>动态包含</h1>

<jsp:include page="common/head.jsp"/>

<p>content</p>

<jsp:include page="common/foot.jsp"/>

(建议开发用动态包含。)

 

第五节:Jsp 跳转指令

<jsp:forward page=” ”>

<jsp:param value=”” name=””>

</jsp:forward>

服务器内部跳转,可带参数;

 

<title>Jsp 跳转指令</title>

</head>

<body>

<jsp:forward page="target.jsp">

<jsp:param value="huang" name="userName"/>

<jsp:param value="123" name="password"/>

</jsp:forward>

</body>

-----------------------------------------------------------

<title>Jsp 跳转后页面target</title>

</head>

<body>

服务器内部跳转后的页面<br>

userName:<%=request.getParameter("userName") %><br>

password:<%=request.getParameter("password") %><br>

</body>

第三章 JSP 九大内置对象及四个作用域

 

第一节:Jsp 九大内置对象及四大作用域概述

在Jsp开发中,Jsp提供了9个内置对象,这些内置对象将由容器为用户进行实例化,用户直接使用即可。

这9个内置对象分别是:

pageContext,request,response,session,application,config,out,page,exception;常用的是前面 5个,需要熟练掌握。

在Jsp开发中,可以保存数据,Jsp提供了四种数据保存范围;分别是 page,request,session,application。

 

 

第二节:Jsp 四大作用域

Page 范围:

只在一个页面中保存数据; javax.servlet.jsp.PageContext(抽象类)

<body>

<%

// 设置两个page范围的数据 key->value

pageContext.setAttribute("name","page王二小");

pageContext.setAttribute("age",12);

%>

<%

// 取值

String name=(String)pageContext.getAttribute("name");

int age=(Integer)pageContext.getAttribute("age");

%>

<font>姓名:<%=name %></font>

<font>年龄:<%=age %></font>

 

Request 范围:

只在一个请求中保存数据; javax.servlet.http.HttpServletRequest(接口)

RequestScope.jsp

<body>

<%

// 设置两个request范围的数据 key-> value

request.setAttribute("name","request王二小");

request.setAttribute("age",12);

%>

<jsp:forward page="requestTarget.jsp"></jsp:forward>

</body>

RequestTarget.jsp

<body>

<%

// 取值

String name=(String)request.getAttribute("name");

int age=(Integer)request.getAttribute("age");

%>

<font>姓名:<%=name %></font>

<font>年龄:<%=age %></font>

</body>

 

Session 范围:

在一次会话范围中保存数据,仅供单个用户使用;

javax.servlet.http.HttpSession(接口)

sessionScope.jsp

<body>

<%

// 设置两个session范围的数据 key-> value

session.setAttribute("name","session王二小");

session.setAttribute("age",12);

%>

<h1>session值设置完毕!</h1>

</body>

sessionTarget.jsp

<%

// 取值

String name=(String)session.getAttribute("name");

int age=(Integer)session.getAttribute("age");

%>

<font>姓名:<%=name %></font>

<font>年龄:<%=age %></font>

 

Application 范围:

在整个服务器上保存数据,所有用户共享;javax.servlet.ServletContext(接口)

applicationScope.jsp

<body>

<%

// 设置两个application范围的数据 key-> value

application.setAttribute("name","application王二小");

application.setAttribute("age",12);

%>

<h1>application值设置完毕!</h1>

</body>

 

applicationTarget.jsp

<body>

<%

// 取值

String name=(String)application.getAttribute("name");

int age=(Integer)application.getAttribute("age");

%>

<font>姓名:<%=name %></font>

<font>年龄:<%=age %></font>

</body>

 

 

第三节:response 对象

response内置对象和request内置对象是相对应的,response内置对象用于响应客户请求,向客户端输出信息;javax.servlet.HttpServletResponse 接口。

自动刷新应用

<body>

<%

// 每隔一秒刷新一次页面

response.setHeader("refresh","1");

// 获取当前时间

Date myDate=new Date();

%>

当前时间:<%= myDate.toLocaleString() %>

</body>

2,页面重定向应用客户端跳转

<%

// 重定向,客户端跳转,网址会变

response.sendRedirect("index.html");

%>

3,操作cookie应用 post、get方法比较:post放数据包里;get放Url后面,get数据量小,不安全;

//response03.jsp

<title>登录页面</title>

<script type="text/javascript">

function resetValue(){

document.getElementById("userName").value="";

document.getElementById("pwd").value="";

}

</script>

<%

String userName=null;

String pwd=null;

Cookie[] cookies=request.getCookies();

for(int i=0;cookies!=null &&i<cookies.length;i++){

if(cookies[i].getName().equals("userNameAndPwd")){

userName=cookies[i].getValue().split("-")[0];

pwd=cookies[i].getValue().split("-")[1];

}

}

 

if(userName==null){

userName="";

}

 

if(pwd==null){

pwd="";

}

%>

</head>

<body>

<form action="userLogin.jsp" method="post">

<table>

<tr>

<td>用户名:</td>

<td><input type="text" id="userName" name="userName" value="<%=userName%>"/></td>

</tr>

<tr>

<td>密码:</td>

<td><input type="password" id="pwd" name="pwd" value="<%=pwd %>" /></td>

</tr>

<tr>

<td>记住密码:</td>

<td><input type="checkbox" id="remember" name="remember" value="remember-me"/></td>

</tr>

<tr>

<td><input type="submit" value="登录"/></td>

<td><input type="button" value="重置" onclick="resetValue()"/></td>

</tr>

</table>

</form>

</body>

//userLogin.jsp

<body>

<%

String userName=request.getParameter("userName"); // 获取用户名

String pwd=request.getParameter("pwd"); // 获取密码

String remember=request.getParameter("remember"); // 获取记住密码

 

if("remember-me".equals(remember)){

Cookie userNameAndPwd=new Cookie("userNameAndPwd",userName+"-"+pwd);

userNameAndPwd.setMaxAge(1*60*60*24*7); // cookie记录一个星期

response.addCookie(userNameAndPwd); // 保存cookie

System.out.println("设置Cookie成功");

}

// response.sendRedirect("response03.jsp");

%>

登录成功

</body>

4,cookie和session的比较:cookie信息是存客户端的,session 信息是存服务器的;

 

第四节:out 对象

Out 内置对象主要用来向客户端输出各种类型的数据,同时还可以管理应用服务器上的输出缓冲区。所以out内置对象的方法是向客户端输出数据和管理缓冲区; 底层javax.servlet.jsp.JspWriter 抽象。

<body>

<%

int totalbuffer=out.getBufferSize(); // 获取总缓冲区的大小

int available=out.getRemaining(); // 获取未使用的缓冲区的大小

int user=totalbuffer-available; // 获取使用的缓冲区大小

out.println("总共缓冲区的大小:"+totalbuffer);

out.println("未使用的缓冲区的大小:"+available);

out.println("使用的缓冲区大小:"+user);

%>

</body>

 

第五节:config 对象

config 内置对象是JSP页面通过JSP容器进行初始化时被传递的对象。javax.servlet.ServletConfig 。

在Servlet初始化的时候,JSP引擎通过config 向它传递信息。这种信息可以是属性名和属性值匹配的参数,也可以是通过ServletContext对象传递的服务器的有关信息。

//web.xml

<servlet>

<servlet-name>init</servlet-name>

<jsp-file>/sysInit.jsp</jsp-file>

<init-param>

<param-name>jdbcName</param-name>

<param-value>com.mysql.jdbc.Driver</param-value>

</init-param>

<init-param>

<param-name>dbUrl</param-name>

<param-value>jdbc:mysql://localhost:3306/db_xx</param-value>

</init-param>

</servlet>

 

<servlet-mapping>

<servlet-name>init</servlet-name>

<url-pattern>/init</url-pattern>

</servlet-mapping>

 

//sysInit.jsp

<body>

<%

String jdbcName=config.getInitParameter("jdbcName");

String dbUrl=config.getInitParameter("dbUrl");

%>

<h1>驱动名称:<%=jdbcName %></h1>

<h1>连接地址:<%=dbUrl %></h1>

</body>

 

请求地址:http://localhost:8081/JspServlet/init

 

第六节:exception 对象

exception 内置对象用来处理JSP文件在执行时发生的所有异常,它是java.lang.Throwable 类的一个对象。

//exception01.jsp

<%@ page errorPage="error.jsp"%>

...

<body>

<%

int a=1;

int b=0;

out.println(a/b);

%>

</body>

 

//error.jsp

<%@ page isErrorPage="true"%>

...

<body>

<%

if(exception!=null){

out.println("程序错误信息:");

out.println(exception.getMessage());

}

%>

</body>

第七节:pageContext 对象

pageContext 内置对象是一个比较特殊的对象。它相当于页面中所有对象功能的集合,即使用它可以访问到本页面中所有对象。pageContext 内置对象由Jsp 容器创建并初始化,pageContext 对象提供了对JSP 页面所有对象及控件的访问。

<body>

<%

pageContext.setAttribute("name0", "pageInfo");

request.setAttribute("name1", "requestInfo");

session.setAttribute("name2", "sessionInfo");

application.setAttribute("name3", "applicationInfo");

 

out.println("使用pageContext<br/>");

out.println("page中的属性值:"+pageContext.getAttribute("name0")+"<br/>");

out.println("request中的属性值:"+pageContext.getRequest().getAttribute("name1")+"<br/>");

out.println("session中的属性值:"+pageContext.getSession().getAttribute("name2")+"<br/>");

out.println("application中的属性值:"+pageContext.getServletContext().getAttribute("name3")+"<br/>");

%>

</body>

 

第四章 JavaBean组件

第一节:Javabean 组件引入

JavaBean 是使用Java 语言开发的一个可重用的组件,在JSP 开发中可以使用JavaBean 减少重复代码,使整个JSP 代码的开发更简洁。

 

第二节:jsp:useBean 创建javabean

<jsp:useBean id="实例化对象名称" scope="保存范围" class="类完整名称"/>

Scope一共有page,request,session和application 4个属性范围,默认是page;

<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>

<%

student.setName("王二小2");

student.setAge(12);

%>

<h1>姓名:<%=student.getName() %></h1>

<h1>年龄:<%=student.getAge() %></h1>

</body>

第三节:jsp:setProperty 设置javabean 属性值

<jsp:setProperty property="属性名称" name="实例化对象的名称" value="属性值" param="参数名称"/>

当 property=”*” 时,自动匹配所有属性。

<body>

<% request.setCharacterEncoding("utf-8"); %>

<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>

<jsp:setProperty property="*" name="student"/> <!-- 自动匹配所有属性 -->

<h1>姓名:<%=student.getName() %></h1>

<h1>年龄:<%=student.getAge() %></h1>

</body>

当属性名不匹配时,使用param属性

<body>

<% request.setCharacterEncoding("utf-8"); %>

<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>

<jsp:setProperty property="name" name="student" param="userName"/>

<jsp:setProperty property="age" name="student" value="100"/>

<h1>姓名:<%=student.getName() %></h1>

<h1>年龄:<%=student.getAge() %></h1>

</body>

 

第四节:jsp:getProperty 获取javabean 属性值

<jsp:getProperty property="属性名称" name="实例化对象的名称"/>

<body>

<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>

<%

student.setName("王二小2");

student.setAge(12);

%>

<h1>姓名:<jsp:getProperty property="name" name="student"/></h1>

<h1>年龄:<jsp:getProperty property="age" name="student"/></h1>

</body>

 

第五节:javabean 的保存范围

Javabean 的保存范围有page,request,session.application,默认是page;

举例request范围:

<body>

<jsp:useBean id="student" scope="request" class="com.java1234.model.Student"/>

<jsp:setProperty property="name" name="student" value="王八蛋"/>

<jsp:setProperty property="age" name="student" value="12"/>

<jsp:forward page="target01.jsp"/>

</body>

//target01.jsp

<body>

<jsp:useBean id="student" scope="request" class="com.java1234.model.Student"/>

<h1>姓名:<jsp:getProperty property="name" name="student"/></h1>

<h1>年龄:<jsp:getProperty property="age" name="student"/></h1>

</body>

第六节:javabean 删除

page 范围:pageContext.removeAttribute(“javaBean Name”);

request 范围:request.removeAttribute(“javaBean Name”);

session 范围:session.removeAttribute(“javaBean Name”);

application 范围:application.removeAttribute(“javaBean Name”);

<body>

<jsp:useBean id="student" scope="session" class="com.java1234.model.Student"/>

<jsp:setProperty property="name" name="student" value="王八蛋"/>

<jsp:setProperty property="age" name="student" value="12"/>

<h1>Session数据设置完毕!</h1>

</body>

//javabeanDelete.jsp

<body>

<% session.removeAttribute("student"); %>

<h1>javabean已删除!</h1>

</body>

 

第五章Servlet 开发

第一节:问候servlet 他大爷

Web.xml配置servlet名称、映射等,此处略。

package com.java1234.web;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class HelloWorldServlet extends HttpServlet{

 

/**

*

*/

private static final long serialVersionUID = 1L;

 

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

System.out.println("get");

this.doPost(request, response);

}

 

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setCharacterEncoding("gbk");

PrintWriter out=response.getWriter();

out.println("<html>");

out.println("<head><title>问候大爷</title></head>");

out.println("Servlet大爷你好!");

out.println("</html>");

out.close();

}

 

}

第二节:servlet 生命周期

Servlet 的生命周期,简单的概括这就分为四步:servlet 类加载--->实例化--->服务--->销毁。

 

第三节:客户端跳转VS 服务器端跳转

1,在Servlet 中获取session,application

2,客户端跳转response.sendRedirect("目标地址");

//web.xml配置同上

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setAttribute("requestKey", "request值");

HttpSession session=request.getSession(); // 获取session

session.setAttribute("sessionKey", "session值");

ServletContext application=this.getServletContext(); // 获取application

application.setAttribute("applicationKey", "application值");

response.sendRedirect("target.jsp"); // 客户端跳转/重定向

}

//target.jsp

<body>

<h1>目标地址</h1>

request值:<%=request.getAttribute("requestKey") %><br/>

session值:<%=session.getAttribute("sessionKey") %><br/>

application值:<%=application.getAttribute("applicationKey") %><br/>

</body>

(sendRedirect重定向不携带request参数)

3,服务器跳转:RequestDispatcher rd=request.getRequestDispatcher("目标地址"); rd.forward(request, response);

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setAttribute("requestKey", "request值");

HttpSession session=request.getSession(); // 获取session

session.setAttribute("sessionKey", "session值");

ServletContext application=this.getServletContext(); // 获取application

application.setAttribute("applicationKey", "application值");

RequestDispatcher rd=request.getRequestDispatcher("target.jsp");

rd.forward(request, response); // 服务器跳转/转发

}

//target.jsp

<body>

<h1>目标地址</h1>

request值:<%=request.getAttribute("requestKey") %><br/>

session值:<%=session.getAttribute("sessionKey") %><br/>

application值:<%=application.getAttribute("applicationKey") %><br/>

</body>

(携带request参数)

第四节:Jsp&Servlet 用户登录功能实现

代码太多…

第五节:Servlet 过滤器

过滤用户(非法)请求

Web,xml配置filter,此处略。下面贴核心代码:

public class LoginFilter implements Filter {

 

@Override

public void destroy() {

// TODO Auto-generated method stub

 

}

 

@Override

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)

throws IOException, ServletException {

// TODO Auto-generated method stub

HttpServletRequest request=(HttpServletRequest)servletRequest;

HttpSession session=request.getSession();

Object o=session.getAttribute("currentUser");

String path=request.getServletPath(); //获取请求路径

if(o==null&&path.indexOf("login")<0){ // 排除登录请求的过滤

request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);

}else{

filterChain.doFilter(servletRequest, servletResponse);

}

}

 

@Override

public void init(FilterConfig arg0) throws ServletException {

// TODO Auto-generated method stub

 

}

}

 

第六节:Servlet 监听器

监听web 事件;如application,session,request

示例(session)

Web.xml配置

<listener>

<listener-class>com.java1234.listener.SessionAttributeListener</listener-class>

</listener>

 

// SessionAttributeListener.java

package com.java1234.listener;

 

import javax.servlet.http.HttpSessionAttributeListener;

import javax.servlet.http.HttpSessionBindingEvent;

 

public class SessionAttributeListener implements HttpSessionAttributeListener{

 

public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {

// TODO Auto-generated method stub

System.out.println("添加的属性名:"+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());

}

 

public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

// TODO Auto-generated method stub

System.out.println("删除的属性名:"+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());

}

 

public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

// TODO Auto-generated method stub

 

}

}
————————————————
版权声明:本文为CSDN博主「今天超市大减价」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40146789/article/details/96431276

推荐阅读