今天给大家讲解一下如何封装那些我们要写很多遍的代码。
目录
一、application
简介
application也是一种储存方式,跟session,cookie一样。但是也有不同之处,cookie是前端储存。session是会话级储存,session是储存在自己的电脑中,适合储存私有信息。application是应用级储存,及共享的储存,适合公共的信息储存。
application的案例:在线人数
当登录成功后,在线人数加一。
以下是登录处理界面 doLogin.jsp
<%@page import="com.xyz.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 t_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); //存放在后台
//-------------- 计算当前人数 -------------
//session相当于存在你的银行卡里面,而application是存在整个银行里面
Object obj=application.getAttribute("count");
if(obj==null){ //如果为null,将obj设为0
obj=0;
}
Integer count=(Integer)obj;
count++; //人数加一
application.setAttribute("count", count);
//cookie的值每次发送请求的时候会被自动带上
//cookie默认是在你当前浏览器打开的过程中生效
Cookie cookie1=new Cookie("yh",yh);
Cookie cookie2=new Cookie("mm",mm);
//设置存储时间 (单位是 s) 【七天免登录】
cookie1.setMaxAge(60*60*24*7);
cookie2.setMaxAge(60*60*24*7);
//cookie是存放到前台
response.addCookie(cookie1);
response.addCookie(cookie2);
//转发
//request.getRequestDispatcher("/news/index.jsp").forward(request, response);
//重定向
response.sendRedirect("news/index.jsp");
}else{
//重定向
response.sendRedirect("${pageContext.request.contextPath}/login.jsp");
}
//关闭资源
DBHelper.close(con, ps, rs);
%>
当退出登录时,当前人数减一
以下是退出处理界面 doExit
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//session的存储时间
//session默认与服务器共存
session.setMaxInactiveInterval(60);
//删除session
session.invalidate();
//跳回登录界面
response.sendRedirect("/web-05/login.jsp");
//让在线人数减一
Object obj=application.getAttribute("count");
Integer count=(Integer)obj;
count--;
application.setAttribute("count", count);
%>
二、JavaBean封装
1.JavaBean的简介
javaBean泛指java对象,JavaBean实际上是指一种特殊的Java类,它通常用来实现一些比较常用的简单功能,并可以很容易的被重用或者是插入其他应用程序中去。所有遵循“一定编程原则”的Java类都可以被称作JavaBean。
2.JavaBean的优势
1.解决代码重复编写,减少代码冗余
2.功能区分明确,避免业务逻辑处理与页面显示处理集中在一起造成混乱
3.提高了代码的维护性
3.Javabean封装代码
在这个java的src中建package,在package里建class
封装连接和关闭语句
package com.xyz.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
public class DBHelper {
//1.加载驱动
static {
//OracleDriver
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//2.定义连接字符串
private static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
//3.获得连接
public static Connection getCon() {
try {
return DriverManager.getConnection(URL,"scott","zkingedu");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//4.关闭资源
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();
}
}
}
封装查询
先来一个新闻的实体类
package com.xyz.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 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 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 + ", newsCount="
+ newsCount + ", newsMarker=" + newsMarker + "]";
}
public News(int newsId, String newsTitle, int newsTopic, String newsAuthor, String newsPublisher,
String newsContent, int newsCount, int newsMarker) {
super();
this.newsId = newsId;
this.newsTitle = newsTitle;
this.newsTopic = newsTopic;
this.newsAuthor = newsAuthor;
this.newsPublisher = newsPublisher;
this.newsContent = newsContent;
this.newsCount = newsCount;
this.newsMarker = newsMarker;
}
public News() {
// TODO Auto-generated constructor stub
}
}
再来一个新闻的操作类
package com.xyz.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xyz.pojo.News;
import com.xyz.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.setNewsCount(rs.getInt(7));
news.setNewsMarker(rs.getInt(8));
//将新闻对象添加到集合中
list.add(news);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBHelper.close(con, ps, rs);
}
return list;
}
}
鉴权的封装
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//判断用户有没有登录
Object username=session.getAttribute("username");
if(username==null){
response.sendRedirect("/web-05/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.html" 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="${pageContext.request.contextPath}/news/add.jsp">新闻发布</a></li>
<li class="divider"></li>
<li><a href="#">类别管理</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="history.jsp">历史记录</a></li>
<li><a href="doExit.jsp">退出<span class="glyphicon glyphicon-off"></span></a></li>
</ul>
</div>
</nav>
封装后,可以在我们需要鉴权的界面引入
<%@include file="XXX.jsp" %> 可以在jsp中引入其他的jsp文件
封装后的调用
<%@page import="com.xyz.util.DBHelper"%>
<%@page import="com.xyz.pojo.News"%>
<%@page import="com.xyz.dao.NewsDao"%>
<%@page import="java.nio.charset.StandardCharsets"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@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 包含 --%>
<%-- 引入鉴权 --%>
<%@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;" method="post">
<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过来(newname是查询关键字)
String newName=request.getParameter("newname");
if(newName==null){ //当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 data-placement="bottom" data-toggle="tooltip" href="${pageContext.request.contextPath}/news/read.jsp?newId=<%= news.getNewsId()%>" title="<%= news.getNewsTitle()%>">
<%= 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>
今天就分享到这啦