使用基本MVC2模式创建新闻网站
Posted wajp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用基本MVC2模式创建新闻网站相关的知识,希望对你有一定的参考价值。
1.什么是MVC
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
(1)Model层:Model指模型部分,一般在应用中Model层包括业务处理层和数据访问层。数据访问层主要是对数据库的一些操作的封装。业务处理层应用JavaBean构建, JavaBean主要是用作将从View层获取的数据和数据库的数据进行桥接。除却JavaBean以外,若想构建分布式应用系统,可以应用EJB组件进行业务逻辑层的构建。
(2)Controller层:Controller指控制部分,一般是对View层提交的请求为其设置对应的Servlet进行特定功能的处理,这里的进行特定功能的处理一般是编写在Model中的业务处理层中的。Controller一般只是在Web应用中充当一个中介者的作用。
(3)View层:View指视图部分,这一部分的内容是展示给用户实际进行交互的,通常使用JSP和html进行构建(个人比较喜欢以HTML嵌入JSP的方式来构建网页)。
综上来说,一个小型完整的基于MVC设计模式的Web应用程序的处理流程应该如下:
由上面的图中我们可以看出,用户在客户端(Web应用的客户端即为浏览器)中发出请求的时候,请求首先由View层的JSP/HTML将HTTP请求传给控制器中对应的Servlet,然后由Servlet负责调用Model层中的业务逻辑处理部分进行要求的处理,处理期间如果设计数据库的操作,则与数据库进行操作,最后全部操作结束之后,由业务逻辑层将结果发给控制层,控制层以HTTP响应的形式将结果发送回客户端。
MVC编程模式
-
Model(模型)表示应用程序核心(比如数据库记录列表)。
-
View(视图)显示数据(数据库记录)。
-
Controller(控制器)处理输入(写入数据库记录)。
通常模型对象负责在数据库中存取数据。
通常视图是依据模型数据创建的。
通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
package bean; public class News { String title; String datetime; String content; String type; int id; public News(String title,String datetime,String content,String type,int id){ super(); this.title = title; this.datetime = datetime; this.content = content; this.type = type; this.id = id; } public int getId(){ return id; } public void setId(int id){ this.id = id; } public News(){ } public String getTitle(){ return title; } public void setTitle(String title){ this.title = title; } public String getDatetime(){ return datetime; } public void setDatetime(String datetime){ this.datetime = datetime; } public String getContent(){ return content; } public void setContent(String content){ this.content = content; } public String getType(){ return type; } public void setType(String type){ this.type = type; } public News(String title,String datetime,String content,String type){ super(); this.title = title; this.datetime = datetime; this.content = content; this.type = type; } } News.java
package bean; public class User { String name; String password; public User(){ } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String getPassword(){ return password; } public void setPassword(String password){ this.password = password; } public User(String name,String password){ super(); this.name = name; this.password = password; } } User.java
package com.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import bean.News; public class Newsdao { @SuppressWarnings("unused") private static final long serialVersionUID = 1L; static Connection con = null; public static Connection getCon(){ String driverName = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/newsdata?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; String name = "root"; String pwd = "123456"; try{ Class.forName(driverName); try{ con = DriverManager.getConnection(url,name,pwd); }catch(SQLException e){ e.printStackTrace(); } }catch(ClassNotFoundException e){ e.printStackTrace(); } return con; } //添加新闻 public boolean addNews(News news){ con = Newsdao.getCon(); boolean flag = false; String sql = "insert news(title,type,datetime,content) values(‘"+news.getTitle()+"‘,‘"+news.getType()+"‘,‘"+news.getDatetime()+"‘,‘"+news.getContent()+"‘)"; try{ PreparedStatement ps = con.prepareStatement(sql); int i = ps.executeUpdate(); ps.close(); con.close(); if(i>0){ flag = true; } }catch(SQLException e){ System.out.println("添加出错!"); e.printStackTrace(); } return flag; } public List<News> selectByID(int id){ con = Newsdao.getCon(); List<News> list = new ArrayList<>(); String sql = "select * from news where id="+id+""; System.out.println(sql); Statement state; ResultSet rs; try{ state = con.createStatement(); rs = state.executeQuery(sql); while(rs.next()){ News news = new News(); news.setTitle(rs.getString("title")); news.setDatetime(rs.getString("content")); news.setContent(rs.getString("content")); news.setType(rs.getString("type")); news.setId(id); list.add(news); } rs.close(); state.close(); con.close(); }catch(SQLException e){ System.out.println("查询出错!"); e.printStackTrace(); } return list; } //删除新闻 public List<News> selectAll(){ con = Newsdao.getCon(); List<News> list = new ArrayList<News>(); String sql = "select * from news"; Statement state; ResultSet rs; try{ state = con.createStatement(); rs = state.executeQuery(sql); while(rs.next()){ News news = new News(); news.setId(rs.getInt("id")); news.setTitle(rs.getString("title")); news.setDatetime(rs.getString("datetime")); news.setContent(rs.getString("content")); news.setType(rs.getString("type")); list.add(news); } rs.close(); state.close(); con.close(); }catch(SQLException e){ System.out.println("查询出错!"); e.printStackTrace(); } return list; } //修改新闻 public boolean update(News news){ con = Newsdao.getCon(); boolean flag = false; String sql = "update news set title=‘"+news.getTitle()+"‘,type=‘"+news.getType()+"‘,datetime=‘"+news.getDatetime()+"‘,content=‘"+news.getContent()+"‘ where id = "+news.getId()+""; System.out.println(sql); Statement state = null; try{ state = con.createStatement(); int i=state.executeUpdate(sql); System.out.println(i); if(i>0){ flag = true; } }catch(SQLException e){ System.out.println("更新错误!"); e.printStackTrace(); } return flag; } //删除新闻 public boolean delete(int id){ con = Newsdao.getCon(); boolean flag = false; String sql = "delete from news where id=‘"+id+"‘"; PreparedStatement ps; try{ ps = con.prepareStatement(sql); int i = ps.executeUpdate(); if(i>0){ flag = true; } }catch(SQLException e){ System.out.println("删除错误!"); e.printStackTrace(); } return flag; } } Newsdao.java
package com.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import bean.User; public class Userdao { private static final long serialVersionUID = 1L; private String driverName="com.mysql.cj.jdbc.Driver"; private String url="jdbc:mysql://localhost:3306/newsdata?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; private String name="root"; private String pwd="123456"; public boolean login(User u) { boolean flag=false; String sql="select * from user where uname=‘"+u.getName()+"‘ and password=‘"+u.getPassword()+"‘"; System.out.println(sql); Connection connection=null; Statement statement=null; ResultSet resultSet=null; try { //System.out.println("******************"); Class.forName(driverName); try { //System.out.println("##################3"); connection = DriverManager.getConnection(url, name, pwd); //System.out.println("******************"); statement = connection.createStatement(); resultSet = statement.executeQuery(sql); flag=resultSet.next(); resultSet.close(); statement.close(); connection.close(); //System.out.println(flag+"**********"); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } return flag; } } Userdao.java
package servlet; 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 com.dao.Newsdao; import bean.News; @WebServlet("/AddServlet") public class AddServlet extends HttpServlet { public AddServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); String title=request.getParameter("title"); String type=request.getParameter("type"); String datetime=request.getParameter("datetime"); String content=request.getParameter("ueditor"); System.out.println("这是ueditor的内容"+title+content); News news=new News(); news.setTitle(title); news.setContent(content); news.setDatetime(datetime); news.setType(type); Newsdao nd=new Newsdao(); try{ nd.addNews(news); response.sendRedirect("newslistServlet"); //request.getRequestDispatcher("/newslist.jsp").forward(request, response); }catch(Exception e) { System.out.println("添加失败"); } } } AddServlet.java
package servlet; 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 com.dao.Newsdao; @WebServlet("/DeleteServlet") public class DeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DeleteServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String id=(String)request.getParameter("id"); System.out.println("被删除的新闻"); int nid=Integer.parseInt(id); Newsdao nd=new Newsdao(); nd.delete(nid); response.sendRedirect("newslistServlet"); } } DeleteServlet.java
package servlet; 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 com.dao.Newsdao; import bean.News; @WebServlet("/UpdateServlet") public class UpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UpdateServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("utf-8"); String id=request.getParameter("id"); System.out.println("id的值为"+id); int nid=Integer.parseInt(id); String title=request.getParameter("title"); String type=request.getParameter("type"); String datetime=request.getParameter("datetime"); String content=request.getParameter("editor"); News news=new News(); news.setId(nid); news.setTitle(title); news.setContent(content); news.setDatetime(datetime); news.setType(type); Newsdao nd=new Newsdao(); try{ nd.update(news); response.sendRedirect("newslistServlet"); }catch(Exception e) { System.out.println("修改失败"); } } } UpdataServlet.java
package servlet; import java.io.IOException; import java.util.List; 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 com.dao.Newsdao; import bean.News; @WebServlet("/SelectServlet") public class SelectServlet extends HttpServlet { private static final long serialVersionUID = 1L; public SelectServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;cahrset=utf-8"); String id=request.getParameter("id"); int nid=Integer.parseInt(id); Newsdao nd=new Newsdao(); List<News> list=nd.selectByID(nid); request.setAttribute("news", list); System.out.println(list.size()); request.getRequestDispatcher("/content.jsp").forward(request, response); } } SelectServlet.java
以上是关于使用基本MVC2模式创建新闻网站的主要内容,如果未能解决你的问题,请参考以下文章