Javabeans就是符合某种特定的规范的Java类。使用Javabeans的好处是解决代码重复编写,减少代码冗余,功能区分明确,提高了代码的维护性。
- 是一个共有的类
- 属性是私有的
- 属性全部用get、set方法封装
- 包含无参的共有构造方法
Jsp动作元素(action elements),动作元素为请求处理阶段提供信息。动作元素遵循XML元素的基本语法,有一个包含元素名的开始标签,可以有属性、可选内容、与开始标签匹配的结束标签。
通过对象的get、set方式使用Javabean
<body>
<%
//获取javabean对象
Users user = new Users();
user.setUsername("admin");
user.setPassword("123456");
%>
<h1>使用普通方式创建javabean的实例h1>
用户名:<%=user.getUsername() %><br>
密码:<%=user.getPassword() %><br>
body>
<body>
<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
<h1>setProperty动作元素h1><hr>
<%--
property ="*" name="myUsers"/>
--%>
<%--
property ="username" name="myUsers"/>
--%>
<%--
property ="username" name="myUsers" value="lisi"/>
property="password" name="myUsers" value="888888"/>
--%>
<jsp:setProperty property="username" name="myUsers" />
<jsp:setProperty property="password" name="myUsers" param="mypass"/>
用户名:<jsp:getProperty property="username" name="myUsers"/><br>
密码:<jsp:getProperty property="password" name="myUsers"/><br>
<a href="testScope.jsp">测试javabean的四个作用范围a>
<%
//request.getRequestDispatcher("testScope.jsp").forward(request, response);
%>
<body>
<h1>Javabean的四个作用范围h1><br>
<%--
"myUsers" class="com.po.Users" scope="application"/>
用户名:property="username" name="myUsers"/>
密码:property="password" name="myUsers"/>
--%>
<%--
用户名:<%=((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>
Model1模型出现之前,整个Web应用几乎全部由JSP页面组成,JSP页面接收处理客户端请求,对请求处理后直接做出响应。
弊端:在页面层充斥着大量的业务逻辑代码和数据访问层代码,Web程序的可拓展性和可维护性非常差。
Javabean的出现可以使jsp页面中使用Javabean封装的数据或者调用Javabean的业务逻辑代码,这样大大提升了程序udall可维护性。
使用JSP+Javabean实现简单用户登录
<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>
<%@ 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+"/";
if(userDAO.usersLogin(loginUser))
{
session.setAttribute("loginUser", loginUser.getUsername());
request.getRequestDispatcher("login_success.jsp").forward(request, response);
}
else
{
response.sendRedirect("login_failure.jsp");
}
%>
3.UsersDAO.java
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;
}else{
return false;
}
}
}
中文名称为“小甜饼”,是Web服务器保存在客户端的一系列文本信息。
- 典型应用1:判定注册用户是否已经登陆网站
- 典型应用2:“购物车”的处理
作用:
1. 对特定象的追踪
2. 保存用户网页浏览记录与习惯
3. 简化登录
风险:容易泄漏用户信息
void setMaxAge(int expiry);//设置cookie有效期,以秒为单位
int getMaxAge();//获取cookie的有效时间,以秒为单位
void setValue(String value);//在cookie创建后,对cookie进行赋值
String getValue();//获取cookie的值
String getName();//获取cookie的名称
用cookie实现登陆时记住密码功能
<body>
<h1>用户登录h1>
<hr>
<%
//如果保存了cookie(记住了密码),再次登录时将其显示出来
request.setCharacterEncoding("utf-8");
String username = "";
String password = "";
//用request对象获得所有cookie对象
Cookie[] cookies = request.getCookies();
//如果存在cookie对象则遍历每一个cookie对象,
//找到对象中存在key值为username或password的对象,然后得到相应的value值
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>
<body>
<h1>登录成功h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
//首先判断用户是否选择了记住登录状态
String[] isUseCookies = request.getParameterValues("isUseCookie");
if(isUseCookies!=null&&isUseCookies.length>0)
{
//得到表单提交的用户名和密码
String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
//使用URLEncoder解决无法在Cookie当中保存中文字符串问题
String password = URLEncoder.encode(request.getParameter("password"),"utf-8");
//如果选择了则把用户名和密码保存在Cookie对象里面
Cookie usernameCookie = new Cookie("username",username);
Cookie passwordCookie = new Cookie("password",password);
usernameCookie.setMaxAge(864000);
passwordCookie.setMaxAge(864000);//设置最大生存期限为10天
//用response保存cookie
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); //设置Cookie失效
response.addCookie(c); //重新保存。
}
}
}
}
%>
body>
//include指定
<%@ include file = "data.jsp"%>
//include动作
include page = "data.jsp" flush = "false"/>
"data.jsp"/>
//等同于请求重定向
request.getRequestDispatcher("/url").forward(request,response);
<body>
<h1>param动作h1>
<jsp:forward page="user.jsp">
<jsp:param value="[email protected]" name="email"/>
<jsp:param value="888888" name="password"/>
jsp:forward>
body>
<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>
使用Model1思想、cookie技术和JDBC知识,实现最近浏览商品功能的实现
public class DBHelper {
//连接数据库的URL地址
private static final String DRIVER = "com.mysql.jdbc.Driver";
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 ="123";
private static Connection conn=null;
//静态代码块负责加载驱动
static
{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception
{
if(conn==null)
{
conn = (Connection) 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 e) {
e.printStackTrace();
}
}
}
//商品类(与数据库的商品表对应)
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;
}
}
1.设计得到所欲商品的方法
// 获得所有商品的信息(得到所有商品)
public ArrayList getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
// 商品集合
ArrayList list = new ArrayList();
try {
conn = DBHelper.getConnection();
String sql = "select * from items;";
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.setPicture(rs.getString("picture"));
item.setPrice(rs.getInt("price"));
list.add(item);// 把一个商品加入集合
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2.设计根据ID得到对应商品的方法
// 根据商品编号获取商品资料(根据ID得到对应的商品)
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=?;";
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.setPicture(rs.getString("picture"));
item.setPrice(rs.getInt("price"));
return item;
}else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.设计得到最近浏览的五条商品的方法
// 获取最近浏览的前五条商品信息
public ArrayList getViewList(String list) {
ArrayList itemlist = new ArrayList();
int iCount=5;//每次返回前五条记录
if (list!=null&&list.length()>0) {
//根据逗号分隔
String[] arr = list.split(",");
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 import="entity.Items"%>
<%@page import="dao.ItemsDAO"%>
<%@ 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+"/";
%>
"-//W3C//DTD HTML 4.01 Transitional//EN">
"<%=basePath%>">
My JSP 'index.jsp' starting page
"750" height="60" cellpadding="0" cellspacing="0" border="0">
<%
ItemsDAO itemsDao = new ItemsDAO();
ArrayList list = itemsDao.getAllItems();
if(list!=null&&list.size()>0){
for(int i=0;i
-
"details.jsp?id=<%=item.getId()%>">"images/
<%=item.getPicture() %>" width="120" height="90" border="1"/>
- "dd_name"><%=item.getName() %>
- "dd_city">产地:<%=item.getCity() %>
价格:¥<%=item.getPrice() %>
<%
}
}
%>
商品详情页:
<body>
<h1>商品详情h1>
<hr>
<center >
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<%
ItemsDAO itemsDao = new ItemsDAO();
Items item = itemsDao.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>
<td><B><%=item.getName()%>B>td>
tr>
<tr>
<td>产地:<%=item.getCity() %>td>
tr>
<tr>
<td><B>价格:<%=item.getPrice() %>¥B>td>
tr>
table>
td>
<%
}
%>
<%
String list = "";
//从客户端获得cookies集合
Cookie[] cookies = request.getCookies();
//遍历该集合
if(cookies!=null&&cookies.length>0){
for(Cookie c:cookies){
//查看是否已经保存有名为ListViewCookie的cookie
if(c.getName().equals("ListViewCookie")){
//有责把其值赋给list
list = c.getValue();
}
}
}
//追加当前商品编号
list+=request.getParameter("id")+",";
//如果浏览记录超过1000条,清零
String[] arr = list.split(",");
if(arr!=null&&arr.length>0){
if(arr.length>=1000){
list="";
}
}
//在把list重新添加到名为ListViewCookie的cookie对象中
//其实cookie/list中存储的就是一串id
Cookie cookie = new Cookie("ListViewCookie",list);
//条cookie对象
response.addCookie(cookie);
%>
<td width="30%" bgcolor="#EEE" align="center">
<br>
<b>您浏览过的商品b><br>
<%
ArrayList itemlist = itemsDao.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"/>a>
dt>
<dd class="dd_name"><%=i.getName() %>dd>
<dd class="dd_city">产地:<%=i.getCity() %> 价格:<%=i.getPrice() %>¥dd>
dl>
div>
<%
}
}
%>
tr>
table>
center>
body>
html>