javaweb实验:Java Web综合应用开发__基于MVC模式

news2025/1/11 12:34:42

目录

  • 前言
  • 实验目的
  • 实验原理
  • 实验内容
  • 实验过程
    • 项目结构
    • 代码实现
    • Java代码
      • controller层
        • AddNewsServlet类
        • DeletrNewsServlet类
        • LoginServlet类
        • LogoutServlet类
        • QueryAllNewsServlet类
        • QueryNewsServlet类
        • RegisterServlet类
        • UpdateNewsServlet类
      • dao层
        • NewsDao类
        • UserDao类
      • daoimpl层
        • NewsDaoImpl类
        • UserDaoImpl类
      • entity层
        • News类
        • PageBean类
        • User类
      • service层
        • NewsService类
        • UserService类
      • serviceimpl层
        • NewsServiceImpl类
        • UserServiceImpl类
      • util层
    • jsp代码
        • addNews
        • displayNews
        • login
        • login_failure
        • queryAllNews
        • reg_failure
        • reg_success
        • register
        • updateNews
      • 配置web.xml
      • 成果
    • 分页查询
  • 总结

前言

本实验的目的是让学生掌握Java Web开发的基本原理和方法,以及MVC设计模式的应用。MVC是一种将程序分为三个部分的设计模式,即模型(Model)、视图(View)和控制器(Controller)。模型负责封装数据和业务逻辑,视图负责展示用户界面,控制器负责接收用户请求并调用模型和视图进行处理。MVC模式可以提高程序的可维护性、可扩展性和可重用性,是一种常用的Web开发模式。

本实验要求学生使用JSP、Servlet和JavaBean技术,实现一个简单的在线图书管理系统。该系统可以实现用户注册、登录、浏览图书、借阅图书、归还图书等功能。学生需要按照MVC模式,将程序分为三个层次,即数据访问层、业务逻辑层和表现层。数据访问层使用Druid连接池和JDBC技术,对MySQL数据库进行操作。业务逻辑层使用JavaBean封装数据和业务方法。表现层使用JSP和HTML构建用户界面,并使用Servlet作为控制器,接收用户请求并调用业务逻辑层进行处理。

本实验报告将详细介绍本实验的设计思路、实现步骤、运行结果和遇到的问题。希望通过本实验,学生能够深入理解Java Web开发的原理和方法,以及MVC设计模式的优势和应用。

实验目的

理解MVC模式,并能够熟练使用MVC模式,综合运用JSP、JavaBean(DAO模式)和Servlet等相关技术,进行Web应用程序的开发。

实验原理

关于MVC模式
MVC是一个设计模式,它强制性的使应用程序的输入、处理和输出分开。使用MVC设计模式被分成三个核心层:模型层、视图层、控制层。它们各自处理自己的任务。各层的任务如下:
模型层(Model):完成一个个独立的业务操作组件,一般都是以JavaBean的形式进行定义的。
控制层(Controller):此层由Servlet实现,负责所有的用户请求参数,判断请求参数是否合法,根据请求的类型调用JavaBean执行操作并将最终的处理结果交由显示层进行显示。
显示层(View):此层主要是负责接收Servlet传递的内容,并且调用JavaBean,将内容显示给用户。
如图1所示。使用MVC模式进行Web程序开发,是以Servlet为主体展开的,由Servlet接收所有的客户端请求,根据请求调用相应的JavaBean,并将所有的显示结果交给JSP完成。
在这里插入图片描述

实验内容

[贯穿项目] 使用MVC模式,综合运用JSP、JavaBean(DAO模式)和Servlet等相关技术,实现新闻管理系统。要求提供如下功能:用户登录,用户注册,新闻的增、查、改、删。
关于创建项目创建数据库等内容在此就不多赘述

实验过程

项目结构

在这里插入图片描述
在这里插入图片描述

代码实现

Java代码

controller层

AddNewsServlet类

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuc.ss.entity.News;
import nuc.ss.service.NewsService;
import nuc.ss.serviceimpl.NewsServiceImpl;

@WebServlet("/addNews")
public class AddNewsServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 1、解决编码问题
    	req.setCharacterEncoding("utf-8");
    	resp.setCharacterEncoding("utf-8");
    	resp.setContentType("text/html;charset=utf-8");
    	
    	//2、接受前台数据,并将前台数据封装成一个News对象
    	String title = req.getParameter("title");
    	String author = req.getParameter("author");
    	String content = req.getParameter("content");
    	String date_str = req.getParameter("enterdate");
    	String hot_str = req.getParameter("hot");
    	// String-->Util.Date
    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    	Date date;
    	int hot;
    	News news = null;
		try {
			date = df.parse(date_str);
			hot = Integer.parseInt(hot_str);			
	    	news = new News(0, title, author, content, date, hot);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		// 3、调用service层,然后传入news
		NewsService ns = new NewsServiceImpl();
		
		int n = ns.addNews(news);
		
		// 4、处理结果
    	if(n >0) {
    		//插入成功
    		resp.sendRedirect("queryAllNews"); 
    	}else {
    		// 插入失败
    		req.getRequestDispatcher("addNews.jsp").forward(req, resp);
    		
    	}

	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}

DeletrNewsServlet类

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuc.ss.service.NewsService;
import nuc.ss.serviceimpl.NewsServiceImpl;

@WebServlet("/deleteNews")
public class DeleteNewsServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 1、解决编码问题
    	req.setCharacterEncoding("utf-8");
    	//resp.setCharacterEncoding("utf-8");
    	resp.setContentType("text/html;charset=utf-8");
    	// 2、获取前台传过来的id
    	int id = Integer.parseInt(req.getParameter("id"));
    	// 3、调用Service层
    	NewsService ns = new NewsServiceImpl();
    	int n = ns.removeNews(id);
    	// 4、处理结果
    	if(n>0) {
    		//删除成功,则直接刷新页面
    		resp.sendRedirect("queryAllNews");
    	}else {
    		resp.getWriter().println("删除失败!");
    	}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}

LoginServlet类

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuc.ss.entity.User;
import nuc.ss.service.UserService;
import nuc.ss.serviceimpl.UserServiceImpl;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		//获取前台数据
	   request.setCharacterEncoding("UTF-8");
	   String id = request.getParameter("id");
	   String password = request.getParameter("password");
	   String remenber = request.getParameter("remenber");
	   String name;
	   if((!(name=check(id,password)).equals(""))){  //登录成功,跳转到成功页
			Cookie cookie;
		    System.out.println("remenber=" + remenber);// on, null
	   		if(remenber != null) {
		    		cookie = new Cookie("Cookie2020", id+"#"+password+"#"+remenber);
		    		cookie.setMaxAge(45);
		    		response.addCookie(cookie);
		    } else {
		    		cookie = new Cookie("Cookie2020", id+"#"+password+"#"+remenber);
		    		cookie.setMaxAge(0);
		    		response.addCookie(cookie); 	
		    }
	   		
	   		request.getSession().setAttribute("username", name);
	   		request.getSession().setMaxInactiveInterval(30);// 30秒
			response.sendRedirect("queryAllNews");
			
	   }else{              //登录失败,跳转到失败页
		   response.sendRedirect("login_failure.jsp");
	   }

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private String check(String userid, String userpwd){

		String uname = "";

		UserService us = new UserServiceImpl();
		User user = us.login(userid, userpwd);
		
		if(user != null){  //登录成功
			uname = user.getUname();
		}
		
		return uname;
	 }

}

LogoutServlet类

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	HttpSession session = request.getSession();
    	session.removeAttribute("username");
    	
    	//跳转到login.jsp
   		response.sendRedirect("login.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

QueryAllNewsServlet类

import nuc.ss.entity.News;
import nuc.ss.entity.PageBean;
import nuc.ss.service.NewsService;
import nuc.ss.serviceimpl.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/queryAllNews")
public class QueryAllNewsServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1、调用service层,查询新闻
		NewsService ns = new NewsServiceImpl();
		List<News> list = ns.queryAllNews();

		// 2、处理结果
		req.setAttribute("list", list);
    	req.getRequestDispatcher("queryAllNews.jsp").forward(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}

QueryNewsServlet类

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuc.ss.entity.News;
import nuc.ss.service.NewsService;
import nuc.ss.serviceimpl.NewsServiceImpl;

@WebServlet("/queryNews")
public class QueryNewsServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 1、解决编码问题
    	req.setCharacterEncoding("utf-8");
    	//resp.setCharacterEncoding("utf-8");
    	resp.setContentType("text/html;charset=utf-8");
    	
    	//2、接受前台数据
    	int id = Integer.parseInt(req.getParameter("id"));
    	int flag = Integer.parseInt(req.getParameter("flag"));
    	
    	// 3、调用service层,查询指定id的新闻信息
		NewsService ns = new NewsServiceImpl();
		
		News news = ns.queryOneNews(id);
		
		// 4、处理结果
		if(news != null) {
			req.setAttribute("news", news);
			if(flag == 1) {
				req.getRequestDispatcher("updateNews.jsp").forward(req, resp);
			}else {
				req.getRequestDispatcher("displayNews.jsp").forward(req, resp);	
			}
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}

RegisterServlet类

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuc.ss.entity.User;
import nuc.ss.service.UserService;
import nuc.ss.serviceimpl.UserServiceImpl;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码格式
		req.setCharacterEncoding("UTF-8");
		//resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		//获取前台数据
		String id = req.getParameter("uid");
		String name = req.getParameter("uname");
		String password = req.getParameter("upassword");
		String password2 = req.getParameter("upassword2");
		String sex = req.getParameter("usex");
		String email = req.getParameter("uemail");
		java.util.Date regdate = new java.util.Date();
		
		String uname = check(id,name,password,password2,sex,email,regdate);
		
		if(!( "".equals(uname) || "######".equals(uname)
				|| "******".equals(uname)|| "$$$$$$".equals(uname))){  //注册成功,跳转到成功页
			req.getSession().setAttribute("info", uname);
			resp.sendRedirect("reg_success.jsp");
			
		}else{              //注册失败,跳转到失败页
			String info = "";
			if("######".equals(uname)){
				info = "错误:登录ID已经存在!";
			}
			if("******".equals(uname)){
				info = "错误:两次输入密码不一致!";
			}
			if("$$$$$$".equals(uname)){
				info = "错误:所有信息都必须填写!";
			}		
			req.getSession().setAttribute("info", info);
			resp.sendRedirect("reg_failure.jsp");
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
	
	private String check(String userid, String username, 
		      String userpwd, String userpwd2,
		      String usersex, String useremail, 
		      java.util.Date userregdate){
	
		if("".equals(userid) || "".equals(username) || "".equals(userpwd) || "".equals(userpwd2)){
			return "$$$$$$";
		}
		
		if(!(userpwd.equals(userpwd2))){
			return "******";
		}
		
		User user = new User(userid,username,userpwd,usersex,useremail,userregdate);	
		
		UserService us = new UserServiceImpl();
		
		int n = us.register(user);
		
		if (n == -1) {
			return "######";
		}
		
		return username;
	} 

}

UpdateNewsServlet类

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nuc.ss.entity.News;
import nuc.ss.service.NewsService;
import nuc.ss.serviceimpl.NewsServiceImpl;

@WebServlet("/updateNews")
public class UpdateNewsServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 1、解决编码问题
    	req.setCharacterEncoding("utf-8");
    	resp.setCharacterEncoding("utf-8");
    	resp.setContentType("text/html;charset=utf-8");
    	
    	//2、接受前台数据,并将前台数据封装成一个News对象
    	int id = Integer.parseInt(req.getParameter("id"));    	
    	String title = req.getParameter("title");
    	String author = req.getParameter("author");
    	String content = req.getParameter("content");
    	String date_str = req.getParameter("enterdate");
    	String hot_str = req.getParameter("hot");
    	// String-->Util.Date
    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    	Date date;
    	int hot;
    	News news = null;
		try {
			date = df.parse(date_str);
			hot = Integer.parseInt(hot_str);			
	    	news = new News(id, title, author, content, date, hot);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		// 3、调用service层,然后传入news
		NewsService ns = new NewsServiceImpl();
		
		int n = ns.updateNews(news);
		
		// 4、处理结果
    	if(n >0) {
    		//修改成功
    		resp.sendRedirect("queryAllNews"); 
    	}else {
    		// 修改失败
    		resp.sendRedirect("queryAllNews");
    	}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}

dao层

这里是dao的接口

NewsDao类

import nuc.ss.entity.News;

import java.util.List;

public interface NewsDao {

	static int getTotalSize() {
		return 0;
	}

	static List<News> queryNewsByPage(int startIndex, int pageSize) {
		return null;
	}

	int insertOne(News news);

	List<News> selectAll();

	int deleteOne(int id);

	News selectOne(int id);

	int updateOne(News news);

}

UserDao类

import nuc.ss.entity.User;

public interface UserDao {

	int insertOne(User user);

	User findOne(String uid, String pwd);
	
	boolean findOne(String uid);

}

daoimpl层

NewsDaoImpl类

import nuc.ss.dao.NewsDao;
import nuc.ss.entity.News;
import nuc.ss.entity.PageBean;
import nuc.ss.util.DBUtil;

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

public class NewsDaoImpl implements NewsDao {

	@Override
	public int insertOne(News news) {
		String sql = "insert into t_news values(default,?,?,?,?,?)";
		Object[] objs = {news.getTitle(), news.getAuthor(), news.getContent(), news.getEnterdate(), news.getHot()};
		int n = DBUtil.excuteDML(sql, objs);
		return n;
	}

	@Override
	public List<News> selectAll() {
		Connection conn = DBUtil.getConnection();
		String sql = "select * from t_news";
		PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
		ResultSet rs = null;
		List<News> list = new ArrayList<News>();
		try {
			rs = ps.executeQuery();
			while(rs.next()) {
				News news = new News(rs.getInt("id"), rs.getString("title"),
						rs.getString("author"), rs.getString("content"),
						rs.getDate("enterdate"), rs.getInt("hot"));
				list.add(news);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeAll(rs, ps, conn);
		}
		return list;
	}

	@Override
	public int deleteOne(int id) {
		String sql = "delete from t_news where id=?";
		Object[] objs = {id};
		int n = DBUtil.excuteDML(sql, objs);
		return n;
	}

	@Override
	public News selectOne(int id) {
		Connection conn = DBUtil.getConnection();
		String sql = "select * from t_news where id=?";
		PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
		try {
			ps.setInt(1, id);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		ResultSet rs = null;
		News news = null;
		try {
			rs = ps.executeQuery();
			if(rs.next()) {
				news = new News(rs.getInt("id"), rs.getString("title"),
						rs.getString("author"), rs.getString("content"),
						rs.getDate("enterdate"), rs.getInt("hot"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeAll(rs, ps, conn);
		}
		return news;		
	}

	@Override
	public int updateOne(News news) {
		String sql = "update t_news set title=?,author=?,content=?,enterdate=?,hot=? where id=?";
		Object[] objs = {news.getTitle(), news.getAuthor(), news.getContent(),
				         news.getEnterdate(), news.getHot(), news.getId()};
		int n = DBUtil.excuteDML(sql, objs);
		return n;
	}

	public PageBean<News> queryNewsByPage(int currentPage, int pageSize) {
		// 创建一个PageBean对象
		PageBean<News> pageBean = new PageBean<News>();
		// 设置当前页数和每页记录数
		pageBean.setCurrentPage(currentPage);
		pageBean.setPageSize(pageSize);
		// 调用dao层的方法获取总记录数
		int totalSize = NewsDao.getTotalSize();
		// 设置总记录数
		pageBean.setTotalSize(totalSize);
		// 计算总页数
		int totalPage = (totalSize % pageSize == 0) ? (totalSize / pageSize) : (totalSize / pageSize + 1);
		// 设置总页数
		pageBean.setTotalPage(totalPage);
		// 计算开始索引
		int startIndex = (currentPage - 1) * pageSize;
		// 调用dao层的方法获取当前页数据
		List<News> list = NewsDao.queryNewsByPage(startIndex, pageSize);
		// 设置当前页数据
		pageBean.setList(list);
		// 返回PageBean对象
		return pageBean;


	}

}

UserDaoImpl类

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import nuc.ss.dao.UserDao;
import nuc.ss.entity.User;
import nuc.ss.util.DBUtil;

public class UserDaoImpl implements UserDao{

	@Override
	public int insertOne(User user) {
		
		String sql = "insert into t_user values (?,?,?,?,?,?)";
		
		Object[] objs = {user.getUid(), user.getUname(), user.getUpassword(), user.getUsex(), user.getUemail(), user.getUregdate()};
		int n = DBUtil.excuteDML(sql, objs);
		
		return n;
	}

	@Override
	public User findOne(String uid, String pwd) {
		Connection conn = DBUtil.getConnection();
		String sql = "select * from t_user where uid=? and upassword=?";
		PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
		ResultSet rs = null;
		User user = null;
		try {
			ps.setString(1, uid);
			ps.setString(2, pwd);
			
			rs = ps.executeQuery();
			if(rs.next()) {
				user = new User(rs.getString("uid"), rs.getString("uname"), rs.getString("upassword"), rs.getString("usex"), rs.getString("uemail"), rs.getDate("uregdate"));		
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DBUtil.closeAll(rs, ps, conn);
		}
		
		return user;
	}

	@Override
	public boolean findOne(String uid) {
		Connection conn = DBUtil.getConnection();
		String sql = "select * from t_user where uid=?";
		PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
		ResultSet rs = null;
		try {
			ps.setString(1, uid);
			
			rs = ps.executeQuery();
			if(rs.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DBUtil.closeAll(rs, ps, conn);
		}
		
		return false;
	}

}

entity层

News类

import java.util.Date;

public class News {
	private static int id;
	private String title;
	private String author;
	private String content;
	private Date enterdate;
	private int hot;
	public News(int id, String title, String author, String content, Date enterdate, int hot) {
		super();
		this.id = id;
		this.title = title;
		this.author = author;
		this.content = content;
		this.enterdate = enterdate;
		this.hot = hot;
	}
	public static int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getEnterdate() {
		return enterdate;
	}
	public void setEnterdate(Date enterdate) {
		this.enterdate = enterdate;
	}
	public int getHot() {
		return hot;
	}
	public void setHot(int hot) {
		this.hot = hot;
	}
	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", author=" + author + ", content=" + content + ", enterdate="
				+ enterdate + ", hot=" + hot + "]";
	}	
}

PageBean类

import java.util.List;
public class PageBean<T> {
    private Integer currentPage; // 当前页数
    private Integer totalPage; // 总页数
    private Integer totalSize; // 总记录数
    private Integer pageSize; // 每页记录数
    private List<T> list; // 当前页数据

    // 构造方法,根据总记录数、当前页数和每页记录数计算总页数
    public PageBean() {
        this.totalSize = totalSize;
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalPage = (totalSize % pageSize == 0) ? (totalSize / pageSize) : (totalSize / pageSize + 1);
    }

    // getter和setter方法
    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(Integer totalSize) {
        this.totalSize = totalSize;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

User类

import java.util.Date;

public class User {
	private String uid;
	private String uname;
	private String upassword;
	private String usex;
	private String uemail;
	private Date uregdate;
	
	public User(String uid, String uname, String upassword, String usex, String uemail, Date uregdate) {
		super();
		this.uid = uid;
		this.uname = uname;
		this.upassword = upassword;
		this.usex = usex;
		this.uemail = uemail;
		this.uregdate = uregdate;
	}
	
	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public String getUpassword() {
		return upassword;
	}

	public void setUpassword(String upassword) {
		this.upassword = upassword;
	}

	public String getUsex() {
		return usex;
	}

	public void setUsex(String usex) {
		this.usex = usex;
	}

	public String getUemail() {
		return uemail;
	}

	public void setUemail(String uemail) {
		this.uemail = uemail;
	}

	public Date getUregdate() {
		return uregdate;
	}

	public void setUregdate(Date uregdate) {
		this.uregdate = uregdate;
	}

	@Override
	public String toString() {
		return "User [uid=" + uid + ", uname=" + uname + ", upassword=" + upassword + ", usex=" + usex + ", uemail="
				+ uemail + ", uregdate=" + uregdate + "]";
	}

}

service层

NewsService类

import nuc.ss.entity.News;
import nuc.ss.entity.PageBean;

import java.util.List;

public interface NewsService {

	int addNews(News news);

	List<News> queryAllNews();

	int removeNews(int id);

	News queryOneNews(int id);

	int updateNews(News news);

    int getTotalCount();

	// 声明一个分页查询的方法
	PageBean<News> queryNewsByPage(int currentPage, int pageSize);

}

UserService类

import nuc.ss.entity.User;

public interface UserService {

	int register(User user);

	User login(String uid, String pwd);

}

serviceimpl层

NewsServiceImpl类

import nuc.ss.dao.NewsDao;
import nuc.ss.daoimpl.NewsDaoImpl;
import nuc.ss.entity.News;
import nuc.ss.entity.PageBean;
import nuc.ss.service.NewsService;

import java.util.List;

public class NewsServiceImpl implements NewsService {
	private NewsDao nd = new NewsDaoImpl();
	private NewsServiceImpl newsDao;

	@Override
	public int addNews(News news) {

		return nd.insertOne(news);
	}
	@Override
	public List<News> queryAllNews() {

		return nd.selectAll();
	}
	@Override
	public int removeNews(int id) {
		
		return nd.deleteOne(id);
	}
	@Override
	public News queryOneNews(int id) {
		
		return nd.selectOne(id);
	}
	@Override
	public int updateNews(News news) {
		
		return nd.updateOne(news);
	}

	@Override
	public int getTotalCount() {
		return 0;
	}

	@Override
	public PageBean<News> queryNewsByPage(int currentPage, int pageSize) {
		return null;
	}

	public void setNewsDao(NewsDao newsDao) {
		this.newsDao = (NewsServiceImpl) newsDao;

	}
}

UserServiceImpl类

import nuc.ss.dao.UserDao;
import nuc.ss.daoimpl.UserDaoImpl;
import nuc.ss.entity.User;
import nuc.ss.service.UserService;

public class UserServiceImpl implements UserService{
	private UserDao ud = new UserDaoImpl();
	
	@Override
	public int register(User user) {
		if(ud.findOne(user.getUid())){
			return -1;
		}
		return ud.insertOne(user);
	}
/*	public int register(User user) {

		return ud.insertOne(user);
	}*/

	@Override
	public User login(String uid, String pwd) {
		
		return ud.findOne(uid, pwd);
	}

}

util层

public class DBUtil {
	public static Connection getConnection() {
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("加载成功!");
			String url = "jdbc:mysql://localhost:3306/db_news2019?useUnicode=true&characterEncoding=utf-8";
			String username = "root";
			String password = "12345678";
			connection = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("加载失败!驱动类没有找到!");
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("数据库连接失败!请检查数据库名以及用户帐号!");
		}
		return connection;
	}

	// 关闭资源连接connection,statement,resultset
	public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
		if(resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			
	}
	
	// 创建数据库操作对象preparedStatement
	public static PreparedStatement getPreparedStatement(Connection connection, String sql) {
		PreparedStatement preparedStatement = null;
		try {
			preparedStatement = connection.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return preparedStatement;
	}
	
	// 创建数据库操作对象statement
	public static Statement getStatement(Connection connection) {
		Statement statement = null;
		try {
			statement = connection.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return statement;
	}
	
	// 封装DML语句(更新操作)
	public static int excuteDML(String sql, Object...objs) {
		int n = 0;
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = getConnection();
			preparedStatement = getPreparedStatement(connection, sql);
			for (int i = 0; i < objs.length; i++) {
				preparedStatement.setObject(i+1, objs[i]);
			}
			n = preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			closeAll(null, preparedStatement, connection);
		}
		return n;
	}
	
}

jsp代码

addNews

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>增加新闻</title>

</head>
<body>
	<form action="addNews" method="post">
		<table align="center">
			<tr>
				<td>新闻题目</td>
				<td><input type="text" name="title"></td>
			</tr>
			<tr>
				<td>新闻作者</td>
				<td><input type="text" name="author"></td>
			</tr>
			<tr>
				<td>新闻内容</td>
				<td><textarea rows="5" cols="70" name="content"></textarea> </td>
			</tr>
			<tr>
				<td>新闻日期</td>
				<td><input type="date" name="enterdate"></td>
			</tr>
			<tr>
				<td>新闻热度</td>
				<td><input type="number" name="hot"></td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="添加">
				</td>
			</tr>
		</table>
	</form>

</body>
</html>

displayNews

<%@ page language="java" 
	contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="nuc.ss.entity.News"%>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>查询新闻详情</title>
</head>
<body>
<% 
	News news = (News)request.getAttribute("news");

	if(news != null){
%>
		<table align="center">
		<tr>
			<td>新闻题目</td>
			<td><input type="text" readonly="readonly"  value="<%=news.getTitle() %>"></td>
		</tr>
		<tr>
			<td>新闻作者</td>
			<td><input type="text" readonly="readonly"  value="<%=news.getAuthor() %>"></td>
		</tr>
		<tr>
		<td>新闻内容</td>
		<td><textarea rows="5" cols="70" readonly="readonly"><%=news.getContent() %></textarea> </td>
		</tr>
		<tr>
			<td>新闻日期</td>
			<td><input type="date" readonly="readonly"  value="<%=news.getEnterdate() %>"></td>
		</tr>
		<tr>
			<td>新闻热度</td>
			<td><input type="number" readonly="readonly" value="<%=news.getHot() %>"></td>
		</tr>
	</table>
<%
	}
%>
<br>
<center>
	<a href="queryAllNews">返回</a>
</center>

</body>
</html>

login

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>登录程序之表单页面</title>
</head>
<body>
<%
	String id = "";
	String password = "";
	String remenber = null;
	Cookie[] cookies = request.getCookies();
	if(cookies != null){
		for(int i=0; i<cookies.length; i++){
			if (cookies[i].getName().equals("Cookie2020")) {
		           //如果cookie对象的名称为Cookie2019
				id = cookies[i].getValue().split("#")[0];  //获取用户名
				password = cookies[i].getValue().split("#")[1];  //获取密码
				remenber = cookies[i].getValue().split("#")[2];  //获取remenber
			}
		}
	}
%>

<center>
  <h1>登录操作</h1>
  <hr>
  <form action="login" method="post">
    <table border="1">
      <tr>
        <td colspan="2">用户登录</td>   
      </tr>
      <tr>
        <td>登录ID:</td>
        <td><input type="text" name="id" value="<%=id %>"></td>
      </tr>
      <tr>
        <td>登录密码:</td>
        <td><input type="password" name="password" value="<%=password %>"></td>
      </tr>
      <tr>
        <td colspan="2">
          &nbsp;&nbsp;<input type="submit" value="登录">&nbsp;&nbsp;
          <input type="reset" value="重置">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <input type="checkbox" name="remenber"  <%if(remenber!=null){%> checked <%}%>>记住我	 
        </td>   
      </tr>
    </table>
  </form>
  <h5>如果您尚未注册,请先进行<a href="register.jsp">&nbsp;注册&nbsp;</a></h5>
</center>
</body>

login_failure

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>登录程序之登录成功页面</title>
</head>
<body>
<center>
  <h1>登录操作</h1>
  <hr>
  <h2>用户ID或密码错误!请重新<a href="login.jsp">登录</a></h2>
</center>
</body>

queryAllNews

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="java.util.*" %>
<%@page import="nuc.ss.service.NewsService"%>
<%@page import="nuc.ss.serviceimpl.NewsServiceImpl"%>
<%@page import="nuc.ss.entity.News"%>
<%@page import="nuc.ss.entity.User"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>显示所有新闻</title>
	<script type="text/javascript">
		function del(id){
			var flag = window.confirm("是否真的要删除?");
			if(flag){
				window.location.href = "deleteNews?id=" + id;
			}
		}
		function update(id){
			window.location.href = "queryNews?id=" + id + "&flag=1";
		}
		function query(id){
			window.location.href = "queryNews?id=" + id + "&flag=0";
		}
	</script>
</head>
<body>
<%
    if(session.getAttribute("username") == null)
    {
		response.sendRedirect("login.jsp"); 
    }
%>
	<table align="center" border="0" width="750px" cellspacing="0">
		<tr>
			<td align="center" style="font-family:'黑体'; font-size:28px;">登录成功!欢迎[<%=session.getAttribute("username")%>]访问新闻管理系统!</td>	
		</tr>
		<tr>
			<td><hr></td>
		</tr>
		<tr style="font-family:'宋体'; font-size:24px;">
			<td align="right"><a href="addNews.jsp"><b>增加新闻</b></a>&nbsp;&nbsp;<a href="logout">安全退出</a></td>
		</tr>
	</table>
	<table  align="center" border="1" width="750px" cellspacing="0">
			<tr>
				<th width="320px">标题</th>
				<th width="120px">作者</th>
				<!-- <th width="600px">内容</th> -->
				<th width="110px">日期</th>
				<th width="50px">热度</th>
				<th width="150px">操作</th>
		    </tr>
	    <%
	    	List<News> list = (List)request.getAttribute("list");
			for(News news: list){
	    %>
	    	<tr>
	    		<td><%=news.getTitle() %></td>
	    		<td><%=news.getAuthor() %></td>
	    		<td><%=news.getEnterdate() %></td>
	    		<td><%=news.getHot() %></td>
	    		<td>
	    			<a href="javascript:query(<%=news.getId() %>)">查询详情</a>
	    			<a href="javascript:update(<%=news.getId() %>)">修改</a>
	    			<a href="javascript:del(<%=news.getId()%>)">删除</a>
	    		</td>
	    	</tr>
	    <%
	    	}
	    %>
	</table>
</body>
</html>

reg_failure

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>登录程序之登录成功页面</title>
</head>
<body>
<center>
  <h1>注册操作</h1>
  <hr>
  <h2><%=session.getAttribute("info")%>请重新<a href="register.jsp">注册</a></h2>
</center>
</body>

reg_success

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>登录程序之登注册成功页面</title>
</head>
<body>
    <h2>[<%=session.getAttribute("info")%>]恭喜您--注册成功!</h2>
    
    <h4>5秒后自动跳转到登录页面</h4>
<%
	response.setHeader("refresh", "5;login.jsp");
%>    

</body>
</html>

register

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>新闻管理系统之用户注册页面</title>
</head>
<body>
<center>
  <h1>注册操作</h1>
  <hr>
  <form action="register" method="post">
    <table border="1">
      <tr>
        <td colspan="2" align="center">用户注册</td>   
      </tr>
      <tr>
        <td align="right">登录ID:</td>
        <td><input type="text" name="uid"></td>
      </tr>
      <tr>
        <td align="right">真实姓名:</td>
        <td><input type="text" name="uname"></td>
      </tr>      
	  <tr>
		<td align="right">&nbsp;&nbsp;&nbsp;别:</td>
		<td>
			<input type="radio" name="usex" value="男"><input type="radio" name="usex" value="女"></td>
	  </tr>
	  <tr>
        <td align="right">E-Mail</td>
        <td><input type="text" name="uemail"></td>
      </tr>      <tr>
        <td align="right">登录密码:</td>
        <td><input type="password" name="upassword"></td>
      </tr>
      <tr>
        <td align="right">确认密码:</td>
        <td><input type="password" name="upassword2"></td>
      </tr>
      <tr>
        <td colspan="2">
          &nbsp;&nbsp;<input type="submit" value="注册">&nbsp;&nbsp;
          <input type="reset" value="重置"> 
        </td>   
      </tr>
    </table>
  </form>
  <h5><a href="login.jsp">&nbsp;返回登录页面&nbsp;</a></h5>
  
</center>
</body>

updateNews

<%@ page language="java" 
	contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="nuc.ss.entity.News"%>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>修改新闻</title>
</head>
<body>
<%	
	News news = (News)request.getAttribute("news");
%>
	<form action="updateNews" method="post">
		<input type="hidden" name="id" value="<%=news.getId() %>">
		<table align="center">
			<tr>
				<td>新闻题目</td>
				<td><input type="text" name="title" value="<%=news.getTitle() %>"></td>
			</tr>
			<tr>
				<td>新闻作者</td>
				<td><input type="text" name="author" value="<%=news.getAuthor() %>"></td>
			</tr>
			<tr>
				<td>新闻内容</td>
				<td><textarea rows="5" cols="70" name="content"><%=news.getContent() %></textarea> </td>
			</tr>
			<tr>
				<td>新闻日期</td>
				<td><input type="date" name="enterdate" value="<%=news.getEnterdate() %>"></td>
			</tr>
			<tr>
				<td>新闻热度</td>
				<td><input type="number" name="hot" value="<%=news.getHot() %>"></td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="保存修改">
				</td>
			</tr>
		</table>
	</form>

<br>
<center>
	<a href="queryAllNews">返回</a>
</center>

</body>
</html>

配置web.xml

参考配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ProjforNewsV1_0</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>nuc.ss.controller.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>nuc.ss.controller.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/logout</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>nuc.ss.controller.RegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/register</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>QueryAllNewsServlet</servlet-name>
    <servlet-class>nuc.ss.controller.QueryAllNewsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>QueryAllNewsServlet</servlet-name>
    <url-pattern>/queryAllNews</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>AddNewsServlet</servlet-name>
    <servlet-class>nuc.ss.controller.AddNewsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AddNewsServlet</servlet-name>
    <url-pattern>/addNews</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>DeleteNewsServlet</servlet-name>
    <servlet-class>nuc.ss.controller.DeleteNewsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DeleteNewsServlet</servlet-name>
    <url-pattern>/deleteNews</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>QueryNewsServlet</servlet-name>
    <servlet-class>nuc.ss.controller.QueryNewsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>QueryNewsServlet</servlet-name>
    <url-pattern>/queryNews</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>UpdateNewsServlet</servlet-name>
    <servlet-class>nuc.ss.controller.UpdateNewsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UpdateNewsServlet</servlet-name>
    <url-pattern>/updateNews</url-pattern>
  </servlet-mapping>
</web-app>

成果

登陆界面
在这里插入图片描述
注册界面
在这里插入图片描述
在这里插入图片描述
新闻展示页面
在这里插入图片描述
增加新闻
在这里插入图片描述
新闻详情
在这里插入图片描述

修改页面在这里插入图片描述
删除新闻
在这里插入图片描述

分页查询

增加一个分页查询的功能
servlet代码

@WebServlet("/queryAllNews")
public class QueryAllNewsServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1、调用service层,查询新闻
		NewsService ns = new NewsServiceImpl();
		int currentPage = 1; // 默认为第一页
		int pageSize = 10; // 默认每页显示10条
		String currentPageStr = req.getParameter("currentPage"); // 获取请求参数中的当前页数
		if (currentPageStr != null && !"".equals(currentPageStr)) { // 如果不为空,则转换为整数
			currentPage = Integer.parseInt(currentPageStr);
		}
		String pageSizeStr = req.getParameter("pageSize"); // 获取请求参数中的每页记录数
		if (pageSizeStr != null && !"".equals(pageSizeStr)) { // 如果不为空,则转换为整数
			pageSize = Integer.parseInt(pageSizeStr);
		}
		PageBean<News> pageBean = ns.queryNewsByPage(currentPage, pageSize); // 调用service层的方法获取PageBean对象
		// 2、处理结果
		req.setAttribute("pageBean", pageBean); // 将PageBean对象存入request域中
		req.getRequestDispatcher("queryAllNews.jsp").forward(req, resp); // 转发到JSP页面显示数据
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<%@page import="java.util.*" %>
<%@page import="nuc.ss.service.NewsService"%>
<%@page import="nuc.ss.serviceimpl.NewsServiceImpl"%>
<%@page import="nuc.ss.entity.News"%>
<%@page import="nuc.ss.entity.User"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>显示所有新闻</title>
    <script type="text/javascript">
        function del(id) {
            var flag = window.confirm("是否真的要删除?");
            if (flag) {
                window.location.href = "deleteNews?id=" + id;
            }
        }

        function update(id) {
            window.location.href = "queryNews?id=" + id + "&flag=1";
        }

        function query(id) {
            window.location.href = "queryNews?id=" + id + "&flag=0";
        }
    </script>
</head>
<body>
    <% if (session.getAttribute("username") == null) {
    response.sendRedirect("login.jsp");
}%>
<table align="center" border="0" width="750px" cellspacing="0">
    <tr>
        <td align="center" style="font-family:'黑体'; font-size:28px;">登录成功!欢迎[<%=session.getAttribute("username")%>]访问新闻管理系统!</td>
    </tr>
    <tr>
        <td><hr></td>
    </tr>
    <tr style="font-family:'宋体'; font-size:24px;">
        <td align="right"><a href="addNews.jsp"><b>增加新闻</b></a>  <a href="logout">安全退出</a></td>
    </tr>
</table>
<table align="center" border="1" width="750px" cellspacing="0">
    <tr>
        <th width="320px">标题</th>
        <th width="120px">作者</th>
        <!-- <th width="600px">内容</th> -->
        <th width="110px">日期</th>
        <th width="50px">热度</th>
        <th width="150px">操作</th>
    </tr>
    <c:forEach items="${pageBean.list}" var="news"> <!-- 遍历当前页数据 -->
    <tr>
        <td>${news.title}</td>
        <td>${news.author}</td>
        <td>${news.enterdate}</td>
        <td>${news.hot}</td>
        <td>
            <a href="javascript:query(${news.id})">查询详情</a>
            <a href="javascript:update(${news.id})">修改</a>
            <a href="javascript:del(${news.id})">删除</a>

        </td>
    </tr>
    </c:forEach>
    <tr>
        <td colspan="5" align="center">
            <span>第${pageBean.currentPage}/${pageBean.totalPage}页 总记录数:${pageBean.totalSize}条 每页${pageBean.pageSize}</span>

            <c:if test="${pageBean.currentPage > 1}"> <!-- 如果不是第一页,则可以跳转到首页和上一页 -->
            <a href="/queryAllNews?currentPage=1&pageSize=${pageBean.pageSize}">首页</a>

            <a href="/queryAllNews?currentPage=${pageBean.currentPage - 1}&pageSize=${pageBean.pageSize}">上一页</a>

            </c:if>

            <c:if test="${pageBean.currentPage < pageBean.totalPage}"> <!-- 如果不是最后一页,则可以跳转到下一页和末页 -->
            <a href="/queryAllNews?currentPage=${pageBean.currentPage + 1}&pageSize=${pageBean.pageSize}">下一页</a>

            <a href="/queryAllNews?currentPage=${pageBean.totalPage}&pageSize=${pageBean.pageSize}">末页</a>

            </c:if>

            <form action="/queryAllNews" method="get"> <!-- 添加一个表单来实现跳转到指定页 -->
                <input type="text" name="currentPage" size="2"/> <!-- 输入要跳转的页数 -->
                <input type="hidden" name="pageSize" value="${pageBean.pageSize}"/> <!-- 隐藏域保存每页记录数 -->
                <input type="submit" value="跳转"/> <!-- 提交表单 -->
            </form>

            <form action="/queryAllNews" method="get"> <!-- 添加一个表单来实现跳转到指定页 -->
                <input type="text" name="currentPage" size="2"/> <!-- 输入要跳转的页数 -->
                <input type="hidden" name="pageSize" value="${pageBean.pageSize}"/> <!-- 隐藏域保存每页记录数 -->
                <input type="submit" value="跳转"/> <!-- 提交表单 -->
            </form>
        </td> <!-- 结束单元格 -->
    </tr> <!-- 结束表格行 -->
</table> <!-- 结束表格 -->

在entity层中添加一个pagebean类

public class PageBean<T> {
    private Integer currentPage; // 当前页数
    private Integer totalPage; // 总页数
    private Integer totalSize; // 总记录数
    private Integer pageSize; // 每页记录数
    private List<T> list; // 当前页数据

    // 构造方法,根据总记录数、当前页数和每页记录数计算总页数
    public PageBean() {
        this.totalSize = totalSize;
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalPage = (totalSize % pageSize == 0) ? (totalSize / pageSize) : (totalSize / pageSize + 1);
    }

    // getter和setter方法
    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(Integer totalSize) {
        this.totalSize = totalSize;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

在dao层增加一个方法

public PageBean<News> queryNewsByPage(int currentPage, int pageSize) {
		// 创建一个PageBean对象
		PageBean<News> pageBean = new PageBean<News>();
		// 设置当前页数和每页记录数
		pageBean.setCurrentPage(currentPage);
		pageBean.setPageSize(pageSize);
		// 调用dao层的方法获取总记录数
		int totalSize = NewsDao.getTotalSize();
		// 设置总记录数
		pageBean.setTotalSize(totalSize);
		// 计算总页数
		int totalPage = (totalSize % pageSize == 0) ? (totalSize / pageSize) : (totalSize / pageSize + 1);
		// 设置总页数
		pageBean.setTotalPage(totalPage);
		// 计算开始索引
		int startIndex = (currentPage - 1) * pageSize;
		// 调用dao层的方法获取当前页数据
		List<News> list = NewsDao.queryNewsByPage(startIndex, pageSize);
		// 设置当前页数据
		pageBean.setList(list);
		// 返回PageBean对象
		return pageBean;


	}

展示一下成果吧
在这里插入图片描述
以上就是这次实验的全部内容啦

总结

本文是对javaweb实验的总结,主要介绍了基于MVC模式的web应用开发的过程和心得。MVC模式是一种设计模式,将web应用分为三个层次:模型(Model)、视图(View)和控制器(Controller)。模型负责封装业务逻辑和数据,视图负责展示用户界面,控制器负责处理用户请求和调用模型和视图。MVC模式的优点是可以实现高内聚低耦合,提高代码的可维护性和可重用性。

在本实验中,我使用了idea作为开发工具,Tomcat作为web服务器,MySQL作为数据库,JSP和Servlet作为视图和控制器,JavaBean作为模型。我实现了一个简单的登录系统和新闻管理系统,包括登录、注册、查询、修改、删除等功能。在开发过程中,我遵循了MVC模式的原则,将不同的功能分配到不同的层次,使得代码结构清晰,易于修改和扩展。我也遇到了一些困难和问题,例如如何保持用户的登录状态,如何防止SQL注入攻击,如何处理中文乱码等。通过查阅资料和调试代码,我逐一解决了这些问题,并从中学习到了很多知识和技巧。

总之,通过本实验,我深刻理解了MVC模式的原理和优势,掌握了基于MVC模式的web应用开发的方法和步骤,提高了我的编程能力和解决问题的能力。我认为这是一次非常有意义和有价值的实验,对于我的未来学习和工作都有很大的帮助。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/567466.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

标签派单系统架构设计

需求描述 项目背景 根据员工历史成单情况&#xff0c;计算员工对不同类型工单的转化能力。根据员工和工单标签匹配进行派单。 业务流程图 规则描述 每10分钟&#xff0c;分城进行一次派单&#xff0c;派单规则可能会动态删减&#xff0c;需要支持动态配置 工单标签说明 一…

抖音seo源码开发,技术交付及故障。服务等响应

抖音seo源码开发、抖音seo源码部署、抖音seo源码开源交付及故障响应 什么是抖音SEO&#xff1f; 抖音SEO主要是指通过一系列优化措施&#xff0c;提高抖音短视频在抖音搜索结果页的排名&#xff0c;从而增加短视频曝光量和观看量的过程。SEO的实现需要涉及多个方面&#xff0c…

MySQL基础一篇打通,图文并茂

准备工作 直接使用MySQL提供的数据&#xff0c;下载MySQL示例数据库 MySQL示例数据库模式由以下表组成&#xff1a; Customers&#xff1a;存储客户的数据。Products&#xff1a;存储比例模型车列表。ProductLines&#xff1a;存储产品系列类别列表。Orders&#xff1a;存储…

【前端工程化】Git入门指南:轻松掌握从安装到操作!

git入门指南 安装和基本配置Bash&#xff0c;CMD和GUI用户名和邮箱的配置 Git仓库本地Git仓库文件状态的划分文件状态检测git忽略文件的配置&#xff08;了解&#xff09;文件更新提交git校验和-日志和版本回退git loggit resetgit reflog 远程仓库远程仓库的操作获取远程仓库远…

整合Springboot+MybatisPlus+达梦数据库

1、安装Windows环境的达梦数据库可视化软件 这里不做安装介绍 安装步骤很简单&#xff0c;提供的软件也很全面&#xff0c;特别是数据库迁移工具&#xff0c;支持市面上许多主流的大型数据库&#xff0c;例如&#xff1a;Oracle、SQLServer、MySQL、DB2、PostgreSQL、Informix…

Axure 原型模板素材哪里下载

1、Axure 原型模板素材哪里下载 如果你想要下载 Axure 原型模板素材&#xff0c;可以前往即时设计资源广场进行一键复用。在即时设计资源广场&#xff0c;你可以免费使用所有的 Axure 原型模板素材&#xff0c;而且没有文件数量、团队或项目数量的限制。这大大降低了资源共享的…

医疗平台,专攻医学软件方向,病历云、影像学、实验室检验

一、开源项目简介 JEHC 本开源平台重点打造医疗&#xff08;专攻医学软件Web方向&#xff0c;病历云&#xff0c;影像学&#xff0c;实验室检验等等&#xff09;&#xff0c;IOT方向&#xff0c;工作流Workflow等。 JEHC-CLOUD基于Spring Cloud 2.X版本&#xff0c;采用前后…

当BIM遇见建筑,设计灵感无限,欣赏有趣的BIM建筑

人们常用“罗马是怎样建成的”来形容建成伟大城邦的复杂和艰辛&#xff0c;也因此&#xff0c;优秀的建筑是如何通过科学严密的设计建成&#xff0c;就成了值得研究的经验。随着国际化交流合作的日益增多&#xff0c;以及BIM先驱者标准院的技术经验引进&#xff0c;BIM在我们的…

zigbee 无线发送数据,呼吸灯

控制端代码&#xff1a; #include "hal_defs.h" #include "hal_cc8051.h" #include "hal_int.h" #include "hal_mcu.h" #include "hal_board.h" #include "hal_led.h" #include "hal_rf.h" #include &…

【服务器数据恢复】IBM服务器虚拟磁盘文件被误删除的数据恢复案例

服务器数据恢复环境&#xff1a; IBM X系列服务器柏科某型号存储。服务器上部署VMware ESXi虚拟主机&#xff0c;存储上存放虚拟机文件。 虚拟主机采用的Windows Server操作系统&#xff0c;部署宏桥和索菲2套应用&#xff0c;数据库是SQL Server。 虚拟磁盘&#xff1a;数据盘…

已经有MySQL了,干嘛还要学MongoDB?

三分钟的时间&#xff0c;通过本文你将学会 1.MongoDB主要特征 2.MongoDB优缺点&#xff0c;扬长避短 3.何时选择MongoDB&#xff1f;为啥要用它&#xff1f; 4.MongoDB与MySQL关键字对比 5.下载与安装MongoDB 6.Java整合MongoDB&#xff0c;实现增删改查 MongoDB和MySQ…

PyTorch-TensorBoard

一、介绍&#xff1a; TensorBoard&#xff1a;是一组用于数据可视化的工具。 SummaryWriter&#xff1a;类&#xff0c;用于提供一个高级API&#xff0c;并在给定目录中创建事件文件&#xff0c;向其中添加摘要和事件。 1. SummaryWriter(log_dir)&#xff1a;log_dir表示Tens…

MySQL 索引(w字)

目录 关于索引 关于磁盘 磁盘 ​扇区 结论 MySQL 与磁盘交互基本单位 MySQL 整体轮廓 结论 关于索引 建立测试表 关于 Page 为何IO交互要是 Page 理解单个Page 理解多个Page ​页目录 复盘一下 ​B树 ​B树 聚簇索引 VS 非聚簇索引 总结(重点) …

就业内推 | 地产行业招运维,最高30k*15薪,有住房交通补贴

01 宝能 &#x1f537;招聘岗位&#xff1a;网络运维高级工程师 &#x1f537;职责描述&#xff1a; 1、负责集团各数据中心和职场网络的设计规划、实施落地和持续优化&#xff1b; 2、负责集团网络的日常运维工作&#xff0c;如服务请求和变更的处理、网络相关故障解决&#…

JSP详解

JSP的概念&#xff1a; 概念&#xff1a;Java Serve Pages Java服务端页面 一种动态的网页技术&#xff0c;其中可以定义Html、css、js等静态内容。还可以定义Java代码的动态内容。 JSPHtmljava JSP的存在使我们可以不用在servlet里面用输出流一行一行的写字符串&#xff0…

拿下7家大厂offer后,整理出来的笔记.....

我第一次接触自动化是在2016年。那时刚毕业一年有余&#xff0c;组内一直做手工功能测试&#xff0c;大概在2018年9月&#xff0c;部门领导要求测试组引入自动化。组内之前从没有开展过任何自动化&#xff0c;测试主管安排了一个刚入职不久的研究生同事去研究。 当时自己内心还…

Jmeter性能测试 -3数据驱动实战

什么是数据驱动&#xff1f; 从数据文件中读取测试数据&#xff0c;驱动测试过程的一种测试方法。数据驱动可以理解为更高级的参数化。 特点&#xff1a;测试数据与测试代码分离&#xff1b;数据控制过程 好处&#xff1a;降低开发和维护成本&#xff0c;减少代码量&#xf…

原型设计工具

常见原型图设计工具 Sketch(国内外通用) 仅支持mac系统&#xff0c;无window系统软件。 Figma(国外) Figma是一个基于浏览器的协作式UI设计工具。 即时设计(国内) 墨刀(国内) 墨刀采用简便的拖拽连线操作&#xff0c;作为一款在线原型设计软件&#xff0c;墨刀支持云端保存…

Docker 设置国内镜像源

Docker 镜像加速 国内从 DockerHub 拉取镜像有时会遇到网络问题&#xff0c;此时可以配置国内的镜像加速来下载。Docker 官方和国内很多云服务商都提供了国内加速器服务&#xff0c;例如如下&#xff1a; 科大镜像&#xff1a;https://docker.mirrors.ustc.edu.cn/网易&#…

SpringSecurity 硅谷通用权限系统:权限管理

由于项目需要 快速入门一下 看的是这篇 比较新比较快 硅谷通用权限系统&#xff1a;权限管理 一、权限管理 1、权限管理介绍 每个系统的权限功能都不尽相同&#xff0c;各有其自身的业务特点&#xff0c;对权限管理的设计也都各有特色。不过不管是怎样的权限设计&#xff0c;大…