大数据正式17
-
初识JSP
-
先来看个例子
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% 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 'test.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> This is my JSP page. <br> <% Date date = new Date(); out.write(date.toLocaleString()); %> </body> </html>
- 效果
-
- 效果
-
-
概述
- jsp实际是动态页面技术
- HTML无法嵌入java代码,但是jsp可以嵌入java代码
-
原理
- jsp会在第一次访问时,被翻译成servlet,之后对这个jsp访问,实际上是对这个jsp生成的servlet进行访问
- 生产的servlet路径【路径:C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\EasyMallWeb\org\apache\jsp下的java文件】
-
生产的servlet例子
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.64 * Generated at: 2017-12-02 03:42:39 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.util.*; 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=ISO-8859-1"); 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 '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(" This is my JSP page. <br>\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); } } }
- jsp基本组成结构
- 模板元素:在jsp页面编写的html内容,翻译的时候为out.write("<...>");进行输出
<html> <head> </head> <h1>hello world!</h1> <body> </body> </html>
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("</head>\r\n"); out.write("<h1>hello world!</h1>\r\n"); out.write("<body>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n");
- 效果:
-
- 效果:
- 脚本表达式:<%=java表达式(无分号)%>,在页面通过执行脚本表达式,来将一个计算结果输出到界面out.print(java表达式)
<%=1+1 %>
out.print(1+1 );
- 效果:
-
- 效果:
- 脚本片段:<%完整的java语句%>,在翻译成servlet的过程中,原样输出到servlet的对应位置
- 注意
- 同一个页面中,后面的java代码可以访问到之前片段声明的变量
- java代码可以分开,即不用完整,分开写,在servlet成型时逻辑通即可
<% for (int i = 0; i < 10; i++) { out.write(""+i); } %>
for (int i = 0; i < 10; i++) { out.write(""+i); }
- 效果
-
- 注意
- jsp声明:<%! %>在jsp声明的内容,被翻译成servlet的过程中,放置到和service同级的位置
<%!String x = "100";%> <h1>lala~~~</h1> <% out.write(x); %>
String x = "100"; 。。。 public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { ... out.write(x); ... }
- 效果
-
- 效果
- jsp注释:<%-- --%>,可以通过jsp注释来将内容注释掉,翻译成servlet直接忽略掉,不会被
1. jsp注释<%-- --%>-------在servlet直接没有 2. java注释// /*/---------在servlet中注释的内容 3. html注释<!-- -->-------在servlet中当做模板元素输出到页面
<%--我是jsp注释 --%>
servlet中没有对应的代码
- 效果
-
- 效果
- 模板元素:在jsp页面编写的html内容,翻译的时候为out.write("<...>");进行输出
-
在真正的开发中,servlet擅长处理业务逻辑,但是不擅长输出页面;jsp不擅长处理业务逻辑,但是擅长页面输出;往往是servlet处理逻辑通过请求转发,利用request域将结果发给jsp,jsp展示界面【转发:域对象来带数据】
会话
- 概述:用户开一个浏览器,访问多个资源,访问服务器多个web资源,然后关闭资源,整个过程称之为一个会话
- 会话中的问题:数据的保存
- request的范围不适合为一个用户多次请求的数据保存,范围太小;每一次都是一个新的Request对象,之前的数据都不存在了
- ServletContext域又太大,各个用户的操作互相影响
- cookie:各个用户互不影响,数据又只属于自己一个人【将会话信息存放在客户端】
- Session:各个用户互不影响,数据又只属于自己一个人【将会话信息存放在服务器端】
-
cookie是客户端技术,将会话产生的数据保存在客户端,当浏览器访问服务器时,服务器通过set-Cookie将数据发送给客户端,客户端进行保存;当浏览器再次访问服务器时,Cookie头信息将之前的保存的信息发送给服务端
package com.peng.ser; import java.io.IOException; import java.util.Date; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LastTimeAccess extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, String> map = new HashMap<String, String>(); // 获取上一次访问的时间 String str = request.getHeader("Cookie"); if (null != str) { // 存Cookie到map for (String temp : str.split(";")) { String[] kv = temp.split("="); map.put(kv[0], kv[1]); } if (map.containsKey("lasttime")) { System.out.println(map.get("lasttime")); response.getWriter().write(map.get("lasttime")); } } response.addHeader("set-Cookie", "lasttime=" + new Date().toLocaleString()); } }
-
简化Cookie的使用
-
api:Cookie类
- 构造方法:Cookie cookie=new Cookie(String name,String value);//只有有参构造
- 普通方法:
- String getName()
- String getValue()
- void setValue(String value)
- 向响应中加入Cookie:response.addCookie(Cookie c)
-
获取头中的Cookie数组:request.getCookies()
package com.peng.ser; import java.io.IOException; import java.util.Date; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LastTimeAccess extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上一次访问的时间 Cookie[] cs = request.getCookies(); if (cs != null) { for (Cookie cookie : cs) { if ("lasttime".equals(cookie.getName())) { response.getWriter().write(cookie.getValue()); } } } Cookie c = new Cookie("lasttime", new Date().toLocaleString()); response.addCookie(c); } }
-
-
Cookie的存活时间
- 如果不设置,浏览器关闭cookie的生命周期也就结束;【会话级别的Cookie】
-
代码设置Cookie的存活时间:保存指定的时间,即使关闭浏览器,下次打开也会存在
package com.peng.ser; import java.io.IOException; import java.util.Date; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LastTimeAccess extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上一次访问的时间 Cookie[] cs = request.getCookies(); if (cs != null) { for (Cookie cookie : cs) { if ("lasttime".equals(cookie.getName())) { response.getWriter().write(cookie.getValue()); } } } Cookie c = new Cookie("lasttime", new Date().toLocaleString()); c.setMaxAge(60 * 60 * 24);// Cookie的存活时间 一天 response.addCookie(c); } }
-
Cookie的访问路径下携带数据
- 如果不设置,则为servlet所在目录的父一级及之后的目录都有此cookie
-
设置浏览器访问哪些路径时携带Cookie【cookie.setPath(String path)】
package com.peng.ser; import java.io.IOException; import java.util.Date; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LastTimeAccess extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上一次访问的时间 Cookie[] cs = request.getCookies(); if (cs != null) { for (Cookie cookie : cs) { if ("lasttime".equals(cookie.getName())) { response.getWriter().write(cookie.getValue()); } } } Cookie c = new Cookie("lasttime", new Date().toLocaleString()); c.setMaxAge(60 * 60 * 24);// Cookie的存活时间 一天 c.setPath("/publicDemo");//设置可以携带的cookie response.addCookie(c); } }
-
删除Cookie
-
需要发送一个Cookie,名字相同,PATH相同,但是要把sexMaxAge(0)设置为0,即立即删除此Cookie
package com.peng.ser; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DelCookie extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie c = new Cookie("lasttime", new Date().toLocaleString()); c.setMaxAge(0);// 删除cookie c.setPath(request.getContextPath()); response.addCookie(c); } }
-
- 浏览器一般最多存放300个,每个站点最多20个,每个最大不超过4kb--为了安全,防止恶意攻击
Session
- 服务端会话数据保存的技术
- 服务器在需要时可以为每个用户创建独一无二的Session对象,在其中保存会话数据,之后同一个用户再来访问,可以找到它对应的Session,每个Session只为各自对象服务,不会发生混乱
- 是一个域对象
- 生命周期:当第一次调用requext.getSession()方法时,此时创建,一直驻留在内存中服务
- 作用范围:整个会话
- 主要功能:在会话范围内共享数据
- 杀死session
- 自杀:invalidate
- 意外身亡:当前web应用销毁时
- 超时(寿终正寝):如果一个session超过30分钟没人用,则服务器认为session超时,则杀死相应的session
- 获取session
- request.getSession();
- 存数据
- request.getSession();
- session.setAttribute(String key,Object obj);
- session.getAttribute(key);
补充
-
EasyMall登录页面逻辑
-
登录页面
<%@page import="java.net.URLDecoder"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="css/login.css" /> <title>EasyMall欢迎您登陆</title> </head> <body> <h1>欢迎登陆EasyMall</h1> <% //获取Cookie Cookie[] cookies = request.getCookies(); String cookieUsername = null; if (cookies != null) { for (Cookie cookie : cookies) { if ("remname".equals(cookie.getName())) { cookieUsername = cookie.getValue(); } } } %> <form action="/LoginSer" method="POST"> <table> <%=//提示账号密码错误 request.getParameter("msg") == null ? "" : "<tr><td colspan='2'><font color='#ff0000'>" + new String(request.getParameter("msg").getBytes("iso8859-1"),"utf-8")+ "</font></td></tr>"%> <tr> <td class="tdx">用户名:</td> <td><input type="text" name="username" <%=cookieUsername == null ? "" : "value=" + cookieUsername + ""%> /> </td> </tr> <tr> <td class="tdx">密码:</td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2"><input type="checkbox" name="remname" value="true" <%=cookieUsername == null ? "" : "checked='checked'"%> />记住用户名 <input type="checkbox" name="autologin" value="true" />30天内自动登陆</td> </tr> <tr> <td colspan="2"><input type="submit" value="登陆" /> </td> </tr> </table> </form> </body> </html>
-
登录后台
package com.easymall.ser; import java.io.IOException; import java.net.URLEncoder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.easymall.utils.MySqlUtils; @SuppressWarnings("serial") public class LoginSer extends HttpServlet { private Connection conn = null; private PreparedStatement stat = null; private ResultSet rs = null; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解决乱码 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); // 获取用户名和密码 String username = request.getParameter("username") == null ? "" : request.getParameter("username"); String password = request.getParameter("password") == null ? "" : request.getParameter("password"); // 处理记住用户名的逻辑 if ("true".equals(request.getParameter("remname"))) { Cookie cookie = new Cookie("remname", URLEncoder.encode(username, "utf-8")); cookie.setMaxAge(60 * 60 * 24 * 30); cookie.setPath(request.getContextPath()); response.addCookie(cookie); } else {// 不保存--删除Cookie Cookie cookie = new Cookie("remname", ""); cookie.setMaxAge(0); cookie.setPath(request.getContextPath()); response.addCookie(cookie); } // 检查用户名和密码 try { conn = MySqlUtils.getConn(); stat = conn .prepareStatement("select * from user where username=? and password=?"); stat.setString(1, username); stat.setString(2, password); rs = stat.executeQuery(); if (rs.next()) { // 正确,回到主页 // 获取session HttpSession session = request.getSession(); // 在session中加入相应的标记 session.setAttribute("username", username); // 回到主页 response.getWriter().write("登录成功!正在跳转。。。"); response.setHeader("refresh", "2;url=" + request.getContextPath() + "/index.jsp"); } else {// 不正确,回到登录界面 response.addHeader("refresh", "0;url=" + request.getContextPath() + "/login.jsp?msg=" + URLEncoder.encode("账号密码错误!","utf-8")); } } catch (Exception e) { e.printStackTrace(); } finally { MySqlUtils.close(conn, stat, rs); } } }
-
-
注销逻辑
package com.easymall.ser; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 注销当前账户 * * @author Administrator * */ @SuppressWarnings("serial") public class LogoutSer extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解决乱码 response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charst=utf-8"); // 杀死session--先进行判断用户是否有session--防止恶意攻击 if (request.getSession(false) != null) { request.getSession(false).invalidate(); } // 回到主页 // 注销中。。。 response.getWriter().write("注销成功!正在跳转到主页。。。"); response.setHeader("refresh", "2;url=" + request.getContextPath() + "/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
-
首界面
-
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" buffer="0kb"%> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="css/index.css" /> <title>欢迎光临EasyMall</title> </head> <body> <% request.getRequestDispatcher("head.jsp").include(request, response); %> <div id="index"> <div id="line1"> <img src="img/index/banner_big.jpg" /> </div> <div id="line2"> <img id="line2_1" src="img/index/adv1.jpg" /> <img id="line2_2" src="img/index/adv2.jpg" /> <img id="line2_3" src="img/index/adv_l1.jpg" /> </div> <div id="line3"> <img id="line3_1" src="img/index/adv3.jpg" /> <img id="line3_2" src="img/index/adv4.jpg" /> <div id="line3_right"> <img id="line3_3" src="img/index/adv_l2.jpg" /> <img id="line3_4" src="img/index/adv_l3.jpg" /> </div> </div> <div id="line4"> <img src="img/index/217.jpg" /> </div> <div id="line5"> <span id="line5_1"> <img src="img/index/icon_g1.png" /> 500强企业 品质保证 </span> <span id="line5_2"> <img src="img/index/icon_g2.png" /> 7天退货 15天换货 </span> <span id="line5_3"> <img src="img/index/icon_g3.png" /> 100元起免运费 </span> <span id="line5_4"> <img src="img/index/icon_g4.png" /> 448家维修网点 全国联保 </span> </div> </div> <% request.getRequestDispatcher("foot.jsp").include(request, response); %> </body> </html>
-
head.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <link rel="stylesheet" href="css/head.css" /> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> <div id="common_head"> <div id="line1"> <div id="content"> <% HttpSession sessionUsername = request.getSession(false); //双重判断--session和username都不能为空 if (sessionUsername != null && null != sessionUsername.getAttribute("username")) { %> 您好:<%=sessionUsername.getAttribute("username")%> | <a href="<%=request.getContextPath()%>/LogoutSer">注销 </a> <% } else { %> <a href="<%=request.getContextPath()%>/login.jsp">登录</a> | <a href="<%=request.getContextPath()%>/regist.jsp">注册</a> <% } %> </div> </div> <div id="line2"> <img id="logo" src="img/head/logo.jpg" /> <input type="text" name="" /> <input type="button" value="搜索" /> <span id="goto"> <a id="goto_order" href="#">我的订单</a> <a id="goto_cart" href="#">我的购物车</a> </span> <img id="erwm" src="img/head/qr.jpg" /> </div> <div id="line3"> <div id="content"> <ul> <li><a href="#">首页</a></li> <li><a href="#">全部商品</a></li> <li><a href="#">手机数码</a></li> <li><a href="#">电脑平板</a></li> <li><a href="#">家用电器</a></li> <li><a href="#">汽车用品</a></li> <li><a href="#">食品饮料</a></li> <li><a href="#">图书杂志</a></li> <li><a href="#">服装服饰</a></li> <li><a href="#">理财产品</a></li> </ul> </div> </div> </div>
- foot.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="css/foot.css" /> <div id="common_foot"> <p> Copyright © 2011-2015 达内软件技术有限公司 版权所有 保留一切权利 苏B2-20130048号 | 京ICP备09062682号-9 <br> 网络文化经营许可证苏网文[2012]0401-019号 </p> </div>
-
-