A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

day17-Session将商品添加到购物车
查看某个商品详情的时候,添加到购物车,需要将商品添加到购物车.
Session的概述
Cookie本身是有大小和个数的限制,Session没有限制.Cookie的数据保存在客户端,Session数据保存在服务器端.(Cookie和Session的区别)
Session的执行原理:基于Cookie的.
使用Session:
  • 获得Session:
    • HTTPSession session = request.getSession();

步骤分析
  • 步骤一:点击加入购物车提交到Servlet
  • 步骤二:在Servlet将购物的商品存入到Session中.
  • 步骤三:可以创建一个Map集合用于保存购物信息Map的key可以是商品的名称,Map的value是数量.
  • 步骤四:在购物车页面中显示Map中的数据就可以.
代码实现public class CartServlet extends HttpServlet {        private static final long serialVersionUID = 1L;        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                // 接收商品名称:                String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");                // 创建Map集合用于保存购物信息.Map<String,Integer> Map的key是商品的名称 value是购买的数量.                Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart");                if(map == null){                        map = new LinkedHashMap<String,Integer>();                }                // 判断购物车中是否已经买了该商品.                if(map.containsKey(name)){                        // map中已经有该商品:// * 如果购物车中已经有该商品: 获得到Map中该商品的数量+1。 存回到Map集合中.                        Integer count = map.get(name);                        count++;                        map.put(name, count);                }else{                        // map中没有该商品.// * 如果购物车中没有改商品: 将商品添加到Map集合中 数量1.                        map.put(name, 1);                }                                                // * 将Map集合保存到session中.                request.getSession().setAttribute("cart", map);                response.setContentType("text/html;charset=UTF-8");                response.getWriter().println("<h3><a href='/day11/demo2/product_list.jsp'>继续购物</a> | <a href='/day11/demo2/cart.jsp'>去结算</a></h3>");        }Session是域对象Session何时创建和销毁?作用范围
  • 创建:服务端第一次调用getSession()创建session.
  • 销毁:三种情况销毁session:
      • session过期,默认过期时间为30分钟.
      • 非正常关闭服务器,如果正常关闭session序列化到硬盘.
      • 手动调用session.invalidate();

  • 作用范围:多次请求.(一次会话)
针对自己项目配置session过期时间: 单位是分钟<session-config>    <session-timeout>5</session-timeout>    </session-config>进行一次性验证码的校验
在登录的页面中,需要有一个验证码的校验.
使用Session保存生成的验证码.
步骤分析:
  • 步骤一:生成验证码,将生成验证码的随机的4个字母或数字保存到session中.
  • 步骤二:在页面中输入验证码的值,点提交.
  • 步骤三:在Servlet中从表单中获得验证码从session中获得一个验证码
  • 步骤四:比对两个验证码值是否一致.
  • 步骤五:将session中保存的验证码清空.
代码实现protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                // 校验验证码程序:                String code1 = request.getParameter("code");                String code2 = (String) request.getSession().getAttribute("code");                request.getSession().removeAttribute("code");                if(!code1.equalsIgnoreCase(code2)){                        request.setAttribute("msg", "验证码输入错误!");                        request.getRequestDispatcher("/demo2/login.jsp").forward(request, response);                        return ;                }   ...}使用JS控制图片切换<script type="text/javascript">         function changeImg(){                 document.getElementById("img1").src="/day11/CheckImgServlet?time="+new Date().getTime();         } </script>使用JQ控制图片切换<script>    $(function(){     $("#img1").on("click",function(){         $(this).prop("src","/day11/CheckImgServlet?time="new Date().getTime())     });       });</script>JSP在JSP的页面中显示商品的信息.
数据库中存放了很多的商品信息,现在将商品的信息全部显示到页面.
JSP的概述
什么是JSP:Java Server Pages(Java服务器端的页面)
为什么要学习JSP:SUN公司推出的Servlet自身有缺陷,没有办法与ASP,PHP进行竞争.推出了动态网页开发技术JSP.
使用JSP: JSP = HTML + Java代码 + JSP自身的东西.
执行JSP的过程:JSP翻译成Servlet,编译这个Servlet的类,生成class文件.得到执行.
JSP的脚本
%! %>        :翻译成Servlet中的成员内容. 定义变量,方法,类. -- 不建议.
<% %>        :翻译成Servlet中service方法内部的内容. 定义类,变量
<%= %>        :翻译成Servlet中service方法中out.print();
JSP的注释 (了解)
  • HTML的注释 : (存在于JSP源码中,存在于JSP翻译后的Servlet中,存在于生成的HTML中)
  • Java代码的注释 :// 单行注释 (存在于JSP的源码中,翻译成Servlet后注释也存在,但是当执行完JSP后生成HTML后,注释就消失了) /* 多行注释*/ /** 文档注释 */
  • JSP的注释 :<%--JSP的注释--%> (只会存在于JSP的源代码中,翻译成Servlet后,JSP的注释就消失了)
什么样的代码用什么注释,实在不清楚可以用快捷键"Ctrl+Shift+/"会自动匹配合适的注释.
JSP的指令
指令的语法:
<%@ 指令名称 属性名称=”属性值” 属性名称=”属性值” ...%>
  • JSP中有三个指令:page指令, include指令, taglib指令.
JSP中page指令:<%@ page %> -- 设置JSP的.
  • language :JSP脚本中使用的语言.现在只能写java.
  • contentType :设置浏览器打开这个JSP的时候采用的默认的字符集的编码.
  • pageEncoding :设置文件保存到本地硬盘,以及生成Servlet后,Servlet保存到硬盘上的编码.
  • import :在JSP中引入类对象,但是import可以出现多次.
<%@page import="java.util.ArrayList"%><%@page import="java.util.List"%>
  • extends :设置JSP翻译成Servlet后继承的类,默认值:org.apache.jasper.runtime.HttpJspBase,这个值要想修改,这个类必须是HttpServlet的子类
  • autoFlush :设置JSP的缓冲自动刷出,true:自动刷出.
  • buffer :设置JSP的缓冲区的大小,默认8kb.
  • session :设置在JSP中是否可以直接使用session对象,默认值是true.
  • isELIgnored :设置在JSP中是否忽略EL表达式,默认值是false不忽略.
  • errorPage :设置错误友好页面的提示.
  • isErrorPage :通过这个设置显示JSP的错误信息.
  • 设置全局的错误友好页面:
    • 在web.xml中配置:

<error-page>          <error-code>404</error-code>          <location>/404.jsp</location>  </error-page>  <error-page>          <error-code>500</error-code>          <location>/500.jsp</location>  </error-page>JSP中的include指令:只是JSP包含其他的页面.<%@ include file="logo.jsp" %><%@ include file="menu.jsp" %><h1>BODY部分</h1><%@ include file="footer.jsp" %>JSP中的taglib指令:指示JSP引入标签库.
<%@ taglib uri="标签的URI的路径" prefix="标签的别名" %>
JSP的内置对象
JSP的内置对象: 在JSP中可以直接使用的对象.
JSP中有9大内置对象:
  • request        HttpServletRequest        getParameter(),setAttribute(String name,Object value);
  • response        HttpServletResponse        setHeader(String name,String value);getOutputStream();getWriter();
  • session        HttpSession        setAttribute();getAttribute();
  • application        ServletContext        setAttribute();getAttribute();
  • page        Object        toString();wait();
  • pageContext        PageContext        setAttribute();getAttribute();
  • config        ServletConfig        getServletName();getServletContext();
  • out        JspWriter        write(),print();
  • exception        Throwable        getMessage(),getCause(); 设置isErrorPage=”true”
header 1header 2header 3
requestHttpServletRequestgetParameter(),setAttribute(String name,Object value);
responseHttpServletResponsesetHeader(String name,String value);getOutputStream();getWriter();
sessionHttpSessionsetAttribute();getAttribute();
applicationServletContextsetAttribute();getAttribute();
pageObjecttoString();wait();
pageContextPageContextsetAttribute();getAttribute();
configServletConfiggetServletName();getServletContext();
outJspWriterwrite(),print();
exceptionThrowablegetMessage(),getCause(); 设置isErrorPage=”true”
page内置对象 :真实对象是Object,就是JSP翻译成Servlet后的类的引用.
out内置对象 :out和response.getWriter是不是同一个对象?区别是什么? * 不是out真实对象JspWriter ,response获得Writer是PrintWriter.
pageContext内置对象:
  • 获得其他的8个内置对象 :编写通用性代码或者框架的时候.
  • 向JSP的四个域中存取数据:
    • PageScope        :当前页面中有效.        pageContext        PageContext
    • RequestScope        :一次请求范围.        request        HttpServletRequest
    • SessionScope        :一次会话范围.        session        HttpSession
    • ApplicationScope        :应用范围        application        ServletContext

JSP的动作标签 列出6个
  • 标签的作用:简化代码.
  • <jsp:forward />        :用于页面的转发.
    • <jsp:forward page="/demo1-jsp/demo3-object/demo3.jsp"></jsp:forward>
  • <jsp:include />        :用于页面的包含.(动态包含)

*****静态包含和动态包含的区别?(<%@ include%>和<jsp:include>)
  • <jsp:param />        :用于带有路径的标签下,传递参数.
  • <jsp:useBean />        :用于在JSP中使用JavaBean.
  • <jsp:setProperty />        :用于在JSP中向JavaBean设置属性的.
  • <jsp:getProperty />        :用于在JSP中获得JavaBean的属性.


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马