JSP学习笔记2
《JAVA遇见HTML——JSP篇》学习笔记(下)
1.Javabean
Javabeans就是符合某种规范的java类,使用Javabeans的好处是【解决代码的重复编写】,减少代码冗余,功能区分明确,提高代码的维护性。
设计原则(规范):1.公有类 2.属性私有 3.包含无参的共有构造方法 4.getter和setter方法封装属性
JSP动作元素(action element):
JSP动作元素为请求处理阶段提供信息。动作元素遵循XML语法,有一个包含元素名的开始标签,可以有属性,可选的内容、与开始标签匹配的结束标签。
第一类是与存取JavaBean有关,包括: <jsp:useBean> <jsp:setProperty> <jsp:getProperty>
<jsp:useBean id="标识符" class="实例化的类的完整名称" scope="作用范围" /> id可以理解为创建的类的对象的名字 <jsp:setProperty name="JavaBean实例名" property="*" /> (跟表单相关联)自动匹配所有属性 <jsp:setProperty name="JavaBean实例名" property="JavaBean属性名" /> (跟表单相关联) <jsp:setProperty name="JavaBean实例名" property="JavaBean属性名" value="BeanValue" /> (手工设置) <jsp:setProperty name="JavaBean实例名" property="JavaBean属性名" param="request对象中的参数名" /> (跟request参数相关联)URL地址栏传递 <jsp:getProperty name="" property="">
<body> <jsp:useBean id="myUser" class="com.po.User" scope="request" /> <%-- <jsp:setProperty property="*" name="myUser"/> --%> <%-- <jsp:setProperty property="username" name="myUser"/> --%> <jsp:setProperty property="username" name="myUser" value="xiaobai"/> <jsp:setProperty property="password" param="pwd" name="myUser"/> 用户名:<%=myUser.getUsername()%><br> 密码:<%=myUser.getPassword()%> </body>
Javabean四个作用域范围:
page,request,session,application
<jsp:getProperty>标签调用时,将会按照page、request、session和application的顺序来查找这个JavaBean实例,直至找到一个实例对象为止,如果在这4个范围内都找不到JavaBean实例,则抛出异常。
<body> <jsp:useBean id="myUser" class="com.po.User" scope="page"></jsp:useBean> 用户名:<jsp:getProperty property="username" name="myUser"/> 密码:<jsp:getProperty property="password" name="myUser"/> <hr> <%-- 用户名:<%=((User)application.getAttribute("myUser")).getUsername() %> --%> <%-- 密码:<%=((User)application.getAttribute("myUser")).getPassword() %> --%> <%-- 用户名:<%=((User)session.getAttribute("myUser")).getUsername() %> --%> <%-- 密码:<%=((User)session.getAttribute("myUser")).getPassword() %> --%> <%-- 用户名:<%=((User)request.getAttribute("myUser")).getUsername() %> --%> <%-- 密码:<%=((User)request.getAttribute("myUser")).getPassword() %> --%> 用户名:<%=((User)pageContext.getAttribute("myUser")).getUsername() %> 密码:<%=((User)pageContext.getAttribute("myUser")).getPassword() %> </body>
Model1
三层结构:界面层(jsp页面) 业务逻辑层(javabean) 数据层(数据库)
就是将业务逻辑封装起来而不是全部写在JSP界面。
package com.dao; import com.po.Users; public class UsersDao { public boolean usersLogin(Users u) { if ("admin".equals(u.getUsername()) && "admin".equals(u.getPassword())) return true; return false; } }
<%@ page language="java" import="java.util.*" contentType="text/html; charset=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+"/"; request.setCharacterEncoding("utf-8"); if (userDao.usersLogin(loginUser)) { session.setAttribute("username", loginUser.getUsername()); request.getRequestDispatcher("login_success.jsp").forward(request, response); } else { response.sendRedirect("login_failure.jsp"); } %>
2.JSP状态管理
HTTP协议的无状态性:无状态是指,当浏览器发送请求给服务器的时候,服务器会响应。但当同一个浏览器再次发送请求时,服务器不会知道是刚才那个浏览器。简单说就是服务器不会保存用户状态,不会记得客户端是否访问过,所以这就是无状态协议
保存用户状态的两大机制:1.Session 2.Cookie
Cookie是文本信息,保存在客户端。
作用:1.保存用户对象的追踪; 2.保存用户网页浏览记录与习惯; 3.简化登录;
but有泄露用户隐私的风险
创建与使用Cookie:
创建Cookie对象: Cookie cookie=new Cookie(String key,Object value); 写入Cookie: response.addCookie(cookie); 读取Cookie: Cookie[] cookies=request.getCookies(); setMaxAge( expiry ) 设置cookie的有效期,以秒为单位 getMaxAge() 获取cookie的有效时间,以秒为单位 setValue(String value) 在cookie创建后,对cookie进行赋值 getValue() 获取cookie的值 getName() 获取cookie的名称
<%@page import="java.net.URLDecoder"%> <%@ 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> <% request.setCharacterEncoding("utf-8"); String username = ""; String password = ""; Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie c: cookies) { if ("username".equals(c.getName())) { username = URLDecoder.decode(c.getValue(), "utf-8"); } if ("password".equals(c.getName())) { password = URLDecoder.decode(c.getValue(), "utf-8"); } } } %> <body> <h1>用户登录</h1> <hr> <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> <% request.setCharacterEncoding("utf-8"); String[] isUserCookies = request.getParameterValues("isUseCookie"); if (isUserCookies != null && isUserCookies.length > 0) { //使用URLEncoder解决无法在Cookie当中保存中文字符串问题 String username = URLEncoder.encode(request.getParameter("username"),"utf-8"); String password = URLEncoder.encode(request.getParameter("password"),"utf-8"); Cookie usernameCookie = new Cookie("username", username); Cookie passwordCookie = new Cookie("password", password); usernameCookie.setMaxAge(864000);//10 days passwordCookie.setMaxAge(864000); response.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); 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>
Cookie和Session的区别
3.JSP指令与动作
include指令: <%@ include file="URL"%>
include动作: <jsp:include page="URL" flush="true|false" /> flush是否从缓冲区读取。
(ps:import里面不要加分号 ~~~>_<~~~
forward动作: <jsp:forward page="URL" />
等同于: request.getRequestDispatcher("/url").forward(request,response);
param动作: <jsp:param name="参数名" value="参数值">
常常与<jsp:forward>一起使用,作为其子标签,可以复制给已有参数,也可以添加新的参数。
<jsp:forward page="user.jsp"> <jsp:param value="admin@123.net" name="email"/> <jsp:param value="xiaoshagua" name="username"/> </jsp:forward>
tomcat高版本:response.addCookie(cookie)会报java.lang.IllegalArgumentException;因为Cookie对象的构造函数的两个字符串参数:Cookie名字和Cookie值都不能包含空白字符以及下列字符:[ ] ( ) < > = , " / ? @ : 具体改detials.jsp中的,将+“,”改为加"#";
package dao; import java.sql.*; import java.util.ArrayList; import entity.Items; import util.DBHelper; // 商品的业务逻辑类 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;"; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { Items items = new Items(); items.setId(rs.getInt("id")); items.setName(rs.getString("name")); items.setCity(rs.getString("city")); items.setNumber(rs.getInt("number")); items.setPicture(rs.getString("picture")); items.setPrice(rs.getInt("price")); list.add(items); // 商品加入集合 } return list; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } public Items getItemById(int id) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DBHelper.getConnection(); String sql = "Select * from items where id = ?;"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if (rs.next()) { Items items = new Items(); items.setId(rs.getInt("id")); items.setName(rs.getString("name")); items.setCity(rs.getString("city")); items.setNumber(rs.getInt("number")); items.setPicture(rs.getString("picture")); items.setPrice(rs.getInt("price")); return items; } return null; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } //最近浏览的商品细信息 public ArrayList<Items> getViewList(String list) { ArrayList<Items> itemlist = new ArrayList<Items>(); if (list != null && list.length() > 0) { String arr[] = list.split("#"); for (int i = arr.length-1; i >= 0 && i >= arr.length-5; i--) { int id = Integer.parseInt(arr[i]); itemlist.add(getItemById(id)); } return itemlist; } return null; } public static void main(String[] args) { ItemsDAO i = new ItemsDAO(); i.getViewList("1#4#6"); } }
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <%@ page import="dao.ItemsDAO" %> <%@ page import="entity.Items" %> <% 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"><a href="details.jsp?id=<%=item.getId() %>"><%=item.getName() %></a></dd> <dd class="dd_city">产地:<%=item.getCity() %> 价格:¥<%=item.getPrice() %></dd> </dl> </div> <% } %> </table> </center> </body> </html>
<%@ 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.getItemById(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> <% } else { out.print("null!"); } %> <!-- 循环结束 --> <% String list = ""; // 从客户端获取Cookie集合 Cookie[] cookies = request.getCookies(); // 遍历 是否存在ListViewCookie if (cookies != null && cookies.length > 0) { for (Cookie c: cookies) { if (c.getName().equals("ListViewCookie")) { list = c.getValue(); } } } list += request.getParameter("id") + "#"; // 浏览记录过多清零 String arr[] = list.split("#"); if (arr != null && arr.length >= 1000) { list = ""; } // 存在同名的Cookie会覆盖前一个 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) { 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() %> 价格:<%=i.getPrice() %> ¥ </dd> </dl> </div> <!-- 循环结束 --> <% } } %> </td> </tr> </table> </center> </body> </html>