MVC简介
所谓MVC,即Model-View-Controller。
(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响应的形式将结果发送回客户端。
简单的基于MVC2的增删改查
基本的操作就是连接数据库的进行简单的增删改查,然后数据的回显。此处遇到的主要的问题一个是使用ueditor富文本编辑的时候,需要配置。
其次最需要注意的就是数据库的操作语句以及数据库的连接,新闻表的代码,由于之前已经做过登录,不在附上该操作代码。在操作数据库时,如果频繁的需要连接数据库,那么可以将连接的代码单独写到一个类中去。
1 package dao; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 import bean.News; 13 14 public class Newsdao { 15 private static final long serialVersionUID = 1L; 16 // private String driverName="com.mysql.jdbc.Driver"; 17 // private String url="jdbc:mysql://localhost:3306/newsdata?useSSL=false&serverTimezone=UTC"; 18 // private String name="root"; 19 // private String pwd="123456"; 20 static Connection con=null; 21 public static Connection getCon() { 22 String driverName="com.mysql.cj.jdbc.Driver"; 23 String url="jdbc:mysql://localhost:3306/newsdata?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; 24 String name="root"; 25 String pwd="123456"; 26 try { 27 Class.forName(driverName); 28 try { 29 con = DriverManager.getConnection(url, name, pwd); 30 } catch (SQLException e) { 31 e.printStackTrace(); 32 } 33 34 } catch (ClassNotFoundException e) { 35 e.printStackTrace(); 36 } 37 return con; 38 } 39 //添加新闻 40 public boolean addNews(News news) { 41 con=Newsdao.getCon(); 42 boolean flag=false; 43 String sql="insert news(title,type,datetime,content) values('"+news.getTitle()+"','" 44 +news.getType()+"','" 45 +news.getDateTime()+"','" 46 +news.getContent()+"')"; 47 //System.out.println("添加的sql语句"+sql); 48 try { 49 PreparedStatement ps=con.prepareStatement(sql); 50 int i=ps.executeUpdate(); 51 //System.out.println("i的值"+i); 52 ps.close(); 53 con.close(); 54 if(i>0) { 55 flag =true; 56 } 57 } catch (SQLException e) { 58 System.out.println("添加出错啦"); 59 e.printStackTrace(); 60 } 61 62 return flag; 63 } 64 public List<News> selectByID(int id){ 65 con=Newsdao.getCon(); 66 List<News> list=new ArrayList<>(); 67 String sql="select * from news where id="+id+""; 68 System.out.println(sql); 69 Statement state; 70 ResultSet rs; 71 try { 72 state = con.createStatement(); 73 rs=state.executeQuery(sql); 74 while(rs.next()) { 75 News news=new News(); 76 news.setTitle(rs.getString("title")); 77 news.setContent(rs.getString("content")); 78 news.setDateTime(rs.getString("dateTime")); 79 news.setType(rs.getString("type")); 80 ; news.setId(id); 81 list.add(news); 82 //System.out.println(news.getTitle()); 83 } 84 rs.close(); 85 state.close(); 86 con.close(); 87 } catch (SQLException e) { 88 System.out.println("查询出错啦"); 89 e.printStackTrace(); 90 } 91 return list; 92 } 93 94 95 //删除新闻 96 public List<News> selectAll(){ 97 con=Newsdao.getCon(); 98 List<News> list=new ArrayList<News>(); 99 String sql="select * from news"; 100 Statement state; 101 ResultSet rs; 102 try { 103 state = con.createStatement(); 104 rs=state.executeQuery(sql); 105 while(rs.next()) { 106 News news=new News(); 107 news.setId(rs.getInt("id")); 108 news.setTitle(rs.getString("title")); 109 news.setContent(rs.getString("content")); 110 news.setDateTime(rs.getString("dateTime")); 111 news.setType(rs.getString("type")); 112 list.add(news); 113 //System.out.println(news.getType()); 114 } 115 rs.close(); 116 state.close(); 117 con.close(); 118 } catch (SQLException e) { 119 System.out.println("查询出错啦"); 120 e.printStackTrace(); 121 } 122 return list; 123 } 124 125 //修改新闻 126 127 public boolean update(News news) { 128 con=Newsdao.getCon(); 129 boolean flag=false; 130 String sql="update news set title='"+news.getTitle()+"',type='"+news.getType() 131 +"',dateTime='"+news.getDateTime() 132 +"',content='"+news.getContent()+"' where id="+news.getId()+""; 133 System.out.println(sql); 134 Statement state=null; 135 try { 136 state = con.createStatement(); 137 int i=state.executeUpdate(sql); 138 System.out.println(i); 139 if(i>0) { 140 flag=true; 141 } 142 } catch (SQLException e) { 143 System.out.println("更新错误啦"); 144 e.printStackTrace(); 145 } 146 147 return false; 148 } 149 150 //删除 151 public boolean delete(int id) { 152 con=Newsdao.getCon(); 153 boolean flag=false; 154 String sql="delete from news where id='"+id+"'"; 155 // System.out.println(sql); 156 PreparedStatement ps; 157 try { 158 ps = con.prepareStatement(sql); 159 int i=ps.executeUpdate(); 160 if(i>0){ 161 flag=true; 162 } 163 } catch (SQLException e) { 164 System.out.println("删除出错啦"); 165 e.printStackTrace(); 166 } 167 168 return flag; 169 } 170 171 }
新闻的添加
1 package servlet; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import bean.News; 11 import dao.Newsdao; 12 13 /** 14 * Servlet implementation class AddServlet 15 */ 16 @WebServlet("/AddServlet") 17 public class AddServlet extends HttpServlet { 18 19 20 public AddServlet() { 21 super(); 22 } 23 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 24 doPost(request,response); 25 } 26 27 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 28 request.setCharacterEncoding("utf-8"); 29 response.setContentType("text/html;charset=UTF-8"); 30 String title=request.getParameter("title"); 31 String type=request.getParameter("type"); 32 String datetime=request.getParameter("datetime"); 33 String content=request.getParameter("ueditor"); 34 System.out.println("这是ueditor的内容"+title+content); 35 News news=new News(); 36 news.setTitle(title); 37 news.setContent(content); 38 news.setDateTime(datetime); 39 news.setType(type); 40 41 Newsdao nd=new Newsdao(); 42 43 try{ 44 nd.addNews(news); 45 response.sendRedirect("newslistServlet"); 46 //request.getRequestDispatcher("/newslist.jsp").forward(request, response); 47 }catch(Exception e) { 48 System.out.println("添加失败"); 49 } 50 } 51 52 }
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@page import="java.util.*" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.all.min.js"> </script> <script type="text/javascript" charset="utf-8" src="utf8-jsp/lang/zh-cn/zh-cn.js"></script> <title>新闻页</title> <style type="text/css"> body{ margin-top:20px; backgroud-color:#ff2812; text-align:center; } .text{ 500px; height:20px; } .btn{ right: 35px; bottom: 25px; 100px; height: 30px; background: #759fc7; font-size: 15px; color: #fff; letter-spacing: 10px; margin-left:40px; text-align: center; } </style> </head> <body> <div > <h2>添加新闻</h2> <form action="addServlet" method="POST" > 新闻标题 <input class="text" type="text" name="title" ><br><br> 新闻类别 <input type="radio" name="type" value="娱乐" checked="checked"/>娱乐 <input type="radio" name="type" value="体育"/>体育 <input type="radio" name="type" value="国际"/>国际 <input type="radio" name="type" value="社会"/>社会 <input type="radio" name="type" value="财经"/>财经 <input type="radio" name="type " value="科技"/>科技 <br><br> 发布时间 <input class="text" type="text" name="datetime" ><br><br> 正文编辑 <script id="editor" type="text/plain" name="ueditor" style="1024px;height:500px;margin-left:100px"></script> <button class="btn" type="submit">保存</button > <!-- <button class="btn" type="submit">退出</button> --> </form> </div> <script type="text/javascript"> var ue=UE.getEditor('editor'); function getPlainTxt() { var arr = []; arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容"); arr.push("内容为:"); arr.push(UE.getEditor('editor').getPlainTxt()); alert(arr.join(' ')) } </script> </body> </html>
删除
1 package servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import dao.Newsdao; 12 13 /** 14 * Servlet implementation class DeleteServlet 15 */ 16 @WebServlet("/DeleteServlet") 17 public class DeleteServlet extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 public DeleteServlet() { 21 super(); 22 } 23 24 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 25 doPost(request,response); 26 } 27 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 28 request.setCharacterEncoding("utf-8"); 29 response.setContentType("text/html;charset=utf-8"); 30 String id=(String)request.getParameter("id"); 31 System.out.println("被删除的新闻"); 32 int nid=Integer.parseInt(id); 33 Newsdao nd=new Newsdao(); 34 nd.delete(nid); 35 response.sendRedirect("newslistServlet"); 36 //request.getRequestDispatcher("/newslist.jsp").forward(request, response); 37 } 38 39 }
修改
注意:此处我是用的先回显需要修改的新闻内容,在进行修改操作。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@page import="java.util.*" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.all.min.js"> </script> <script type="text/javascript" charset="utf-8" src="utf8-jsp/lang/zh-cn/zh-cn.js"></script> <title>新闻页</title> <style type="text/css"> body{ margin-top:20px; backgroud-color:#ff2812; text-align:center; } .text{ 500px; height:20px; } .btn{ right: 35px; bottom: 25px; 100px; height: 30px; background: #759fc7; font-size: 15px; color: #fff; letter-spacing: 10px; margin-left:40px; text-align: center; } </style> </head> <body> <div > <h2>修改新闻</h2> <form action="updateServlet" method="GET" > <c:forEach var="s" items="${item}"> 新闻编号 <input class="text" type="text" name="id" value="${s.id }"><br><br> 新闻标题 <input class="text" type="text" name="title" value="${s.title }"><br><br> 新闻类别 <input type="radio" name="type" value="娱乐" ${("娱乐"eq s.type)?"checked":""}/>娱乐 <input type="radio" name="type" value="体育" ${("体育"eq s.type)?"checked":""}/>体育 <input type="radio" name="type" value="国际" ${("国际"eq s.type)?"checked":""}/>国际 <input type="radio" name="type" value="社会" ${("社会"eq s.type)?"checked":""}/>社会 <input type="radio" name="type" value="财经" ${("财经"eq s.type)?"checked":""}/>财经 <input type="radio" name="type" value="科技" ${("科技"eq s.type)?"checked":""}/>科技 <br><br> 发布时间 <input class="text" type="text" name="datetime" value="${s.dateTime }" ><br><br> 正文编辑 <script id="editor" type="text/plain" name="editor" style="1024px;height:500px;margin-left:100px">${s.content}</script> <button class="btn" type="submit">保存</button > <!-- <button class="btn" type="submit">退出</button> --> </form> </div> </c:forEach> <script type="text/javascript"> var ue=UE.getEditor('editor'); UE.getEditor('editor').setContent('${s.content}'); /* function setContent(isAppendTo) { var arr = []; arr.push("使用editor.setContent('欢迎使用ueditor')方法可以设置编辑器的内容"); ue.getEditor('editor').setContent('欢迎使用ueditor', isAppendTo); alert(arr.join(" ")); } */ //alter("gg"); //UE.getEditor('editor').setContent('${s.content}'); function getContent() { var arr = []; arr.push(UE.getEditor('editor').getContent()); alert(arr.join(" ")); } </script> </body> </html>
1 package servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import bean.News; 12 import dao.Newsdao; 13 14 /** 15 * Servlet implementation class UpnewsServlet 16 */ 17 @WebServlet("/UpdateServlet") 18 public class UpdateServlet extends HttpServlet { 19 private static final long serialVersionUID = 1L; 20 21 public UpdateServlet() { 22 super(); 23 } 24 25 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 26 doPost(request,response); 27 28 } 29 30 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 response.setContentType("text/html;charset=UTF-8"); 32 request.setCharacterEncoding("utf-8"); 33 String id=request.getParameter("id"); 34 System.out.println("id的值为"+id); 35 int nid=Integer.parseInt(id); 36 String title=request.getParameter("title"); 37 String type=request.getParameter("type"); 38 String datetime=request.getParameter("datetime"); 39 String content=request.getParameter("editor"); 40 News news=new News(); 41 news.setId(nid); 42 news.setTitle(title); 43 news.setContent(content); 44 news.setDateTime(datetime); 45 news.setType(type); 46 Newsdao nd=new Newsdao(); 47 try{ 48 nd.update(news); 49 response.sendRedirect("newslistServlet"); 50 }catch(Exception e) { 51 System.out.println("修改失败"); 52 } 53 } 54 55 }
1 package servlet; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import bean.News; 13 import dao.Newsdao; 14 15 /** 16 * Servlet implementation class ShowServlet 17 */ 18 @WebServlet("/ShowServlet") 19 public class ShowServlet extends HttpServlet { 20 private static final long serialVersionUID = 1L; 21 22 public ShowServlet() { 23 super(); 24 } 25 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 26 doPost(request,response); 27 } 28 29 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 30 request.setCharacterEncoding("utf-8"); 31 response.setContentType("text/html;cahrset=utf-8"); 32 String id=request.getParameter("id"); 33 int nid=Integer.parseInt(id); 34 35 Newsdao nd=new Newsdao(); 36 List<News> list=nd.selectByID(nid); 37 request.setAttribute("item", list); 38 39 System.out.println(list.size()); 40 request.getRequestDispatcher("/update.jsp").forward(request, response); 41 42 } 43 44 }
查找
1 package servlet; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import bean.News; 13 import dao.Newsdao; 14 @WebServlet("/SelectServlet") 15 public class SelectServlet extends HttpServlet { 16 private static final long serialVersionUID = 1L; 17 public SelectServlet() { 18 super(); 19 } 20 21 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 22 doPost(request,response); 23 } 24 25 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 26 request.setCharacterEncoding("utf-8"); 27 response.setContentType("text/html;cahrset=utf-8"); 28 String id=request.getParameter("id"); 29 int nid=Integer.parseInt(id); 30 Newsdao nd=new Newsdao(); 31 List<News> list=nd.selectByID(nid); 32 request.setAttribute("news", list); 33 34 System.out.println(list.size()); 35 request.getRequestDispatcher("/content.jsp").forward(request, response); 36 37 38 39 } 40 41 }
以下是具体的运行截图,和一些需要的说明
具体的代码已上传云盘:链接: https://pan.baidu.com/s/1puSGXg5eOmiegHRimThAgQ 提取码: ikdm 复制这段内容后打开百度网盘手机App,操作更方便哦