一、JSP内置对象application
application类似于系统的“全局变量”,用于实现用户之间的数据共享。application对象用于保存应用程序的公用数据,服务器启动并自动创建application对象后,只要没有关闭服务器,application对象就一直存在,所有用户共享application对象。
application对象的常用方法:
void setAttribute(String key, Object value):以键/值的方式,将一个对象的值存放到application中
Object getAttribute(String key):根据键去获取application中存放对象的值
application创建以后 在一个应用服务器范围内有效,当应用服务启动后即创建该对象,并向所有用户所共享
案例:显示在线人数
<%@page language="java" contentType="text/html; charset=UTF-8"%>
<%
//怎么判断一个用户有没有登录
Object username = session.getAttribute("username");
if (username == null) {
response.sendRedirect("/web04/login.jsp");
}
%>
<nav class="navbar navbar-default hidden-sm hidden-xs">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.jsp" style="font-size: 25px;">点我</a>
</div>
<ul class="nav navbar-nav">
<li class="dropdown"><a class="dropdown-toggle"
data-toggle="dropdown"> 新闻管理 <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="/web04/news/add.jsp">新闻发布</a></li>
<li class="divider"></li>
<li><a href="/web04/news/show.jsp">类别管理</a></li>
</ul></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a>在线人数:<%=application.getAttribute("count")%></a></li>
<li><a><%=session.getAttribute("username")%></a></li>
<li><a
href="${pageContext.request.contextPath}/news/history.jsp">历史记录</a></li>
<li><a href="${pageContext.request.contextPath}/news/doExit.jsp">退出<span
class="glyphicon glyphicon-off"></span></a></li>
</ul>
</div>
</nav>
处理登录界面
<%@page import="com.zking.util.DBHelper"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="oracle.jdbc.driver.OracleDriver"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String yh=request.getParameter("yh");
String mm=request.getParameter("mm");
//获得连接
Connection con=DBHelper.getCon();
//获得执行对象
PreparedStatement ps=con.prepareStatement("select * from tb_user where user_name=? and user_pwd=?");
ps.setString(1, yh);
ps.setString(2,mm);
//获得结果集
ResultSet rs=ps.executeQuery();
//判断结果
if(rs.next()){
//调用用户存入到服务器的session中
session.setAttribute("username", yh);
//计算当前人数(不是存在卡里面,而是整个银行)
Object obj=application.getAttribute("count");
if(obj==null){
obj=0;
}
Integer count=(Integer)obj;
count++;//人数+1
application.setAttribute("count",count);
//cookie每次发送请求会被自动带上
//cookie默认是在你当前服务器打开的过程中生效的
Cookie cookie1=new Cookie("yh",yh);
//设置存活时间 s
//-1是在你当前浏览器打开的过程中生效
Cookie cookie2=new Cookie("mm",mm);
cookie1.setMaxAge(60*60*24*7);//设置用户名的时间
cookie2.setMaxAge(60*60*24*7);//设置密码的时间
//存到前台
response.addCookie(cookie1);
response.addCookie(cookie2);
response.sendRedirect("news/index.jsp");
// request.getRequestDispatcher("/news/index.jsp").forward(request,response);
}else{
//重定向 客户端
/**
(localhost:8080/web04/)跳转的时候:
a.jsp 跳转到当前(同级)路径下的a.jsp (localhost:8080/web04/a.jsp)
../a.jsp 跳转到上一级路径下的a.jsp (localhost:8080/a.jsp)
/a.jsp 根目录的a.jsp(localhost:8080/a.jsp)
**/
response.sendRedirect("login.jsp");
}
//资源关闭
DBHelper.close(con, ps, rs);
%>
退出登录代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//session的存储时间
//session.setMaxInactiveInterval(60);
//怎么删除session
session.invalidate();
//调回登录页面
response.sendRedirect("/web04/login.jsp");
//让在线人数减1
Object obj=application.getAttribute("count");
Integer count=(Integer)obj;
count--;
application.setAttribute("count", count);
%>
二、JavaBean
JavaBean是特殊的Java类,使用Java语言书写,并且遵守JavaBean API规范。
JavaBean实际上是指一种特殊的Java类,它通常用来实现一些比较常用的简单功能,并可以很容易的被重用或者是插入其他应用程序中去。所有遵循“一定编程原则”的Java类都可以被称作JavaBean。
JavaBean是一个遵循特定写法的Java类,是一种Java语言编写的可重用组件,它的方法命名,构造及行为必须符合特定的约定:
- 这个类必须要有一个公共的无参构造函数
- 这个类中的所有属性都要私有化
- 私有化的属性要写public类型的方法(get,set)
- 可以实现Serializable接口
JavaBean的优势
- 解决代码重复编写,减少代码冗余
- 功能区分明确,避免业务逻辑处理与页面显示处理集中在一起造成混乱
- 提高了代码的维护性
JavaBean及其分类
符合规范的Java类都是JavaBean
JavaBean的分类
封装数据
- 按照OO原则,属性与数据库表字段相对应
- 属性私有
- 具有public的set/get方法
封装业务
- 具有实现特定功能的方法和方法实现
- 通常与一个封装数据的JavaBean对应
案例:使用JavaBean对新闻发布系统数据进行封装
DBHelper.java代码如下:
package com.zking.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBHelper {
// 加载驱动
static {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
e.printStackTrace();
}
}
// 定义连接字符串
private static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
//获得连接
public static Connection getCon(){
try {
return DriverManager.getConnection(URL,"SCOTT","123123");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭资源
*/
public static void close(Connection con,PreparedStatement ps,ResultSet rs) {
try {
if(!con.isClosed()) {
con.close();
}
ps.close();
rs.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
News.java代码如下:
package com.zking.pojo;
import java.io.Serializable;
public class News implements Serializable{
private int newsId;
private String newsTitle;
private int newsTopic;
private String newsAuthor;
private String newsPublisher;
private String newsContent;
private String newsCover;
private int newsCount;
private int newsMarker;
public int getNewsId() {
return newsId;
}
public void setNewsId(int newsId) {
this.newsId = newsId;
}
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public int getNewsTopic() {
return newsTopic;
}
public void setNewsTopic(int newsTopic) {
this.newsTopic = newsTopic;
}
public String getNewsAuthor() {
return newsAuthor;
}
public void setNewsAuthor(String newsAuthor) {
this.newsAuthor = newsAuthor;
}
public String getNewsPublisher() {
return newsPublisher;
}
public void setNewsPublisher(String newsPublisher) {
this.newsPublisher = newsPublisher;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
public String getNewsCover() {
return newsCover;
}
public void setNewsCover(String newsCover) {
this.newsCover = newsCover;
}
public int getNewsCount() {
return newsCount;
}
public void setNewsCount(int newsCount) {
this.newsCount = newsCount;
}
public int getNewsMarker() {
return newsMarker;
}
public void setNewsMarker(int newsMarker) {
this.newsMarker = newsMarker;
}
@Override
public String toString() {
return "News [newsId=" + newsId + ", newsTitle=" + newsTitle + ", newsTopic=" + newsTopic + ", newsAuthor="
+ newsAuthor + ", newsPublisher=" + newsPublisher + ", newsContent=" + newsContent + ", newsCover="
+ newsCover + ", newsCount=" + newsCount + ", newsMarker=" + newsMarker + "]";
}
public News(int newsId, String newsTitle, int newsTopic, String newsAuthor, String newsPublisher, String newsContent,
String newsCover, int newsCount, int newsMarker) {
super();
this.newsId = newsId;
this.newsTitle = newsTitle;
this.newsTopic = newsTopic;
this.newsAuthor = newsAuthor;
this.newsPublisher = newsPublisher;
this.newsContent = newsContent;
this.newsCover = newsCover;
this.newsCount = newsCount;
this.newsMarker = newsMarker;
}
public News() {
super();
}
}
NewsDao.java代码如下:
package com.zking.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zking.pojo.News;
import com.zking.util.DBHelper;
public class NewsDao {
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
public List<News> queryByName(String newName) {
List<News>list=new ArrayList<News>();
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select * from t_news where news_title like ?");
ps.setString(1, "%"+newName+"%");
rs=ps.executeQuery();
while(rs.next()){
News news=new News();
// 給新聞对象赋值
news.setNewsId(rs.getInt(1));
news.setNewsTitle(rs.getString(2));
news.setNewsTopic(rs.getInt(3));
news.setNewsAuthor(rs.getString(4));
news.setNewsPublisher(rs.getString(5));
news.setNewsContent(rs.getString(6));
news.setNewsCover(rs.getString(7));
news.setNewsCount(rs.getInt(8));
news.setNewsMarker(rs.getInt(9));
// 将新闻对象添加到集合中
list.add(news);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.close(con, ps, rs);
}
return list;
}
}
这些写完后 然后就可以对之前写的代码进行简化 首页代码简化后的代码如下:
<%@page import="com.zking.pojo.News"%>
<%@page import="com.zking.dao.NewsDao"%>
<%@page import="java.nio.charset.StandardCharsets"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>bootstrap</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link
href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css"
rel="stylesheet">
<script
src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
<script
src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<style>
* {
outline: none !important;
}
body, html {
background: #7f8d90;
}
nav, .breadcrumb {
border-radius: 0px !important;
margin-bottom: 0px !important;
}
.breadcrumb {
margin-bottom: 20px !important;
background: #36485c;
color: white;
}
li h4 {
width: 300px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.breadcrumb .active {
color: yellow;
}
</style>
</head>
<body>
<%@include file="top.jsp" %>
<ol class="breadcrumb">
<li>您当前的位置是</li>
<li>新闻发布系统</li>
<li class="active">首页</li>
</ol>
<form action="${pageContext.request.contextPath}/news/index.jsp"
class="form-inline" style="margin: 0px auto 20px;">
<div class="form-group" style="display: block; text-align: center;">
<div class="input-group">
<div class="input-group-addon">新闻标题</div>
<input name="newName" class="form-control" placeholder="请在此输入搜索的关键字"
type="text"> <span class="input-group-btn">
<button class="btn btn-primary" type="submit">搜索🔍</button>
</span>
</div>
</div>
</form>
<div class="container">
<ul class="list-group">
<%
//点击了表单之后 跳转的是当前这个页面 同时携带一个newName(查询的关键字)过来
String newName = request.getParameter("newName");
if (newName == null) {
newName = "";//查询所有
}
//破碎重组
//newName=new String(newName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
for(News news:new NewsDao().queryByName(newName)){
%>
<li class="list-group-item">
<h4 class="list-group-item-heading">
<a
href="${pageContext.request.contextPath}/news/read.jsp?newId=<%=news.getNewsId()%>"
data-placement="bottom" data-toggle="tooltip" href=""
title="国家卫健委:昨日新增确诊病例29例,其中本土病例2例"> <%=news.getNewsTitle()%>
</a>
</h4>
<p class="list-group-item-text text-right">
<span class="glyphicon glyphicon-user"><code><%=news.getNewsAuthor()%></code></span>
<span class="glyphicon glyphicon-eye-open"><code><%=news.getNewsCount()%></code></span>
<span class="glyphicon glyphicon-tag"><code><%=news.getNewsMarker()%></code></span>
<span class="glyphicon glyphicon-time"><code><%=news.getNewsPublisher()%></code></span>
</p>
</li>
<%
}
%>
</ul>
</div>
<div class="container text-center">
<ul class="pagination" style="margin: 20px auto;">
<li><a href="#"><span>«</span></a></li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#"><span>»</span></a></li>
</ul>
</div>
<script>
$(function() {
$('[data-toggle="tooltip"]').tooltip({
trigger : "hover"
})
})
</script>
</body>
</html>
今天的分享就到这里结束啦!!✌
以上就是Java application&&JavaBean封装的一些内容!!📖
感 谢 阅 读 ……