一、MVC设计模式实例
M层
Login.java
package org.entity; public class Login { private int id; private String uname; private String upwd; public Login() { } public Login( String uname, String upwd) { this.uname = uname; this.upwd = upwd; } public Login(int id, String uname, String upwd) { this.id = id; this.uname = uname; this.upwd = upwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } }
LoginDao.jsp
package org.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.entity.Login; //模型层,用于处理登录(查询数据) public class LoginDao { public static int login(Login login) {//登录 int flag=-1;//登录成功与否的标识 -1:系统异常,0:用户名或密码有误,1:登录成功 int result =-1; Connection connection =null; PreparedStatement pstmt =null; ResultSet rs =null; try { Class.forName("com.mysql.cj.jdbc.Driver"); //Ctrl+1自动返回 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/login?serverTimezone=UTC&characterEncoding=utf-8","root","vayne"); String sql="Select count(*) from login where uname=? and upwd =?"; pstmt = connection.prepareStatement(sql); pstmt.setString(1, login.getUname()); pstmt.setString(2, login.getUpwd()); rs = pstmt.executeQuery(); if(rs.next()) { result =rs.getInt(1); } if(result>0) {//登录成功 flag= 1; }else { flag=0;//用户名或密码错误 } }catch(ClassNotFoundException e) { e.printStackTrace(); flag=-1;//系统异常 }catch(SQLException e) { e.printStackTrace(); flag=-1;//系统异常 }catch(Exception e) { e.printStackTrace(); flag=-1;//系统异常 }finally { try { if(rs!=null) rs.close(); if(pstmt!=null) pstmt.close(); if(connection!=null) connection.close(); }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); } } return flag; } }
View
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form action="LoginServlet" method="post"> 用户名:<input type="text" name="uname"><br/> 密码:<input type="password" name="upwd"><br/> <input type="submit" value="登录"><br/> </form> </body> </html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> 登陆成功!!! </body> </html>
Controller
LoginServlet.java
package org.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dao.LoginDao; import org.entity.Login; //控制器层:接受view层的请求,并分发给Model处理 public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理登录请求 request.setCharacterEncoding("utf-8"); String name= request.getParameter("uname"); String pwd= request.getParameter("upwd"); Login login=new Login(name,pwd); //调用模型层的登录功能 int result=LoginDao.login(login); if(result>0) { request.getRequestDispatcher("welcome.jsp").forward(request, response); }else {//返回登录页,重新登录 request.getRequestDispatcher("login.jsp").forward(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
登录失败,返回登录页面
二、三层架构
与MVC设计模式的目的一致:都是为了提高代码复用
区别:两者对项目的理解角度不同
三层结构的组成:
表示层(USL User Show Layer; View层):
1、表示层前台代码:jsp/html/css/js 等价于MVC中的V层:用于和用户的交互、界面的显示 web前端技术
代码位置:Webcontent
2、表示层后台代码:servlet用来调用业务逻辑层 等价于MVC中的C层:用于控制跳转、调用业务逻辑层 Servlet、SpringMVC、Struts2
代码位置:xxx.servlet
业务逻辑层(BLL Business Logic Layer; Service层):逻辑性,可拆
1、 接受表示层的请求、调用
2、 组装数据访问层:根据逻辑关系,对增删改查方法进行调用
代码位置:xxx.service
数据访问层(DAL Data Access Layer; Dao层):不可再分、原子性 直接访问数据库
增删改查的方法实现
代码位置:xxx.dao
三层间的关系:
上层将请求传递给下层,下层处理后,返回给上层
上层依赖于下层。 依赖:a持有b的成员变量,就是a依赖于b。先有b,后有a。
Servlet:
一个Servlet一般对于一个功能,如果有增删改查(查询单个、查询全部)五个功能,则创建五个Servlet
表示层前台
实例
对学生信息的增删改查,
index.jsp
<%@page import="org.student.entity.Student"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生信息列表</title> </head> <body> <table border="1px"> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>爱好</th> </tr> <% List <Student> students =(List<Student>) request.getAttribute("students"); for(Student student:students){ %> <tr> <td><%=student.getSno() %></td> <td><%=student.getSname() %></td> <td><%=student.getSage() %></td> <td><%=student.getShobby() %></td> <td><a href ="DeleteStudentServlet?sno=<%=student.getSno() %>">删除</a></td> <td><a href="QueryStudentServlet?sno=<%=student.getSno() %>">查询</a></td> </tr> <% } %> </table> </body> </html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加学生信息</title> </head> <body> <form action="AddStudentServlet" method="post"> 学号:<input type="text" name="sno"><br/> 姓名:<input type="text" name="sname"><br/> 年龄:<input type="text" name="sage"><br/> 爱好:<input type="text" name="shobby"><br/> <input type="submit" value="添加"> </form> </body> </html>
studentinfo.jsp
<%@page import="org.student.entity.Student"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生个人信息</title> </head> <body> <% Student student= (Student)request.getAttribute("student"); %> <form action="UpdateStudentServlet"> 学号:<input type="text" name="sno" value="<%=student.getSno()%>" readonly="readonly"><br/> 姓名:<input type="text" name="sname" value="<%=student.getSname()%>"><br/> 年龄:<input type="text" name="sage" value="<%=student.getSage()%>"><br/> 爱好:<input type="text" name="shobby" value="<%=student.getShobby()%>"><br/> <input type="submit" value="修改"> </form> </body> </html>
package org.student.dao;
package org.student.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 org.student.entity.Student; public class StudentDao { //数据库URL和账号密码 private static final String URL="jdbc:mysql://localhost:3306/login?serverTimezone=UTC&characterEncoding=utf-8"; private static final String UNAME="root"; private static final String UPWD="vayne"; //数据库连接 public static Connection getConn () { Connection conn = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL, UNAME, UPWD); } catch (Exception e) { e.printStackTrace(); } return conn; } public static void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs) { try { if(conn!=null) conn.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } try { if(rs!=null) rs.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } //关闭conn和pstmt public static void closePart(Connection conn,PreparedStatement pstmt) { try { if(conn!=null) conn.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } //添加学生信息 public static boolean AddStudent(Student student) { boolean flag = false; String sql="insert into student(sno,sname,sage,shobby) values(?,?,?,?)" ; Connection conn = StudentDao.getConn(); PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1,student.getSno()); pstmt.setString(2, student.getSname()); pstmt.setInt(3, student.getSage()); pstmt.setString(4, student.getShobby()); int count = pstmt.executeUpdate(); if(count>0) { flag=true; } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { StudentDao.closePart(conn, pstmt); } return flag; } //根据学号删除学生信息 public static boolean DeleteStudent(int sno) { boolean flag = false; String sql="delete from student where sno =?" ; Connection conn = StudentDao.getConn(); PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1,sno); int count = pstmt.executeUpdate(); if(count>0) { flag=true; } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { StudentDao.closePart(conn, pstmt); } return flag; } //根据学号修改学生信息:根据sno找到学生,并将学生改为student public static boolean UpdateStudent(int sno,Student student) { boolean flag = false; String sql="update student set sname =?,sage=?,shobby=? where sno =?" ; Connection conn = StudentDao.getConn(); PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getSname()); pstmt.setInt(2, student.getSage()); pstmt.setString(3, student.getShobby()); pstmt.setInt(4, sno); int count = pstmt.executeUpdate(); if(count>0) { flag=true; } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { StudentDao.closePart(conn, pstmt); } return flag; } //查询学生是否存在 public static boolean isExist(int sno) { return Query(sno)==null? false:true; } //根据学号查询学生全部信息 public static Student Query(int sno) { Student student= null; String sql="select * from student where sno =?" ; Connection conn = StudentDao.getConn(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1,sno); rs = pstmt.executeQuery(); if(rs.next()) { int no=rs.getInt("sno"); String name=rs.getString("sname"); int age=rs.getInt("sage"); String hobby=rs.getString("shobby"); student= new Student(no,name,age,hobby); } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { StudentDao.closeAll(conn, pstmt, rs); } return student; } //查询全部学生信息 public static List<Student> QueryAll() { List<Student> students = new ArrayList<>(); Student student= null; String sql="select * from student " ; Connection conn = StudentDao.getConn(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while(rs.next()) { int no=rs.getInt("sno"); String name=rs.getString("sname"); int age=rs.getInt("sage"); String hobby=rs.getString("shobby"); student= new Student(no,name,age,hobby); students.add(student); } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { StudentDao.closeAll(conn, pstmt, rs); } return students; } }
package org.student.entity;
package org.student.entity; public class Student { private int sno; private String sname; private int sage; private String shobby; @Override public String toString() { return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", shobby=" + shobby + "]"; } public Student() { } public Student( String sname, int sage, String shobby) { this.sname = sname; this.sage = sage; this.shobby = shobby; } public Student(int sno, String sname, int sage, String shobby) { this.sno = sno; this.sname = sname; this.sage = sage; this.shobby = shobby; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public String getShobby() { return shobby; } public void setShobby(String shobby) { this.shobby = shobby; } }
org.student.service
package org.student.service; import org.student.entity.Student; import java.util.List; import org.student.dao.*; public class StudentService { public boolean AddStudent(Student student) { boolean flag=false; if(!StudentDao.isExist(student.getSno())) { StudentDao.AddStudent(student); flag=true; }else { System.out.println("此人已存在"); } return flag; } //根据学号进行删除 public boolean DeleteStudent(int sno) { boolean flag=false; if(StudentDao.isExist(sno)) { StudentDao.DeleteStudent(sno); flag=true; }else { System.out.println("此人不存在"); } return flag; } //根据学号进行修改 public boolean UpdateStudent(int sno,Student student) { boolean flag=false; if(StudentDao.isExist(sno)) { StudentDao.UpdateStudent(sno,student); flag=true; }else { System.out.println("此人不存在"); } return flag; } //根据学号查询学生 public Student Query(int sno) { return StudentDao.Query(sno); } //查询全部学生 public List<Student> QueryAll(){ return StudentDao.QueryAll(); } }
package org.student.servlet;
AddStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.StudentService; public class AddStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); int no= Integer.parseInt(request.getParameter("sno")); String name= request.getParameter("sname"); int age= Integer.parseInt(request.getParameter("sage")); String hobby= request.getParameter("shobby"); Student student = new Student(no,name,age,hobby); StudentService studentservice = new StudentService(); boolean result=studentservice.AddStudent(student); //out对象的获取方法 PrintWriter out = response.getWriter(); if(result) { out.println("添加成功"); }else { out.println("添加失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
DeleteStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.service.StudentService; public class DeleteStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); int no= Integer.parseInt(request.getParameter("sno")); StudentService studentservice = new StudentService(); boolean result=studentservice.DeleteStudent(no); //out对象的获取方法 PrintWriter out = response.getWriter(); if(result) { out.println("删除成功"); response.sendRedirect("QueryAllStudentServlet"); }else { out.println("删除失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
QueryAllStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.StudentService; public class QueryAllStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); StudentService studentservice = new StudentService(); List<Student> students=studentservice.QueryAll(); //out对象的获取方法 PrintWriter out = response.getWriter(); request.setAttribute("students", students); request.getRequestDispatcher("index.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
QueryStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.StudentService; public class QueryStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //获取待查询修改人的学号 int no= Integer.parseInt(request.getParameter("sno")); StudentService studentservice = new StudentService(); Student student=studentservice.Query(no); //out对象的获取方法 PrintWriter out = response.getWriter(); out.println(student); request.setAttribute("student", student); request.getRequestDispatcher("studentinfo.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
UpdateStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.StudentService; public class UpdateStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //获取待修改人的学号 int no= Integer.parseInt(request.getParameter("sno")); //获取修改后的内容 String name= request.getParameter("sname"); int age= Integer.parseInt(request.getParameter("sage")); String hobby= request.getParameter("shobby"); //将修改后的内容封装到一个实体类中 Student student = new Student(name,age,hobby); StudentService studentservice = new StudentService(); boolean result=studentservice.UpdateStudent(no,student); //out对象的获取方法 PrintWriter out = response.getWriter(); if(result) { out.println("修改成功"); response.sendRedirect("QueryAllStudentServlet"); }else { out.println("修改失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
点击删除
进行查询
进行修改
今天在测试过程中遇到了Servlet找不到的问题,就是因为我多加了个空格
来源:https://www.cnblogs.com/yeyueweiliang/p/12215978.html