赞
踩
本实验的目的是让学生掌握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等相关技术,实现新闻管理系统。要求提供如下功能:用户登录,用户注册,新闻的增、查、改、删。
关于创建项目创建数据库等内容在此就不多赘述
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); } }
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); } }
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; } }
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); } }
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); } }
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); } }
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; } }
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的接口
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); }
import nuc.ss.entity.User;
public interface UserDao {
int insertOne(User user);
User findOne(String uid, String pwd);
boolean findOne(String uid);
}
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; } }
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; } }
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 + "]"; } }
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; } }
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 + "]"; } }
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); }
import nuc.ss.entity.User;
public interface UserService {
int register(User user);
User login(String uid, String pwd);
}
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; } }
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); } }
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; } }
<%@ 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>
<%@ 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>
<%@ 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"> <input type="submit" value="登录"> <input type="reset" value="重置"> <input type="checkbox" name="remenber" <%if(remenber!=null){%> checked <%}%>>记住我 </td> </tr> </table> </form> <h5>如果您尚未注册,请先进行<a href="register.jsp"> 注册 </a></h5> </center> </body>
<%@ 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>
<%@ 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> <% 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>
<%@ 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>
<%@ 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>
<%@ 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">性 别:</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"> <input type="submit" value="注册"> <input type="reset" value="重置"> </td> </tr> </table> </form> <h5><a href="login.jsp"> 返回登录页面 </a></h5> </center> </body>
<%@ 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>
参考配置
<?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应用开发的方法和步骤,提高了我的编程能力和解决问题的能力。我认为这是一次非常有意义和有价值的实验,对于我的未来学习和工作都有很大的帮助。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。