JSP--慕课网笔记

来源:互联网 发布:es java api 查询 编辑:程序博客网 时间:2024/06/02 06:04
第1章 JAVA WEB简介
1-1 什么是WEB应用程序

JavaWeb简介

  1. 什么是Web应用程序
  2. 静态页面与动态页面
  3. 搭建Java Web开发环境
  4. 手工编写第一个Web应用程序
  5. MyEclipse配置
  6. 使用MyEclipse编写第一个Web应用程序
  7. 修改Tomcat默认端口

什么是Web应用程序
Web应用程序是一种可以通过Web访问的应用程序。Web应用程序的一个最大好处是用户
很容易访问应用程序。用户只需要有浏览器即可,不需要在安装其他软件。

为什么要学习Web应用程序
我们说Web应用程序开发,是目前软件开发领域的三大方向之一。
JAVAEE方向需求一直是很大的,也是就业比较容易和稳定的。

软件领域三大方向

  • 桌面应用程序
  • Web应用程序
  • 嵌入式应用程序
1-2 静态网页与动态网页

静态网页与动态网页

  • 静态网页
    表现形式:网页中的内容是固定,不会更新
    所需技术:HTML、CSS
  • 动态网页
    表现形式:网页中的内容通过程序动态显示,自动更新。学习制作动态网页。
    所需技术:HTML、CSS,数据库技术,至少一门高级语言(Java、C#、Php),
    Javascript,XML等。主流的动态网页脚本技术(Jsp/Asp.net/Php)
1-3 练习题

关于静态网页与动态网页下说法错误的是( )。
动态网页上可以显示动态元素比如:动画,视频等,而静态网页无法显示动态元素

动态网页的内容一般是从数据库里面读取出来的
动态网页的内容的显示是通过程序来实现的
学习动态网页开发至少要掌握一门高级语言

动态网页的动态指的是能与用户进行交互,比如登录时输入正确的用户名和密码,系统会提示登录成功。

1-4 搭建JAVA WEB开发环境

工欲善其事必先利其器。学会搭建Java Web学习JSP动态网站开发的最基本技能之一。

  • JDK
  • Tomcat
  • MyEclipse

Tomcat服务器简介

  • Apache Jakarta的开源项目
  • JSP/Servlet容器

Tomcat安装与配置
安装Tomcat–>配置环境变量–>测试首页

CATALINA_HOME:Tomcat根目录

1-5 Tomcat目录结构

Tomcat服务器的目录结构

目录 说明 /bin 存放各种平台下用于启动和停止Tomcat的命令文件 /conf 存放Tomcat服务器的各种配置文件 /lib 存放Tomcat服务器所需的各种JAR文件 /logs 存放Tomcat的日志文件 /temp Tomcat运行时用于存放临时文件 webapps 当发布web应用时,默认会将web应用的文件发布到此目录 /work Tomcat把有JSP生成的Servlet放于此目录下
1-6 手工编写第一个Java Web程序

手工编写第一个Web程序

  1. 在WebApps创建项目目录
  2. 编写index.jsp
  3. 创建WEB-INF目录
  4. 测试运行
<html><head>    <title>第一个web应用</title></head><body>    第一个web应用</body></html>
1-7 WEB-INF目录详解

WEB-INF目录结构

  1. WEB-INF是Java的WEB应用的安全目录。所谓安全就是客户端无法访问,只有服务端可以访问的目录。
  2. web.xml,项目部署文件。
  3. classess文件夹,用于存放*.classess文件。
  4. lib文件夹,用于存放需要的jar包。
1-8 MyEclipse开发Java Web程序

MyEclipse
MyEclipse,是在eclipse基础上加上自己的插件开发而成的功能
强大的企业级集成开发环境,主要用于Java、Java EE以及移动应用
的开发。MyEclipse的功能非常强大,支持也十分广泛,尤其是对各种
开源产品的支持相当不错。

MyEclipse与Eclipse的区别

  • MyEclipse:收费,集成了很多收费的插件。比如:SSH,安卓等。
  • Eclipse:免费开源,不包含任何附加功能的插件。

MyEclipse配置JRE
windows->Preference->Java->Installed JREs

MyEclipse集成Tomcat服务器
windows->Preference->MyEclipse->Server->Tomcat

MyEclipse Web项目目录结构
项目名称
java源程序
类库
项目根目录
资源文件

1-9 理解Web项目虚拟路径

理解项目的虚拟路径
选择项目->属性->MyEclipse->Web->查看项目虚拟路径

1-10 Eclipse开发Java Web程序

Dynamic Web Project

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="ISO-8859-1"%><!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>Insert title here</title></head><body>hello world !</body></html>
1-11 修改Tomcat服务器默认端口号

修改conf/server.xml

<Connector port="8080" protocol="HTTP/1.1"               connectionTimeout="20000"               redirectPort="8443" />
1-12 练习题

修改Tomcat服务器默认端口号需要修改的配置文件是( )
server.xml

第2章 JSP基础语法
2-1 JSP简介
  1. Jsp简介
  2. 常用动态网站开发技术
  3. Jsp页面构成元素
  4. Jsp的生命周期
  5. 阶段项目

JSP全名为Java Server Pages,其根本是一个简化的Servlet设计,
他实现了在Java当中使用HTML标签。Jsp是一种动态网页技术标准也是
JAVAEE的标准。JSP与Servlet一样,是在服务器端执行的。

2-2 常见动态网站开发技术对比

常见动态网站开发技术对比

  • Jsp:Java平台,安全性高,适合开发大型的,企业级的Web应用程序
  • Asp.net:.Net平台,简单易学。但是安全性及跨平台性差。
  • Php:简单,高效,成本低开发周期短,特别适合中小型企业的Web应用开发。
    (LAMP:Linux+Apache+MySql+PHP)
2-3 JSP页面元素简介及page指令

JSP页面组成部分

  • 指令
  • 表达式
  • 小脚本
  • 声明
  • 注释
  • 静态内容

Jsp指令

  • page指令:通常位于jsp页面的顶端,同一个页面可以有多个page指令。
  • include指令:将一个外部文件嵌入到JSP文件中,同时解析这个页面中的JSP语句。
  • taglib指令:使用标签库定义新的自定义标签,在JSP页面中启用定制行为。

page指令语法
<%@ page 属性1=”属性值” 属性2=”属性值1,属性值2”…
属性n=”属性值n”%>

属性 描述 默认值 language 指定JSP页面使用的脚本语言 java import 通过该属性来引用脚本语言中使用到的类文件 无 contentType 用来指定JSP页面所采用的编码方式 text/html,ISO-8859-1
2-4 练习题

以下哪个不属于JSP的三大指令元素( )
import

include
page
taglib

2-5 JSP注释

在JSP页面的注释

  • HTML的注释: 客户端可见
  • JSP的注释:<%– html注释 –> 客户端不可见
  • JSP脚本注释://当行注释 /**/多行注释 客户端不可见
2-6 练习题

以下哪个注释是客户端无法查看到的注释( )
<%– 这里是注释–%>

2-7 JSP脚本

在JSP页面中执行的java代码
语法:
<% Java代码 %>

<%    out.println("大家好!");%>
2-8 JSP声明

在JSP页面中定义变量或者方法。
语法:
<%! Java代码 %>

<%!     String s = "张三";    int add(int a,int b){        return a+b;    }%>
2-9 JSP表达式

在JSP页面中执行的表达式。
语法:
<%= 表达式 %> //注意:表达式不以分号结尾

<p>你好,<%= s %></p><p>1+1= <%= add(1,1) %></p>
2-10 JSP页面生命周期
Created with Raphaël 2.1.0用户发出请求index.jsp是否是第一次请求?JSP引擎把该JSP文件转换成为一个Servlet,生成字节码文件,并执行jspInit()生成的字节码文件解析执行,jspService()yesno

jspservice()方法被调用来处理客户端的请求。对每一个请求,JSP引擎创建
一个新的线程来处理该请求。如果有多个客户端同时请求该JSP文件,则JSP
引擎会创建多个线程。每个客户端请求对应一个线程。以多线程方式执行可以
大大降低对系统资源的需求,提高系统的并发量及响应时间。但是也要注意多线
程的编程带来的同步问题,由于该Servlet始终驻留在内存,所以相应是非常快的。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="java.text.*" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>JSP生命周期</h1>    <hr>    <%        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");        String s = sdf.format(new Date());    %>    今天是:<%= s %>  </body></html>
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase    implements org.apache.jasper.runtime.JspSourceDependent {  private static final javax.servlet.jsp.JspFactory _jspxFactory =          javax.servlet.jsp.JspFactory.getDefaultFactory();  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;  private javax.el.ExpressionFactory _el_expressionfactory;  private org.apache.tomcat.InstanceManager _jsp_instancemanager;  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {    return _jspx_dependants;  }  public void _jspInit() {    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());  }  public void _jspDestroy() {  }  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)        throws java.io.IOException, javax.servlet.ServletException {    final javax.servlet.jsp.PageContext pageContext;    javax.servlet.http.HttpSession session = null;    final javax.servlet.ServletContext application;    final javax.servlet.ServletConfig config;    javax.servlet.jsp.JspWriter out = null;    final java.lang.Object page = this;    javax.servlet.jsp.JspWriter _jspx_out = null;    javax.servlet.jsp.PageContext _jspx_page_context = null;    try {      response.setContentType("text/html; charset=utf-8");      pageContext = _jspxFactory.getPageContext(this, request, response,                null, true, 8192, true);      _jspx_page_context = pageContext;      application = pageContext.getServletContext();      config = pageContext.getServletConfig();      session = pageContext.getSession();      out = pageContext.getOut();      _jspx_out = out;      out.write("\r\n");      out.write("\r\n");String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";      out.write("\r\n");      out.write("\r\n");      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");      out.write("<html>\r\n");      out.write("  <head>\r\n");      out.write("    <base href=\"");      out.print(basePath);      out.write("\">\r\n");      out.write("    \r\n");      out.write("    <title>My JSP 'index.jsp' starting page</title>\r\n");      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");      out.write("\t<!--\r\n");      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");      out.write("\t-->\r\n");      out.write("  </head>\r\n");      out.write("  \r\n");      out.write("  <body>\r\n");      out.write("   \t<h1>JSP生命周期</h1>\r\n");      out.write("   \t<hr>\r\n");      out.write("   \t");        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");        String s = sdf.format(new Date());      out.write("\r\n");      out.write("   \t今天是:");      out.print( s );      out.write("\r\n");      out.write("  </body>\r\n");      out.write("</html>\r\n");    } catch (java.lang.Throwable t) {      if (!(t instanceof javax.servlet.jsp.SkipPageException)){        out = _jspx_out;        if (out != null && out.getBufferSize() != 0)          try {            if (response.isCommitted()) {              out.flush();            } else {              out.clearBuffer();            }          } catch (java.io.IOException e) {}        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);        else throw new ServletException(t);      }    } finally {      _jspxFactory.releasePageContext(_jspx_page_context);    }  }}
2-11 练习题

当用户第一次请求一个jsp页面时,首先被执行的方法是( )
构造方法

jspInit()
jspService()
jspDestroy()

第一次请求一个jsp页面时,首先被执行的方法是构造方法

2-12 阶段项目
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>   <%!        String printMultiTable1()        {            String s = "";            for(int i=1;i<=9;i++){                for(int j=1;j<=i;j++){                    s += i + "*" + j + "=" +(i*j)+"&nbsp;&nbsp;&nbsp;&nbsp;";                }                s += "<br>";            }            return s;        }        void printMultiTable2(JspWriter out) throws Exception        {            for(int i=1;i<=9;i++){                for(int j=1;j<=i;j++){                    out.println( i + "*" + j + "=" +(i*j)+"&nbsp;&nbsp;&nbsp;&nbsp;");                }                out.println("<br>");            }        }   %>    <h1>九九乘法表</h1>    <hr>    <%= printMultiTable1() %>    <br>    <% printMultiTable2(out); %>  </body></html>
第3章 JSP内置对象(上)
3-1 JSP内置对象简介
  1. 内置对象简介
  2. 四种作用域范围
  3. out
  4. request/response
  5. session
  6. application
  7. 其他内置对象
  8. 项目案例

JSP内置对象是Web容器创建的一组对象,不使用new关键字就可以使用的内置对象。

int[] value = {60,70,80};  for(int i:value){      out.println(i);  }

九大内置对象

  • out
  • request
  • response
  • session
  • application
  • Page
  • pageContext
  • exception
  • config
3-2 练习题

以下哪个不属于jsp九大内置对象( )
pageConfig

exception
page
pageContext

3-3 web程序的请求与响应模式

Web程序的请求响应模式
用户发送请求(request)
服务器给用户相应(response)

3-4 out对象

什么是缓冲区
缓冲区:Buffer,所谓缓冲区就是内存中的一块区域用来保存临时数据。

IO输出最原始的就是一个字节一个字节输出,就像一粒一粒吃一样,但效率太差。

刚煮好的米饭一粒一粒吃不知道要猴年马月。。。把米饭放到碗里,一碗一碗吃岂不痛快!

out对象是JspWriter类的实例,是向客户端输出内容的常用对象。
常用方法如下:

  • void println() 向客户端打印字符串
  • void clear() 清除缓冲区的内容,如果在flush之后调用会抛出异常
  • void clearBuffer() 清除缓冲区的内容,如果在flush之后调不用会抛出异常
  • void flush() 将缓冲区内容输出到客户端
  • int getBufferSize() 返回缓存区以字节数的大小,如不设缓冲区则为0
  • int getRemaining() 返回缓冲区还剩余多少可用
  • boolean isAutoFlush() 返回缓冲区满时,是自动清空还是抛出异常
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>out内置对象</h1>    <%        out.println("<h2>静夜思</h2>");       out.println("床前明月光<br>");       out.println("疑是地上霜<br>");       out.flush();       //out.clear();//这里会抛出异常。       out.clearBuffer();//这里不会抛出异常。       out.println("举头望明月<br>");       out.println("低头思故乡<br>");    %>        缓冲区大小:<%=out.getBufferSize() %>byte<br>        缓冲区剩余大小:<%=out.getRemaining() %>byte<br>       是否自动清空缓冲区:<%=out.isAutoFlush() %><BR>      </body></html>
3-5 练习题

执行以下jsp脚本输出效果是( )

<% out.println("床前明月光"); out.flush(); out.clear(); out.println("疑是地上霜");%>

在浏览器中只输出床前明月光

在浏览器中输出“床前明月光”,控制台会输出异常信息。

3-6 get与post提交方式的区别

get与post区别

表单有两种提交方式:get与post

  • get:以明文的方式通过URL提交数据,数据在URL中可以看到。提交数据
    量最多不超过2KB。安全性较低但效率比post方式高。适合提交数据量不大,
    安全性不高的数据。比如:搜索、查询等功能。
  • post:将用户提交的信息封装在HTML HEADER内。适合提交数据量大,安全
    性高的用户信息。比如:注册、修改、上传等功能。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>用户登录</h1>    <hr>    <form action="dologin.jsp" name="loginForm" method="post">     <table>       <tr>         <td>用户名:</td>         <td><input type="text" name="username"/></td>       </tr>       <tr>         <td>密码:</td>         <td><input type="password" name="password"/></td>       </tr>       <tr>         <td colspan="2"><input  type="submit" value="登录"></td>       </tr>     </table>    </form>  </body></html>
3-7 request对象(上)

request对象
客户端的请求信息被封装在request对象中,通过它才能了解到客户的请求,然后
响应。它是HttpServletRequest类的实例。request对象具有请求域,即完成客户端
请求之前,该对象一直有效。常用方法如下:

  • String getParameter(String name) 返回name指定参数的参数值
  • String[] getParameterValues(String name) 返回包含参数name的所有值的数组
  • void setAttribute(String,Object) 存储此请求中的属性
  • object getAttribute(String name) 返回指定属性的属性值
  • String getContentType() 得到请求体的MIME类型
  • String getProtocol() 返回请求用的协议类型及版本号
  • String getServerName() 返回接受请求的服务器主机名
3-8 request对象(下)
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>用户注册</h1>    <hr>    <%        int number=-1;       //说明用户第一次访问页面,计数器对象还未创建       if(application.getAttribute("counter")==null)       {           application.setAttribute("counter", 0);       }       number = Integer.parseInt(application.getAttribute("counter").toString());       number++;       application.setAttribute("counter", number);    %>    <!-- <form name="regForm" action="request.jsp" method="post"> -->    <form name="regForm" action="response.jsp" method="post">    <table>      <tr>        <td>用户名:</td>        <td><input type="text" name="username"/></td>      </tr>      <tr>        <td>爱好:</td>        <td>           <input type="checkbox" name="favorite" value="read">读书           <input type="checkbox" name="favorite" value="music">音乐           <input type="checkbox" name="favorite" value="movie">电影           <input type="checkbox" name="favorite" value="internet">上网        </td>      </tr>      <tr>         <td colspan="2"><input type="submit" value="提交"/></td>      </tr>    </table>    </form>    <br>    <br>    <a href="request.jsp?username=李四">测试URL传参数</a>    <br>    <br>    <center>             您是第<%=number %>位访问本页面的用户。    </center>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>request内置对象</h1>    <%        request.setCharacterEncoding("utf-8"); //解决中文乱码问题,无法解决URL传递中文出现的乱码问题。       request.setAttribute("password", "123456");    %>        用户名:<%=request.getParameter("username") %><br>           爱好 :<%            if(request.getParameterValues("favorite")!=null)           {               String[] favorites = request.getParameterValues("favorite");               for(int i=0;i<favorites.length;i++)               {                  out.println(favorites[i]+"&nbsp;&nbsp;");               }            }        %> <br>         密码:<%=request.getAttribute("password") %><br>          请求体的MIME类型:<%=request.getContentType() %><br>         协议类型及版本号:  <%=request.getProtocol() %><br>         服务器主机名 :<%=request.getServerName() %><br>         服务器端口号:<%=request.getServerPort() %><BR>         请求文件的长度 :<%=request.getContentLength() %><BR>         请求客户端的IP地址:<%=request.getRemoteAddr() %><BR>         请求的真实路径:<%=request.getRealPath("request.jsp") %><br>         请求的上下文路径:<%=request.getContextPath() %><BR>           </body></html>
3-9 练习题

在用户注册表单中,用户的爱好信息用复选框表示,包括读书、音乐、电影和上网四项。如果已经选中读书和电影两项,此时要获取用户的爱好信息,使用request对象的哪个方法实现( )
request.getParameterValues(“favorite”);

3-10 response对象

response对象
response对象包含了响应客户请求的有关信息,但在JSP中很少直接用到它。它是
HttpServetResponse类的实例。response对象具有页面作用域,即访问一个页面时
该页面内的response对象只能对这次访问有效,其它页面的response对象对当前页面无效。
常用方法如下:

  • String getCharacterEncoding() 返回响应是用的何种字符编码
  • void setContentType(String type) 设置响应的MIME类型
  • PrintWriter getWriter() 返回可以向客户端输出字符的一个对象(注意比较:
    PrintWriter与内置对象out对象的区别)
  • sendRedirect(String location) 重新定向客户端的请求
<%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%><%    response.setContentType("text/html;charset=utf-8"); //设置响应的MIMI类型    out.println("<h1>response内置对象</h1>");    out.println("<hr>");    //out.flush();    PrintWriter outer = response.getWriter(); //获得输出流对象    outer.println("大家好,我是response对象生成的输出流outer对象");    //response.sendRedirect("reg.jsp");//请求重定向%>
3-11 请求重定向与请求转发的区别

请求转发与请求重定向

  • 请求重定向:客户端行为,response.sendRedirect(),从本质上讲等同于两次请求,
    前一次的请求对象不会保存,地址栏的URL地址会改变。
  • 请求转发:服务器行为,request.getRequestDispatcher().forward(req,resp)是
    一次请求,转发后请求对象会保存,地址栏的URL地址不会改变。

假设你去办理某个护照
重定向:你先去了A局,A局的人说:“这个事不归我管,去B局”,然后,你就从A局
退了出来,自己乘车去了B局。
转发:你去了A局,A局看了以后,知道这个事情其实应该B局来管,但是他没有把
你退回来,而是让你坐一会儿,自己到后面办公室联系了B的人,让他们办好后,送了
过来。

<%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%><%    response.setContentType("text/html;charset=utf-8"); //设置响应的MIMI类型    out.println("<h1>response内置对象</h1>");    out.println("<hr>");    //out.flush();    PrintWriter outer = response.getWriter(); //获得输出流对象    outer.println("大家好,我是response对象生成的输出流outer对象");    //response.sendRedirect("reg.jsp");//请求重定向    //请求重定向    //response.sendRedirect("request.jsp");    //请求转发    request.getRequestDispatcher("request.jsp").forward(request, response);%>
3-12 练习题

关于请求重定向与请求转发的区别以下说法不正确的是( )
请求重定向是服务器端行为而请求转发是客户端行为

请求重定向相当于两次请求,地址栏地址会发生变化
重定向是response对象的方法而请求转发是request对象的方法
请求重定向不会保存原有request对象而请求转发会保存原有request对象

第4章 JSP内置对象(下)
4-1 什么是session

什么是session

  • session表示客户端与服务器的一次会话
  • Web中的session指的是用户在浏览某个网站时,从进入网站到浏览器关闭所经过的这段
    时间,也就是用户浏览这个网站所花的时间
  • 从上述定义中可以看到,session实际上是一个特定的时间概念

购物流程说明
用户登录-》放入购物车-》订单填写-》提交订单-》确认订单-》立即付款

整个购物过程属于一次会话

在服务器的内存中保存着不同用户的session。

4-2 session对象

session对象

  • session对象是一个JSP内置对象。
  • session对象在第一个JSP页面被加载时自动创建,完成会话期管理。
  • 从一个客户打开浏览器并连接到服务器开始,到客户关闭浏览器离开这个服务器结束被
    称为一个会话。
  • 当一个客户访问一个服务器时,可能会在服务器之间的几个页面切换,服务器应该通过
    某种办法知道这是一个客户,就需要session对象。
  • session对象是HttpSession类的实例。

session对象常用方法如下:

long getCreationTime():返回SESSION创建时间
public String getId():返回SESSION创建时JSP引擎为它设置的唯一ID号
public Object setAttribute(String name,Object value):使用指定名称将对象绑定到此会话
public Object getAttribute(String name):返回与此会话中的指定名称绑定在一起的对象,如果没有对象绑定在该名称下,则返回null
String[] getValueNames():返回一个包含SESSION中所有可用属性的数组
int getMaxInactiveInterval():返回两次请求间隔多长时间此SESSION被取消(单位秒)

<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>session内置对象</h1>    <hr>    <%       SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");      Date d = new Date(session.getCreationTime());      session.setAttribute("username", "admin");       session.setAttribute("password", "123456");      session.setAttribute("age", 20);      //设置当前session最大生成期限单位是秒      //session.setMaxInactiveInterval(10);//10秒钟    %>    Session创建时间:<%=sdf.format(d)%><br>        Session的ID编号:<%=session.getId()%><BR>         从Session中获取用户名:<%=session.getAttribute("username") %><br>    <a href="session_page2.jsp" target="_blank">跳转到Session_page2.jsp</a>       </body></html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>session内置对象</h1>    <hr>    <%       //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");      //Date d = new Date(session.getCreationTime());      //session.setAttribute("username", "admin");     %>    Session的ID编号:<%=session.getId()%><BR>         从Session中获取用户名:<%=session.getAttribute("username") %><br>    Session中保存的属性有:<%                      String[] names =session.getValueNames();                     for(int i=0;i<names.length;i++)                     {                        out.println(names[i]+"&nbsp;&nbsp;");                     }    %> <br>      </body></html>
4-3 练习题

下面有关会话(session)描述不正确的是( )。
会话保存在客户端的内存里

会话是用来保存用户状态的一种机制
会话保存在服务器的内存里
每一个会话对应一个唯一的sessionId

4-4 session的生命周期

session的生命周期

  • 创建
    当客户端第一次访问某个jsp或者Servlet时候,服务器将会为当前会话创建一个
    SessionId,每次客户端向服务器发送请求时,都会将此SessionId携带过去,服务端
    会对此SessionId进行校验。
  • 活动
    • 当某次会话当中通过超链接打开新的页面属于同一会话。
    • 只要当前会话页面没有完全关闭,重新打开新的浏览器窗口访问统一项目
      资源时属于同一会话。
    • 除非本次会话的所有页面都关闭后再重新访问某个Jsp或者Servlet将会创建
      新的会话。
      注意事项:注意原有会话还存在,只是这个旧的SessionId仍然存在于服务端,
      只是在有没有客户端会携带它交与服务端进行校验。
  • 销毁
    • 调用了session.invalidate()方法
    • Session过期(超时)
    • 服务器重新启动
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>session内置对象</h1>    <hr>    <%       SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");      Date d = new Date(session.getCreationTime());      session.setAttribute("username", "admin");       session.setAttribute("password", "123456");      session.setAttribute("age", 20);      //设置当前session最大生成期限单位是秒      //session.setMaxInactiveInterval(10);//10秒钟      //session.invalidate();//销毁当前会话。    %>    Session创建时间:<%=sdf.format(d)%><br>        Session的ID编号:<%=session.getId()%><BR>         从Session中获取用户名:<%=session.getAttribute("username") %><br>    <%        //session.invalidate();//销毁当前会话    %>    <a href="session_page2.jsp" target="_blank">跳转到Session_page2.jsp</a>       </body></html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>session内置对象</h1>    <hr>    <%       //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");      //Date d = new Date(session.getCreationTime());      //session.setAttribute("username", "admin");     %>    Session的ID编号:<%=session.getId()%><BR>         从Session中获取用户名:<%=session.getAttribute("username") %><br>    Session中保存的属性有:<%                      String[] names =session.getValueNames();                     for(int i=0;i<names.length;i++)                     {                        out.println(names[i]+"&nbsp;&nbsp;");                     }    %> <br>      </body></html>
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>   <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <!-- 设置会话一分钟后过期 -->  <session-config>    <session-timeout>1</session-timeout>  </session-config></web-app>
4-5 练习题

有关session生命周期下列说法不正确的是( )。
每次重新打开新的浏览器窗口相当于开启了一次新的会话

session的生命周期分为创建、活动、销毁三个阶段
调用session.invalidate()方法可以销毁当前会话
重启web服务器会销毁所有的会话

4-6 application对象
  • application对象实现了用户数据的共享,可存放全局变量。
  • application开始于服务器的启动,终止与服务器的关闭
  • 在用户的前后连接或不同用户的连接中,可以对application对象的同一属性进行操作。
  • 在任何地方对application对象的操作,都会影响到其他用户的访问。
  • 服务器的启动和关闭觉得了application对象的生命。
  • application对象是ServletContext类的实例。

常用方法如下:

  • public void setAttribute(String name,Object value) 使用指定名称将对象绑定到此会话。
  • public Object getAttribute(String name) 返回与此会话中指定名称绑定在一起的对象,如果没有对象绑定在该名称下,则返回null。
  • Enumeration getAttributeNames() 返回所有可用属性的枚举。
  • String getServerInfo() 返回JSP(SERVLET)引擎名及版本号。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>application内置对象</h1>    <%        application.setAttribute("city", "北京");       application.setAttribute("postcode", "10000");       application.setAttribute("email", "lisi@126.com");    %>         所在城市是:<%=application.getAttribute("city") %><br>    application中的属性有:<%          Enumeration attributes = application.getAttributeNames();         while(attributes.hasMoreElements())         {            out.println(attributes.nextElement()+"&nbsp;&nbsp;");         }    %><br>    JSP(SERVLET)引擎名及版本号:<%=application.getServerInfo() %><br>                </body></html>
4-7 练习题

使用application 实现计数器效果,在application中保存整型变量num,需要调用application对象的setAttribute方法,以下选项正确的是( )。
setAttribute(”counter”,num);

4-8 page对象

page对象是指向当前JSP页面本身,有点像类中的this指针,它是java.lang.Object类的实例。
常用方法如下:

  • class getClass() 返回此Object的类
  • int hashCode() 返回此Object的hash码
  • boolean equals(Object obj) 判断此Object是否与指针的Object对象相等
  • void copy(Object obj) 把此Object拷贝到指定的Object对象中
  • Object clone() 克隆此Object对象
  • String toString() 把此Object对象转换成String类的对象
  • void notify() 唤醒一个等待的线程
  • void notifyAll() 唤醒所有等待的线程
  • void wait(int timeout) 使一个线程处于等待直到timeout结束或被唤醒
  • void wait() 使一个线程处于等待直到被唤醒
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>page内置对象</h1>         当前page页面对象的字符串描述:<%=page.toString() %><br>   </body></html>
4-9 pageContext对象和config对象

pageContext对象

  • pageContext对象提供了对JSP页面所有的对象及名字空间的访问
  • pageContext对象可以访问到本页所在的session,也可以取本页面所在的application的某一值
  • pageContext对象相当于页面中所有功能集大成者
  • pageContext对象本类名也叫pageContext

常用方法:

  • JspWriter getOut() 返回当前客户端响应被使用的JspWriter流(out)。
  • HttpSession getSession() 返回当前页面中HttpSession对象(session)。
  • Object getPage() 返回当前页面Object对象(page)。
  • ServletRequest getRequest() 返回当前页面的ServletRequest对象(request)。
  • ServletResponse getResponse() 返回当前页面的ServletResponse对象(response)。
  • void setAttribute(String name,Object attribute) 设置属性及属性值
  • Object getAttribute(String name,int scope) 在指定范围内取属性的值
  • int getAttributeScope(String name) 返回某属性的作用范围
  • void forward(String relativeUrlPath) 使当前页面重导到另一页面
  • void include(String relativeUrlPath) 在当前位置包含另一文件
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>pageContext内置对象</h1>    <hr>            用户名是:<%=pageContext.getSession().getAttribute("username") %><br>          <%        //跳转到注册页面       //pageContext.forward("reg.jsp");       pageContext.include("include.jsp");    %>                  </body></html>

Config对象
config对象实在一个Servlet初始化时,JSP引擎向它传递信息用的,此信息包括
Servlet初始化时要用到的参数(通过属性名和属性值构成)以及服务器的有关信息
(通过传递一个ServletContext对象),常用方法如下:

  • ServletContext getServletContext() 返回含有服务器相关信息的ServletContext对象。
  • String getInitParamter(name) 返回初始化参数的值。
  • Enumeration getInitParamterNames() 返回Servlet初始化所需所有参数的枚举。
4-10 exception对象

exception对象是一个异常对象,当一个页面在运行过程中发生了异常,就产生
这个对象。如果一个JSP页面要应用此对象,就必须把isErrorPage设置为true,
否则无法编译。他实际上是java.lang.Throwable的对象,常用方法如下:

  • String getMessage() 返回描述异常的消息。
  • String toString() 返回关于异常的简短描述消息。
  • void printStackTrace() 显示异常及其栈轨迹
  • Throwable FillInStackTrace() 重写异常的执行栈轨迹
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" errorPage="exception.jsp"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>测试异常的页面</h1>    <hr>    <%       System.out.println(100/0); //抛出运行时异常,算数异常    %>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" isErrorPage="true" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>exception内置对象</h1>    <hr>        异常的消息是:<%=exception.getMessage()%><BR>        异常的字符串描述:<%=exception.toString()%><br>  </body></html>
4-11 阶段案例——实现用户登录

实现用户登录小例子
用户名admin,密码admin,登录成功使服务器内部转发到login_success.jsp页面,
并且提示登陆成功的用户名。如果登陆失败则重定向到login_failure.jsp页面。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  String username ="";  String password ="";  request.setCharacterEncoding("utf-8");//防止中文乱码  username = request.getParameter("username");  password = request.getParameter("password");  //如果用户和密码都等于admin,则登录成功  if("admin".equals(username)&&"admin".equals(password))  {     session.setAttribute("loginUser", username);     request.getRequestDispatcher("login_success.jsp").forward(request, response);  }  else  {     response.sendRedirect("login_failure.jsp");  }%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>    <head>        <!-- Page title -->        <title>imooc - Login</title>        <!-- End of Page title -->        <!-- Libraries -->        <link type="text/css" href="css/login.css" rel="stylesheet" />          <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>        <script type="text/javascript" src="js/easyTooltip.js"></script>        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>        <!-- End of Libraries -->       </head>    <body>    <div id="container">        <div class="logo">            <a href="#"><img src="assets/logo.png" alt="" /></a>        </div>        <div id="box">             登录失败!请检查用户或者密码!<br>          <a href="login.jsp">返回登录</a>           </div>    </div>    </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>    <head>        <!-- Page title -->        <title>imooc - Login</title>        <!-- End of Page title -->        <!-- Libraries -->        <link type="text/css" href="css/login.css" rel="stylesheet" />          <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>        <script type="text/javascript" src="js/easyTooltip.js"></script>        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>        <!-- End of Libraries -->       </head>    <body>    <div id="container">        <div class="logo">            <a href="#"><img src="assets/logo.png" alt="" /></a>        </div>        <div id="box">          <%              String loginUser = "";             if(session.getAttribute("loginUser")!=null)             {                loginUser = session.getAttribute("loginUser").toString();             }          %>             欢迎您<font color="red"><%=loginUser%></font>,登录成功!        </div>    </div>    </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>    <head>        <!-- Page title -->        <title>imooc - Login</title>        <!-- End of Page title -->        <!-- Libraries -->        <link type="text/css" href="css/login.css" rel="stylesheet" />          <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>        <script type="text/javascript" src="js/easyTooltip.js"></script>        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>        <!-- End of Libraries -->       </head>    <body>    <div id="container">        <div class="logo">            <a href="#"><img src="assets/logo.png" alt="" /></a>        </div>        <div id="box">            <form action="dologin.jsp" method="post">            <p class="main">                <label>用户名: </label>                <input name="username" value="" />                 <label>密码: </label>                <input type="password" name="password" value="">                </p>            <p class="space">                <input type="submit" value="登录" class="login" style="cursor: pointer;"/>            </p>            </form>        </div>    </div>    </body></html>
第5章 JavaBeans
5-1 本章简介
  • Javabean简介
  • Javabean设计原则
  • Jsp中如何使用Javabean
  • Javabean的四个作用域范围
  • Model1简介
  • 项目案例
5-2 JavaBean简介及设计原则

Javabean简介
Javabeans就是符合某种特定规范的Java类。使用Javabeans的好处是
解决代码重复编写,减少代码冗余,功能区分明确,提高了代码的维护性。

Javabean设计原则

  • 公有类
  • 无参公有构造方法
  • 私有属性
  • getter和setter方法
public class Students {    private String name;    private int age;    public Students(){}    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}
5-3 什么是JSP动作元素

JSP动作元素(action elements),动作元素为请求处理阶段提供信息。动作
元素遵循XML元素的语法,有一个包含元素名的开始标签,可以有属性、可选
内容、与开始标签匹配的结束标签。

  • 第一类是与存取Javabean有关的,包括:
  • 第二类是从JSP1.2就开始有的基本元素,包括6个动作元素
  • 第三类是JSP2.0新增加的元素,主要与JSP Document有关,包括六个元素
  • 第四类是JSP2.0新增加的动作元素,主要用来动态生成XML元素标签的值,包括3个动作
  • 第五类是JSP2.0新增的动作元素,主要是用在Tag File中,有2个元素
5-4 使用普通方式创建JavaBean
  • 像使用普通java类一样,创建javabean实例。
/* * 用户类 * */public class Users {    private String username;//用户名    private String password;//密码    //保留此默认的构造方法    public Users()    {    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="com.po.Users" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <%        Users user = new Users();       user.setUsername("admin"); //设置用户名       user.setPassword("123456");//设置密码    %>    <h1>使用普通方式创建javabean的实例</h1>    <hr>       用户名:<%=user.getUsername() %><br>       密码:<%=user.getPassword() %><br>  </body></html>
5-5 useBean动作元素
  • 在Jsp页面通常使用jsp动作标签来使用Javabean。
    • useBeans动作
    • setProperty动作
    • getProperty动作


作用:在Jsp页面中实例化或者在指定范围内使用javabean:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>    <h1>使用useBean动作创建javabean的实例</h1>    <hr>       用户名:<%=myUsers.getUsername() %><br>       密码:<%=myUsers.getPassword() %><br>  </body></html>
5-6 setProperty

作用:给已经实例化的Javabean对象的属性赋值,一共有四种形式。

(跟表单关联)
(跟表单关联)
(手工设置)
(跟request参数关联)

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'dologin.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>    <h1>setProperty动作元素</h1>    <hr>   <!--根据表单自动匹配所有的属性 -->   <%--    <jsp:setProperty name="myUsers" property="*"/>     --%>   <!--根据表单匹配所有部分的属性 -->   <%--    <jsp:setProperty name="myUsers" property="username"/>     --%>   <!--根表单无关,通过手工赋值给属性 -->   <%--    <jsp:setProperty name="myUsers" property="username" value="lisi"/>   <jsp:setProperty name="myUsers" property="password" value="888888"/>   --%>   <!--通过URL传参数给属性赋值 -->   <jsp:setProperty name="myUsers" property="username"/>   <jsp:setProperty name="myUsers" property="password" param="mypass"/>   <!-- 使用getProperty方式来获取用户名和密码 -->      用户名:<jsp:getProperty name="myUsers" property="username"/> <br>      密码:<jsp:getProperty name="myUsers" property="password"/><br>   <br>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>系统登录</h1>    <hr>    <form name="loginForm" action="dologin.jsp?mypass=999999" method="post">      <table>        <tr>          <td>用户名:</td>          <td><input type="text" name="username" value=""/></td>        </tr>        <tr>          <td>密码:</td>          <td><input type="password" name="password" value=""/></td>        </tr>        <tr>          <td colspan="2" align="center"><input type="submit" value="登录"/></td>        </tr>      </table>    </form>  </body></html>
5-7 getProperty

作用:获取指定Javabean对象的属性值。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'dologin.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>    <h1>setProperty动作元素</h1>    <hr>   <!--根据表单自动匹配所有的属性 -->   <%--    <jsp:setProperty name="myUsers" property="*"/>     --%>   <!--根据表单匹配所有部分的属性 -->   <%--    <jsp:setProperty name="myUsers" property="username"/>     --%>   <!--根表单无关,通过手工赋值给属性 -->   <%--    <jsp:setProperty name="myUsers" property="username" value="lisi"/>   <jsp:setProperty name="myUsers" property="password" value="888888"/>   --%>   <!--通过URL传参数给属性赋值 -->   <jsp:setProperty name="myUsers" property="username"/>   <jsp:setProperty name="myUsers" property="password" param="mypass"/>   <!-- 使用传统的表达式方式来获取用户名和密码 -->   <%--            用户名:<%=myUsers.getUsername() %><br>       密码:<%=myUsers.getPassword() %><br>    --%>   <!-- 使用getProperty方式来获取用户名和密码 -->      用户名:<jsp:getProperty name="myUsers" property="username"/> <br>      密码:<jsp:getProperty name="myUsers" property="password"/><br>  </body></html>
5-8 JavaBean四个作用域范围

Javabean的四个作用域范围

说明:使用useBeans的scope属性可以用来指定javabean的作用范围

  • page //仅在当前页面有效
  • request //可以通过HttpRequest.getAttribute()方法取得JavaBean对象
  • session //可以通过HttpSession.getAttribute()方法获得JavaBean对象
  • application //可以通过application.getAttribute方法获得JavaBean对象
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>系统登录</h1>    <hr>    <form name="loginForm" action="dologin.jsp?mypass=999999" method="post">      <table>        <tr>          <td>用户名:</td>          <td><input type="text" name="username" value=""/></td>        </tr>        <tr>          <td>密码:</td>          <td><input type="password" name="password" value=""/></td>        </tr>        <tr>          <td colspan="2" align="center"><input type="submit" value="登录"/></td>        </tr>      </table>    </form>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'dologin.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>    <h1>setProperty动作元素</h1>    <hr>   <!--根据表单自动匹配所有的属性 -->   <%--    <jsp:setProperty name="myUsers" property="*"/>     --%>   <!--根据表单匹配所有部分的属性 -->   <%--    <jsp:setProperty name="myUsers" property="username"/>     --%>   <!--根表单无关,通过手工赋值给属性 -->   <%--    <jsp:setProperty name="myUsers" property="username" value="lisi"/>   <jsp:setProperty name="myUsers" property="password" value="888888"/>   --%>   <!--通过URL传参数给属性赋值 -->   <jsp:setProperty name="myUsers" property="username"/>   <jsp:setProperty name="myUsers" property="password" param="mypass"/>   <!-- 使用传统的表达式方式来获取用户名和密码 -->   <%--            用户名:<%=myUsers.getUsername() %><br>       密码:<%=myUsers.getPassword() %><br>    --%>   <!-- 使用getProperty方式来获取用户名和密码 -->      用户名:<jsp:getProperty name="myUsers" property="username"/> <br>      密码:<jsp:getProperty name="myUsers" property="password"/><br>   <br>   <br>      <a href="testScope.jsp">测试javabean的四个作用域范围</a>      <%          request.getRequestDispatcher("testScope.jsp").forward(request, response);      %>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="com.po.Users" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'testScope.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>Javabean的四个作用域范围</h1>    <hr>    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>       用户名:<jsp:getProperty name="myUsers" property="username"/><br>       密码:<jsp:getProperty name="myUsers" property="password"/><br>    <!-- 使用内置对象获取用户名和密码 -->    <hr>   <%--        用户名:<%=((Users)application.getAttribute("myUsers")).getUsername()%><br>       密码:<%=((Users)application.getAttribute("myUsers")).getPassword() %><br>   --%>   <%--        用户名:<%=((Users)session.getAttribute("myUsers")).getUsername()%><br>       密码:<%=((Users)session.getAttribute("myUsers")).getPassword() %><br>   --%>   <%--        用户名:<%=((Users)request.getAttribute("myUsers")).getUsername()%><br>       密码:<%=((Users)request.getAttribute("myUsers")).getPassword() %><br>   --%>   <%        String username = "";       String password = "";       if(pageContext.getAttribute("myUsers")!=null )       {          username = ((Users)pageContext.getAttribute("myUsers")).getUsername();          password = ((Users)pageContext.getAttribute("myUsers")).getPassword();       }   %>       用户名:<%=username%><br>       密码:<%=password%><br>  </body></html>
5-9 练习题

在Java Web 应用程序的jsp页面中有如下一行代码: 要使user对象可以作用于整个Web应用,下划线中应填入( )。
application

5-10 Model1简介

Model 1模型出现前,整个Web应用的情况:几乎全部由JSP页面
组成,JSP页面接受处理客户端请求,对请求处理后直接做出响应。

弊端:在界面层充斥着大量业务逻辑的代码和数据访问层的代码,
Web程序的可扩展性和可维护性非常差。

javabean的出项可以使jsp页面中使用Javabean封装的
数据或者调用Javabean的业务逻辑代码,这样大大提升
了程序的可维护性。

Created with Raphaël 2.1.0浏览器浏览器jspjspjavabeanjavabean数据库数据库请求响应jsp+javabean -> Web服务器
5-11 练习题

以下关于Javabean说法不正确的是( )。
Javabean只能封装数据不能封装业务逻辑。

Javabean就是符合某种设计规范的java类。
在Model1中,由Jsp页面去调用Javabean。
Javabean一般把属性设计为私有,使用setter和getter访问属性。

Javabean既可以封装数据同时也可以封装业务逻辑。

5-12 阶段项目

使用jsp+javabean完成用户登录功能

//用户的业务逻辑类public class UsersDAO {    //用户登录方法    public boolean usersLogin(Users u)    {        if("admin".equals(u.getUsername())&&"admin".equals(u.getPassword()))        {            return true;        }        else        {            return false;        }    }}
//用户类public class Users {    private String username;    private String password;    public Users()    {    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   request.setCharacterEncoding("utf-8");%><jsp:useBean id="loginUser" class="com.po.Users" scope="page"/><jsp:useBean id="userDAO" class="com.dao.UsersDAO" scope="page"/><jsp:setProperty property="*" name="loginUser"/><%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  //如果用户和密码都等于admin,则登录成功  if(userDAO.usersLogin(loginUser))  {     session.setAttribute("loginUser", loginUser.getUsername());     request.getRequestDispatcher("login_success.jsp").forward(request, response);  }  else  {     response.sendRedirect("login_failure.jsp");  }%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>    <head>        <!-- Page title -->        <title>imooc - Login</title>        <!-- End of Page title -->        <!-- Libraries -->        <link type="text/css" href="css/login.css" rel="stylesheet" />          <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>        <script type="text/javascript" src="js/easyTooltip.js"></script>        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>        <!-- End of Libraries -->       </head>    <body>    <div id="container">        <div class="logo">            <a href="#"><img src="assets/logo.png" alt="" /></a>        </div>        <div id="box">            <form action="dologin.jsp" method="post">            <p class="main">                <label>用户名: </label>                <input name="username" value="" />                 <label>密码: </label>                <input type="password" name="password" value="">                </p>            <p class="space">                <input type="submit" value="登录" class="login" style="cursor: pointer;"/>            </p>            </form>        </div>    </div>    </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>    <head>        <!-- Page title -->        <title>imooc - Login</title>        <!-- End of Page title -->        <!-- Libraries -->        <link type="text/css" href="css/login.css" rel="stylesheet" />          <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>        <script type="text/javascript" src="js/easyTooltip.js"></script>        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>        <!-- End of Libraries -->       </head>    <body>    <div id="container">        <div class="logo">            <a href="#"><img src="assets/logo.png" alt="" /></a>        </div>        <div id="box">          <%              String loginUser = "";             if(session.getAttribute("loginUser")!=null)             {                loginUser = session.getAttribute("loginUser").toString();             }          %>             欢迎您<font color="red"><%=loginUser%></font>,登录成功!        </div>    </div>    </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>    <head>        <!-- Page title -->        <title>imooc - Login</title>        <!-- End of Page title -->        <!-- Libraries -->        <link type="text/css" href="css/login.css" rel="stylesheet" />          <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>        <script type="text/javascript" src="js/easyTooltip.js"></script>        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>        <!-- End of Libraries -->       </head>    <body>    <div id="container">        <div class="logo">            <a href="#"><img src="assets/logo.png" alt="" /></a>        </div>        <div id="box">             登录失败!请检查用户或者密码!<br>          <a href="login.jsp">返回登录</a>           </div>    </div>    </body></html>
第6章 JSP状态管理
6-1 http协议的无状态性
  • http协议无状态性
  • 保存用户状态的两大机制
  • Cookie简介
  • Cookie的创建与使用
  • Session与Cookie对比

http协议的无状态性
无状态是指,当浏览器发送请求给服务器的时候,服务器响应客户端请求。
但是当同一个浏览器再一次发送请求给服务器的时候,服务器并不知道它
就是刚才那个浏览器。
简单的说,就是服务器不会去记得你,所以就是无状态协议。

6-2 Cookie概述

保存用户的状态的两大机制

  • Session
  • Cookie

什么是Cookie?

Cookie:中文名称为“小甜饼”,是Web服务器保存在客户端的一些列文本信息。

  • 典型应用一:判定注册用户是否已经登陆网站。
  • 典型应用二:“购物车”的处理。

生活中Cookie的应用

  • 系统会自动记录已经浏览过的视屏
  • 记住用户名和密码实现自动登陆

Cookie的作用

  • 对特定的对象的追踪
  • 保存用户网页浏览记录与习惯
  • 简化登陆

安全风险:容易泄露用户信息

6-3 JSP页面中创建与使用Cookie

Jsp中创建与使用Cookie

  • 创建Cookie对象
    Cookie newCookie = new Cookie(String key,Object value);
  • 写入Cookie对象
    response.addCookie(newCookie);
  • 读取Cookie对象
    Cookiep[] cookies = request.getCookies();

常用方法

方法名称 说明 void setMaxAge(int expiry) 设置cookie的有效期,以秒为单位 void setValue(String value) 在cookie创建后,对cookie进行赋值 String getName() 获取cookie的名称 String getValue() 获取cookie的值 int getMaxAge() 获取cookie的有效时间,以秒为单位
6-4 案例:Cookie在登录中的应用

实现记忆用户名和密码功能

<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>用户登录</h1>    <hr>    <%       request.setCharacterEncoding("utf-8");      String username="";      String password = "";      Cookie[] cookies = request.getCookies();      if(cookies!=null&&cookies.length>0)      {           for(Cookie c:cookies)           {              if(c.getName().equals("username"))              {                   username =  URLDecoder.decode(c.getValue(),"utf-8");              }              if(c.getName().equals("password"))              {                   password =  URLDecoder.decode(c.getValue(),"utf-8");              }           }      }    %>    <form name="loginForm" action="dologin.jsp" method="post">       <table>         <tr>           <td>用户名:</td>           <td><input type="text" name="username" value="<%=username %>"/></td>         </tr>         <tr>           <td>密码:</td>           <td><input type="password" name="password" value="<%=password %>" /></td>         </tr>         <tr>           <td colspan="2"><input type="checkbox" name="isUseCookie" checked="checked"/>十天内记住我的登录状态</td>         </tr>         <tr>           <td colspan="2" align="center"><input type="submit" value="登录"/><input type="reset" value="取消"/></td>         </tr>       </table>    </form>  </body></html>
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'dologin.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>登录成功</h1>    <hr>    <br>    <br>    <br>    <%        request.setCharacterEncoding("utf-8");       //首先判断用户是否选择了记住登录状态       String[] isUseCookies = request.getParameterValues("isUseCookie");       if(isUseCookies!=null&&isUseCookies.length>0)       {          //把用户名和密码保存在Cookie对象里面          String username = URLEncoder.encode(request.getParameter("username"),"utf-8");          //使用URLEncoder解决无法在Cookie当中保存中文字符串问题          String password = URLEncoder.encode(request.getParameter("password"),"utf-8");          Cookie usernameCookie = new Cookie("username",username);          Cookie passwordCookie = new Cookie("password",password);          usernameCookie.setMaxAge(864000);          passwordCookie.setMaxAge(864000);//设置最大生存期限为10response.addCookie(usernameCookie);          response.addCookie(passwordCookie);       }       else       {          Cookie[] cookies = request.getCookies();          if(cookies!=null&&cookies.length>0)          {             for(Cookie c:cookies)             {                if(c.getName().equals("username")||c.getName().equals("password"))                {                    c.setMaxAge(0); //设置Cookie失效                    response.addCookie(c); //重新保存。                }             }          }       }    %>    <a href="users.jsp" target="_blank">查看用户信息</a>  </body></html>
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'users.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>用户信息</h1>    <hr>    <%       request.setCharacterEncoding("utf-8");      String username="";      String password = "";      Cookie[] cookies = request.getCookies();      if(cookies!=null&&cookies.length>0)      {           for(Cookie c:cookies)           {              if(c.getName().equals("username"))              {                   username = URLDecoder.decode(c.getValue(),"utf-8");              }              if(c.getName().equals("password"))              {                   password = URLDecoder.decode(c.getValue(),"utf-8");              }           }      }    %>    <BR>    <BR>    <BR>         用户名:<%=username %><br>         密码:<%=password %><br>  </body></html>
6-5 Session与Cookie的对比
session cookie 在服务端保存用户信息 在客户端保存用户信息 session中保存的是Object类型 cookie中保存的是String类型 随会话的结束而将其存储的数据销毁 cookie可以长期保存在客户端 保存重要信息 保存不重要信息
6-6 练习题

下面关于Cookie与Session的对比描述不正确的是()
Cookie与Session都可以保存任意大小的对象类型

Cookie是客户端保存用户状态的机制
Session是服务器端保存用户状态的机制
Cookie与Session都可以设置生存期限

Cookie中对保存对象的大小是有限制的

6-7 练习题

如果想要设置当前Cookie的生存期限为24小时,以下代码正确的是
setMaxAge(86400);

第7章 JSP指令与动作元素
7-1 include指令
  • include指令
  • include动作
  • include指令与include动作的区别
  • 动作
  • 动作
  • 动作

include指令
语法:
<%@ include file=”URL” %>

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'Include_Command.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>Include指令</h1>    <hr>    <%@ include file="date.jsp"%>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="java.text.*" %><%   Date d = new Date();   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");   String s = sdf.format(d);   out.println(s);%>
7-2 include动作

include动作

语法:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'Include_Command.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>Include动作</h1>    <hr>    <jsp:include page="date.jsp" flush="false"/>  </body></html>
7-3 include指令与include动作的区别
include指令 jsp:include动作 语法格式 <%@include file=”..” %> 发生作用的时间 页面转换期间 包含的内容 文件的实际内容 转换成的Servlet 主页面和包含页面转换成一个Servlet 编译时间 较慢–资源必须被解析 执行时间 稍快
public final class include_005fcommand_jsp extends org.apache.jasper.runtime.HttpJspBase    implements org.apache.jasper.runtime.JspSourceDependent {  private static final javax.servlet.jsp.JspFactory _jspxFactory =          javax.servlet.jsp.JspFactory.getDefaultFactory();  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;  static {    _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1);    _jspx_dependants.put("/date.jsp", Long.valueOf(1504776944846L));  }  private javax.el.ExpressionFactory _el_expressionfactory;  private org.apache.tomcat.InstanceManager _jsp_instancemanager;  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {    return _jspx_dependants;  }  public void _jspInit() {    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());  }  public void _jspDestroy() {  }  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)        throws java.io.IOException, javax.servlet.ServletException {    final javax.servlet.jsp.PageContext pageContext;    javax.servlet.http.HttpSession session = null;    final javax.servlet.ServletContext application;    final javax.servlet.ServletConfig config;    javax.servlet.jsp.JspWriter out = null;    final java.lang.Object page = this;    javax.servlet.jsp.JspWriter _jspx_out = null;    javax.servlet.jsp.PageContext _jspx_page_context = null;    try {      response.setContentType("text/html; charset=utf-8");      pageContext = _jspxFactory.getPageContext(this, request, response,                null, true, 8192, true);      _jspx_page_context = pageContext;      application = pageContext.getServletContext();      config = pageContext.getServletConfig();      session = pageContext.getSession();      out = pageContext.getOut();      _jspx_out = out;      out.write('\r');      out.write('\n');String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";      out.write("\r\n");      out.write("\r\n");      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");      out.write("<html>\r\n");      out.write("  <head>\r\n");      out.write("    <base href=\"");      out.print(basePath);      out.write("\">\r\n");      out.write("    \r\n");      out.write("    <title>My JSP 'Include_Command.jsp' starting page</title>\r\n");      out.write("    \r\n");      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");      out.write("\t<!--\r\n");      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");      out.write("\t-->\r\n");      out.write("\r\n");      out.write("  </head>\r\n");      out.write("  \r\n");      out.write("  <body>\r\n");      out.write("    <h1>Include指令</h1>\r\n");      out.write("    <hr>\r\n");      out.write("    ");      out.write("\r\n");      out.write("\r\n");   Date d = new Date();   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");   String s = sdf.format(d);   out.println(s);      out.write('\r');      out.write('\n');      out.write("\r\n");      out.write("  </body>\r\n");      out.write("</html>\r\n");    } catch (java.lang.Throwable t) {      if (!(t instanceof javax.servlet.jsp.SkipPageException)){        out = _jspx_out;        if (out != null && out.getBufferSize() != 0)          try {            if (response.isCommitted()) {              out.flush();            } else {              out.clearBuffer();            }          } catch (java.io.IOException e) {}        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);        else throw new ServletException(t);      }    } finally {      _jspxFactory.releasePageContext(_jspx_page_context);    }  }}
public final class include_005faction_jsp extends org.apache.jasper.runtime.HttpJspBase    implements org.apache.jasper.runtime.JspSourceDependent {  private static final javax.servlet.jsp.JspFactory _jspxFactory =          javax.servlet.jsp.JspFactory.getDefaultFactory();  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;  private javax.el.ExpressionFactory _el_expressionfactory;  private org.apache.tomcat.InstanceManager _jsp_instancemanager;  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {    return _jspx_dependants;  }  public void _jspInit() {    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());  }  public void _jspDestroy() {  }  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)        throws java.io.IOException, javax.servlet.ServletException {    final javax.servlet.jsp.PageContext pageContext;    javax.servlet.http.HttpSession session = null;    final javax.servlet.ServletContext application;    final javax.servlet.ServletConfig config;    javax.servlet.jsp.JspWriter out = null;    final java.lang.Object page = this;    javax.servlet.jsp.JspWriter _jspx_out = null;    javax.servlet.jsp.PageContext _jspx_page_context = null;    try {      response.setContentType("text/html; charset=utf-8");      pageContext = _jspxFactory.getPageContext(this, request, response,                null, true, 8192, true);      _jspx_page_context = pageContext;      application = pageContext.getServletContext();      config = pageContext.getServletConfig();      session = pageContext.getSession();      out = pageContext.getOut();      _jspx_out = out;      out.write('\r');      out.write('\n');String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";      out.write("\r\n");      out.write("\r\n");      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");      out.write("<html>\r\n");      out.write("  <head>\r\n");      out.write("    <base href=\"");      out.print(basePath);      out.write("\">\r\n");      out.write("    \r\n");      out.write("    <title>My JSP 'Include_Command.jsp' starting page</title>\r\n");      out.write("    \r\n");      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");      out.write("\t<!--\r\n");      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");      out.write("\t-->\r\n");      out.write("\r\n");      out.write("  </head>\r\n");      out.write("  \r\n");      out.write("  <body>\r\n");      out.write("    <h1>Include动作</h1>\r\n");      out.write("    <hr>\r\n");      out.write("    ");      org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "date.jsp", out, false);      out.write("\r\n");      out.write("  </body>\r\n");      out.write("</html>\r\n");    } catch (java.lang.Throwable t) {      if (!(t instanceof javax.servlet.jsp.SkipPageException)){        out = _jspx_out;        if (out != null && out.getBufferSize() != 0)          try {            if (response.isCommitted()) {              out.flush();            } else {              out.clearBuffer();            }          } catch (java.io.IOException e) {}        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);        else throw new ServletException(t);      }    } finally {      _jspxFactory.releasePageContext(_jspx_page_context);    }  }}
public final class date_jsp extends org.apache.jasper.runtime.HttpJspBase    implements org.apache.jasper.runtime.JspSourceDependent {  private static final javax.servlet.jsp.JspFactory _jspxFactory =          javax.servlet.jsp.JspFactory.getDefaultFactory();  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;  private javax.el.ExpressionFactory _el_expressionfactory;  private org.apache.tomcat.InstanceManager _jsp_instancemanager;  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {    return _jspx_dependants;  }  public void _jspInit() {    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());  }  public void _jspDestroy() {  }  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)        throws java.io.IOException, javax.servlet.ServletException {    final javax.servlet.jsp.PageContext pageContext;    javax.servlet.http.HttpSession session = null;    final javax.servlet.ServletContext application;    final javax.servlet.ServletConfig config;    javax.servlet.jsp.JspWriter out = null;    final java.lang.Object page = this;    javax.servlet.jsp.JspWriter _jspx_out = null;    javax.servlet.jsp.PageContext _jspx_page_context = null;    try {      response.setContentType("text/html; charset=utf-8");      pageContext = _jspxFactory.getPageContext(this, request, response,                null, true, 8192, true);      _jspx_page_context = pageContext;      application = pageContext.getServletContext();      config = pageContext.getServletConfig();      session = pageContext.getSession();      out = pageContext.getOut();      _jspx_out = out;      out.write("\r\n");      out.write("\r\n");   Date d = new Date();   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");   String s = sdf.format(d);   out.println(s);      out.write('\r');      out.write('\n');    } catch (java.lang.Throwable t) {      if (!(t instanceof javax.servlet.jsp.SkipPageException)){        out = _jspx_out;        if (out != null && out.getBufferSize() != 0)          try {            if (response.isCommitted()) {              out.flush();            } else {              out.clearBuffer();            }          } catch (java.io.IOException e) {}        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);        else throw new ServletException(t);      }    } finally {      _jspxFactory.releasePageContext(_jspx_page_context);    }  }}
7-4 forward动作

forward动作

语法:

等同于:
request.getRequestDispatcher(“/url”).forward(request,response);

7-5 param动作

param动作

语法:

常常与一起使用,作为其的子标签。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>系统登录</h1>    <hr>    <form name="loginForm" action="dologin.jsp" method="post">      <table>        <tr>          <td>用户名:</td>          <td><input type="text" name="username"/></td>        </tr>        <tr>          <td>密码:</td>          <td><input type="password" name="password"/></td>        </tr>        <tr>          <td colspan="2"><input type="submit" value="登录"/></td>        </tr>      </table>    </form>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'dologin.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <jsp:forward page="user.jsp">      <jsp:param value="admin@123.net" name="email"/>      <jsp:param value="888888" name="password"/>    </jsp:forward>  </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'user.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    <h1>用户资料</h1>    <hr>    <%        request.setCharacterEncoding("utf-8");       String username = "";       String password = "";       String email = "";       if(request.getParameter("username")!=null)       {          username = request.getParameter("username");       }       if(request.getParameter("password")!=null)       {          password = request.getParameter("password");       }       if(request.getParameter("email")!=null)       {          email = request.getParameter("email");       }    %>        用户名:<%=username %><br>        密码:<%=password %><br>        电子邮箱:<%=email %><br>  </body></html>
7-6 练习题

下面关于include指令与include动作的对比描述不正确的是()
动作在编译期间被执行,而include指令在页面请求期间被执行

页面内容经常变化时更适合使用动作
页面内容不经常变化时更适合使用include指令
动作包含的是执行结果,而include指令包含的是文件内容

第8章 案例项目
8-1 项目总体介绍

案例:商品浏览记录的应用

采用Model1(Jsp+Javabean)实现

  • 实现DBHelper类
  • 创建实体类
  • 创建业务逻辑类(DAO)
  • 创建页面层
8-2 项目原型
  • 列表页面
  • 详情页面
8-3 DBHelper类设计

实现DBhelper类型
String driver = “com.mysql.jdbc.Driver”;//数据库驱动
String url = “jdbc:mysql://localhost:3306/shopping?useUnicode=true&charaterEncoding=UTF”;//连接数据库的url地址
String username = “root”;//数据库的用户名
String password = “”;//数据库密码

public class DBHelper {    private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动    //连接数据库的URL地址    private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8";     private static final String username="root";//数据库的用户名    private static final String password="root";//数据库的密码    private static Connection conn=null;    //静态代码块负责加载驱动    static     {        try        {            Class.forName(driver);        }        catch(Exception ex)        {            ex.printStackTrace();        }    }    //单例模式返回数据库连接对象    public static Connection getConnection() throws Exception    {        if(conn==null)        {            conn = DriverManager.getConnection(url, username, password);            return conn;        }        return conn;    }    public static void main(String[] args) {        try        {           Connection conn = DBHelper.getConnection();           if(conn!=null)           {               System.out.println("数据库连接正常!");           }           else           {               System.out.println("数据库连接异常!");           }        }        catch(Exception ex)        {            ex.printStackTrace();        }    }}
8-4 商品实体类设计

采用Model1(JSP+JavaBean)实现

  • 实现DBhelper类
  • 创建实体类
  • 创建业务逻辑类(DAO)
  • 创建页面层
//商品类public class Items {    private int id; // 商品编号    private String name; // 商品名称    private String city; // 产地    private int price; // 价格    private int number; // 库存    private String picture; // 商品图片    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    public int getPrice() {        return price;    }    public void setPrice(int price) {        this.price = price;    }    public int getNumber() {        return number;    }    public void setNumber(int number) {        this.number = number;    }    public String getPicture() {        return picture;    }    public void setPicture(String picture) {        this.picture = picture;    }}
8-5 获取所有商品资料方法的实现
//商品的业务逻辑类public class ItemsDAO {    // 获得所有的商品信息    public ArrayList<Items> getAllItems() {        Connection conn = null;        PreparedStatement stmt = null;        ResultSet rs = null;        ArrayList<Items> list = new ArrayList<Items>(); // 商品集合        try {            conn = DBHelper.getConnection();            String sql = "select * from items;"; // SQL语句            stmt = conn.prepareStatement(sql);            rs = stmt.executeQuery();            while (rs.next()) {                Items item = new Items();                item.setId(rs.getInt("id"));                item.setName(rs.getString("name"));                item.setCity(rs.getString("city"));                item.setNumber(rs.getInt("number"));                item.setPrice(rs.getInt("price"));                item.setPicture(rs.getString("picture"));                list.add(item);// 把一个商品加入集合            }            return list; // 返回集合。        } catch (Exception ex) {            ex.printStackTrace();            return null;        } finally {            // 释放数据集对象            if (rs != null) {                try {                    rs.close();                    rs = null;                } catch (Exception ex) {                    ex.printStackTrace();                }            }            // 释放语句对象            if (stmt != null) {                try {                    stmt.close();                    stmt = null;                } catch (Exception ex) {                    ex.printStackTrace();                }            }        }    }}
8-6 所有商品信息显示
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="entity.Items"%><%@ page import="dao.ItemsDAO"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->    <style type="text/css">       div{          float:left;          margin: 10px;       }       div dd{          margin:0px;          font-size:10pt;       }       div dd.dd_name       {          color:blue;       }       div dd.dd_city       {          color:#000;       }    </style>  </head>  <body>    <h1>商品展示</h1>    <hr>    <center>    <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">      <tr>        <td>          <!-- 商品循环开始 -->           <%                ItemsDAO itemsDao = new ItemsDAO();                ArrayList<Items> list = itemsDao.getAllItems();               if(list!=null&&list.size()>0)               {                   for(int i=0;i<list.size();i++)                   {                      Items item = list.get(i);           %>             <div>             <dl>               <dt>                 <a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>               </dt>               <dd class="dd_name"><%=item.getName() %></dd>                <dd class="dd_city">产地:<%=item.getCity() %>&nbsp;&nbsp;价格:¥ <%=item.getPrice() %></dd>              </dl>          </div>          <!-- 商品循环结束 -->          <%                   }              }           %>        </td>      </tr>    </table>    </center>  </body></html>
8-7 商品详细信息显示
8-8 使用Cookie实现保存商品浏览记录
//商品的业务逻辑类public class ItemsDAO {    // 获得所有的商品信息    public ArrayList<Items> getAllItems() {        Connection conn = null;        PreparedStatement stmt = null;        ResultSet rs = null;        ArrayList<Items> list = new ArrayList<Items>(); // 商品集合        try {            conn = DBHelper.getConnection();            String sql = "select * from items;"; // SQL语句            stmt = conn.prepareStatement(sql);            rs = stmt.executeQuery();            while (rs.next()) {                Items item = new Items();                item.setId(rs.getInt("id"));                item.setName(rs.getString("name"));                item.setCity(rs.getString("city"));                item.setNumber(rs.getInt("number"));                item.setPrice(rs.getInt("price"));                item.setPicture(rs.getString("picture"));                list.add(item);// 把一个商品加入集合            }            return list; // 返回集合。        } catch (Exception ex) {            ex.printStackTrace();            return null;        } finally {            // 释放数据集对象            if (rs != null) {                try {                    rs.close();                    rs = null;                } catch (Exception ex) {                    ex.printStackTrace();                }            }            // 释放语句对象            if (stmt != null) {                try {                    stmt.close();                    stmt = null;                } catch (Exception ex) {                    ex.printStackTrace();                }            }        }    }    // 根据商品编号获得商品资料    public Items getItemsById(int id) {        Connection conn = null;        PreparedStatement stmt = null;        ResultSet rs = null;        try {            conn = DBHelper.getConnection();            String sql = "select * from items where id=?;"; // SQL语句            stmt = conn.prepareStatement(sql);            stmt.setInt(1, id);            rs = stmt.executeQuery();            if (rs.next()) {                Items item = new Items();                item.setId(rs.getInt("id"));                item.setName(rs.getString("name"));                item.setCity(rs.getString("city"));                item.setNumber(rs.getInt("number"));                item.setPrice(rs.getInt("price"));                item.setPicture(rs.getString("picture"));                return item;            } else {                return null;            }        } catch (Exception ex) {            ex.printStackTrace();            return null;        } finally {            // 释放数据集对象            if (rs != null) {                try {                    rs.close();                    rs = null;                } catch (Exception ex) {                    ex.printStackTrace();                }            }            // 释放语句对象            if (stmt != null) {                try {                    stmt.close();                    stmt = null;                } catch (Exception ex) {                    ex.printStackTrace();                }            }        }    }    //获取最近浏览的前五条商品信息    public ArrayList<Items> getViewList(String list)    {        System.out.println("list:"+list);        ArrayList<Items> itemlist = new ArrayList<Items>();        int iCount=5; //每次返回前五条记录        if(list!=null&&list.length()>0)        {            String[] arr = list.split(",");            System.out.println("arr.length="+arr.length);            //如果商品记录大于等于5条            if(arr.length>=5)            {               for(int i=arr.length-1;i>=arr.length-iCount;i--)               {                  itemlist.add(getItemsById(Integer.parseInt(arr[i])));                 }            }            else            {                for(int i=arr.length-1;i>=0;i--)                {                    itemlist.add(getItemsById(Integer.parseInt(arr[i])));                }            }            return itemlist;        }        else        {            return null;        }    }}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%@ page import="entity.Items"%><%@ page import="dao.ItemsDAO"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'details.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->    <style type="text/css">       div{          float:left;          margin-left: 30px;          margin-right:30px;          margin-top: 5px;          margin-bottom: 5px;       }       div dd{          margin:0px;          font-size:10pt;       }       div dd.dd_name       {          color:blue;       }       div dd.dd_city       {          color:#000;       }    </style>  </head>  <body>    <h1>商品详情</h1>    <hr>    <center>      <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">        <tr>          <!-- 商品详情 -->          <%              ItemsDAO itemDao = new ItemsDAO();             Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));             if(item!=null)             {          %>          <td width="70%" valign="top">             <table>               <tr>                 <td rowspan="4"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>               </tr>               <tr>                 <td><B><%=item.getName() %></B></td>                </tr>               <tr>                 <td>产地:<%=item.getCity()%></td>               </tr>               <tr>                 <td>价格:<%=item.getPrice() %></td>               </tr>              </table>          </td>          <%             }          %>          <%               String list ="";              //从客户端获得Cookies集合              Cookie[] cookies = request.getCookies();              //遍历这个Cookies集合              if(cookies!=null&&cookies.length>0)              {                  for(Cookie c:cookies)                  {                      if(c.getName().equals("ListViewCookie"))                      {                         list = c.getValue();                      }                  }              }              list+=request.getParameter("id")+",";              //如果浏览记录超过1000条,清零.              String[] arr = list.split(",");              if(arr!=null&&arr.length>0)              {                  if(arr.length>=1000)                  {                      list="";                  }              }              Cookie cookie = new Cookie("ListViewCookie",list);              response.addCookie(cookie);          %>          <!-- 浏览过的商品 -->          <td width="30%" bgcolor="#EEE" align="center">             <br>             <b>您浏览过的商品</b><br>             <!-- 循环开始 -->             <%                 ArrayList<Items> itemlist = itemDao.getViewList(list);                if(itemlist!=null&&itemlist.size()>0 )                {                   System.out.println("itemlist.size="+itemlist.size());                   for(Items i:itemlist)                   {             %>             <div>             <dl>               <dt>                 <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>               </dt>               <dd class="dd_name"><%=i.getName() %></dd>                <dd class="dd_city">产地:<%=i.getCity() %>&nbsp;&nbsp;价格:<%=i.getPrice() %></dd>              </dl>             </div>             <%                    }                }             %>             <!-- 循环结束 -->          </td>        </tr>      </table>    </center>  </body></html>

《JAVA遇见HTML——JSP篇》视频地址

原创粉丝点击