目录

一.什么是JavaBean?

二.为什么需要JavaBean?

三.如何在JavaWeb中创建Java文件

四.完成模糊查询

   1.封装连接数据库语句(放在dao包下方,DBHeper类)

   2.在pojo包下创建一个新闻实体类

   3.在dao包下方,创建操作类

   4.去新闻系统中的新闻首页操作

总结


一.什么是JavaBean?

  JavaBean泛指的就是Java对象

  Java:可以理解为是豆荚    Bean:豆子

二.为什么需要JavaBean?

  • 解决代码重复编写,减少代码冗余
  • 功能区分明确,避免业务逻辑处理与页面显示处理集中在一起造成混乱
  • 提高了代码的维护性

三.如何在JavaWeb中创建Java文件

1.点击mian文件(一般情况下mian文件下方自带一个Java文件),鼠标右键,点击new,点击other,搜索package,新建一个包,在点击package鼠标右键,new---->other--->class,新建一个class。(就和java文件创建的过程一样)

注:如果main下方没有Java文件,可以直接点到src/main/java鼠标右键,新建package,在新建class,就和java建文件一样。

 

新建javabean类 怎么创建javabean_html


四.完成模糊查询

思路:

   1.封装连接数据库语句(放在dao包下方,DBHeper类)

   代码如下:

package ulit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import oracle.jdbc.driver.OracleDriver;

public class DBHeper {
     static{
    	 try {
    		 Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
     }
     
     //定义连接字符创
     public static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
     
     //获得连接
     public static Connection getCon() {
    	 try {
    		 return DriverManager.getConnection(URL,"scott","zking123"); 
		} catch (Exception e) {
			e.printStackTrace();
		}
    	  return null;
     }
     
   //关闭资源
     public static void getColse(Connection con,PreparedStatement ps,ResultSet rs) {
    	try {
    	if(con!=null&&con.isClosed())con.close();
       	 if(ps!=null)ps.close();
       	 if(rs!=null)rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	 
     }
     
}

2.在pojo包下创建一个新闻实体类

  代码如下:

package pojo;

import java.io.Serializable;

public class News  implements Serializable{
      
	private int news_id;
	private String news_title;
	private int  news_topic;
	private String news_author;
	private String news_publisher;
	private String news_contet;
	private  String news_cover;
	private int news_count;
	public int getNews_id() {
		return news_id;
	}
	public void setNews_id(int news_id) {
		this.news_id = news_id;
	}
	public String getNews_title() {
		return news_title;
	}
	public void setNews_title(String news_title) {
		this.news_title = news_title;
	}
	public int getNews_topic() {
		return news_topic;
	}
	public void setNews_topic(int news_topic) {
		this.news_topic = news_topic;
	}
	public String getNews_author() {
		return news_author;
	}
	public void setNews_author(String news_author) {
		this.news_author = news_author;
	}
	public String getNews_publisher() {
		return news_publisher;
	}
	public void setNews_publisher(String news_publisher) {
		this.news_publisher = news_publisher;
	}
	public String getNews_contet() {
		return news_contet;
	}
	public void setNews_contet(String news_contet) {
		this.news_contet = news_contet;
	}
	public String getNews_cover() {
		return news_cover;
	}
	public void setNews_cover(String news_cover) {
		this.news_cover = news_cover;
	}
	public int getNews_count() {
		return news_count;
	}
	public void setNews_count(int news_count) {
		this.news_count = news_count;
	}
	
	
	@Override
	public String toString() {
		return "News [news_id=" + news_id + ", news_title=" + news_title + ", news_topic=" + news_topic
				+ ", news_author=" + news_author + ", news_publisher=" + news_publisher + ", news_contet=" + news_contet
				+ ", news_cover=" + news_cover + ", news_count=" + news_count + "]";
	}
	

	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		News other = (News) obj;
		if (news_author == null) {
			if (other.news_author != null)
				return false;
		} else if (!news_author.equals(other.news_author))
			return false;
		if (news_contet == null) {
			if (other.news_contet != null)
				return false;
		} else if (!news_contet.equals(other.news_contet))
			return false;
		if (news_count != other.news_count)
			return false;
		if (news_cover == null) {
			if (other.news_cover != null)
				return false;
		} else if (!news_cover.equals(other.news_cover))
			return false;
		if (news_id != other.news_id)
			return false;
		if (news_publisher == null) {
			if (other.news_publisher != null)
				return false;
		} else if (!news_publisher.equals(other.news_publisher))
			return false;
		if (news_title == null) {
			if (other.news_title != null)
				return false;
		} else if (!news_title.equals(other.news_title))
			return false;
		if (news_topic != other.news_topic)
			return false;
		return true;
	}
	
	
	public News() {
		
	}
	
	public News(int news_id, String news_title, int news_topic, String news_author, String news_publisher,
			String news_contet, String news_cover, int news_count) {
		super();
		this.news_id = news_id;
		this.news_title = news_title;
		this.news_topic = news_topic;
		this.news_author = news_author;
		this.news_publisher = news_publisher;
		this.news_contet = news_contet;
		this.news_cover = news_cover;
		this.news_count = news_count;
	}
	

	
	
	
}

3.在dao包下方,创建操作类

 代码如下: 

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import pojo.News;
import pojo.User;
import ulit.DBHeper;



public class Dao {
    private Connection con;
    private PreparedStatement ps;
    private ResultSet rs;
    
    //模糊查询
    public List<News> selectLsit(String name){
    	List<News> list=new ArrayList<News>();
    	try {
    		con=DBHeper.getCon();
        	ps=con.prepareStatement("select * from jw05_news where  news_title like ?");
        	ps.setString(1,"%"+name+"%");
        	rs=ps.executeQuery();
        	while(rs.next()) {
        		News news=new News();
        		news.setNews_id(rs.getInt(1));
        		news.setNews_title(rs.getString(2));
        		news.setNews_topic(rs.getInt(3));
        		news.setNews_author(rs.getString(4));
        		news.setNews_publisher(rs.getString(5));
        		news.setNews_contet(rs.getString(6));
        		news.setNews_cover(rs.getString(7));
        		news.setNews_count(rs.getInt(8));
        		list.add(news);
        	}
            
		} catch (Exception e) {
		e.printStackTrace();
		}finally {
			DBHeper.getColse(con, ps, rs);
		}
    	return list;
    	
    }
	
    
    //查询用户表
    //根据用户名和密码查询数据
    public User select(User u) {
    	try {
			con=DBHeper.getCon();
			ps=con.prepareStatement("select * from jw05_user where uname=? and upwd=?");
			ps.setString(1,u.getUsername());
			ps.setString(2,u.getUserpwd());
			rs=ps.executeQuery();
			while(rs.next()) {
				User user=new User();
				user.setUserid(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setUserpwd(rs.getString(3));
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHeper.getColse(con, ps, rs);
		}
    	return null;
    }
    
    //删除新闻
    public int del(int id) {
    	try {
			con=DBHeper.getCon();
			ps=con.prepareStatement("delete from jw05_news where news_id=?");
			ps.setInt(1, id);
			return ps.executeUpdate();
			
					
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHeper.getColse(con, ps, rs);
		}
    	return 0;
    }
}

   4.去新闻系统中的新闻首页操作

     代码如下:    

<%@page import="pojo.News"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@page import="dao.Dao"%>
<%@page import="ulit.DBHeper"%>
<%@page import="java.nio.charset.StandardCharsets"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@ 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 name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/JavaWeb05/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="/JavaWeb05/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="/JavaWeb05/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>
<%
//当用户为空,返回登录界面
 Object name=session.getAttribute("username");
if(name==null){
	response.sendRedirect("web07/login.jsp");
}
%>

<body>
<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="/JavaWeb07/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><%=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>

<ol class="breadcrumb">
    <li>您当前的位置是</li>
    <li>新闻发布系统</li>
    <li class="active">首页</li>
     <li>在线人数:<%=application.getAttribute("count") %></li>
</ol>

<form action="${pageContext.request.contextPath}/news/index.jsp" class="form-inline" style="margin: 0px auto 20px; mothod="post";>
    <div class="form-group" style="display: block;text-align: center;">
        <div class="input-group">
            <div class="input-group-addon">新闻标题</div>
            <input name="newsName" type="text" class="form-control" placeholder="请在此输入搜索的关键字">
            <span class="input-group-btn">
                    <button type="submit" class="btn btn-primary">搜索🔍</button>
                </span>
        </div>
    </div>
</form>

 <%
  
   String newsName=request.getParameter("newsName");
    //判断newsName
    //如果为null值,设置为空字符串
    if(newsName==null){
    	newsName="";
    }
    
 
  //获得连接对象
  Connection con=DBHeper.getCon();
  Dao dao=new Dao();
  List<News> news=dao.selectLsit(newsName);
  for(News n:news){
	  

%>
  <li class="list-group-item">
            <h4 class="list-group-item-heading">
                <a href="${pageContext.request.contextPath}/news/read.jsp?newId=<%=n.getNews_id()%>" data-placement="bottom" data-toggle="tooltip" href="" title="国家卫健委:昨日新增确诊病例29例,其中本土病例2例">
                    <%=n.getNews_title()%>
                </a>
            </h4>
            <p class="list-group-item-text text-right">
                <span class="glyphicon glyphicon-user"><code><%=n.getNews_author()%></code></span>
                <span class="glyphicon glyphicon-eye-open"><code><%=n.getNews_count()%></code></span>
                <span class="glyphicon glyphicon-tag"><code>1000</code></span>
                <span class="glyphicon glyphicon-time"><code><%=n.getNews_publisher()%></code></span>
            </p>
        </li>
        <%
        
            }
  
        %>
    </ul>
<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>

总结

     JavaBean的封装可以减少我们一些重复的代码,就列如我们连接数据库语句,大家去看原先的新闻系统,基本上每一个文件中,都需要写一遍连接数据库语句,而当我们去封装了连接数据库代码,我们只需要调用,减少我们的代码量。