c mysql三层架构实例_MVC实例及用三层架构实现对学生信息的增删改查

一、MVC设计模式实例

M层

Login.java

package org.entity;

public class Login {

private intid;

private String uname;

private String upwd;

public Login() {

}

public Login( String uname, String upwd) {

this.uname =uname;

this.upwd =upwd;

}

public Login(intid, String uname, String upwd) {

this.id =id;

this.uname =uname;

this.upwd =upwd;

}

public intgetId() {

returnid;

}

public void setId(intid) {

this.id =id;

}

public String getUname() {

returnuname;

}

public voidsetUname(String uname) {

this.uname =uname;

}

public String getUpwd() {

returnupwd;

}

public voidsetUpwd(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 staticint 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();

}

}returnflag;

}

}

View

login.jsp

登录用户名:

密码:

welcome.jsp

Insert title here

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 {

protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//处理登录请求

request.setCharacterEncoding("utf-8");

String name= request.getParameter("uname");

String pwd= request.getParameter("upwd");

Login login=newLogin(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);

}

}

protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//TODO Auto-generated method stub

doGet(request, response);

}

}

d735cb17a5cff705ce0c4a71db07df37.png

41fb0c2439ce6501a71e5a006577a64d.png

87661b534841be7988df908ce823b2b5.png

eec47872c6dd98c834d3ab655572d005.png

登录失败,返回登录页面

550920ec281a029267be265e5a5693ec.png

二、三层架构

与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

表示层前台

实例

对学生信息的增删改查,

9175547d0afef523acd51941ed3acc44.png

index.jsp

学生信息列表
学号姓名年龄爱好

students =(List) request.getAttribute("students");for(Student student:students){%>

删除 查询

add.jsp

添加学生信息学号:

姓名:

年龄:

爱好:

studentinfo.jsp

学生个人信息学号:

姓名:

年龄:

爱好:

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();

}returnconn;

}

public staticvoidcloseAll(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 voidclosePart(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 booleanAddStudent(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);

}returnflag;

}//根据学号删除学生信息

public static boolean DeleteStudent(intsno) {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);

}returnflag;

}//根据学号修改学生信息:根据sno找到学生,并将学生改为student

public static boolean UpdateStudent(intsno,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);

}returnflag;

}//查询学生是否存在

public static boolean isExist(intsno) {return Query(sno)==null? false:true;

}//根据学号查询学生全部信息

public static Student Query(intsno) {

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= newStudent(no,name,age,hobby);

}

}catch(SQLException e) {

e.printStackTrace();

}catch(Exception e) {

e.printStackTrace();

}finally{

StudentDao.closeAll(conn, pstmt, rs);

}returnstudent;

}//查询全部学生信息

public static ListQueryAll() {

List 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= newStudent(no,name,age,hobby);

students.add(student);

}

}catch(SQLException e) {

e.printStackTrace();

}catch(Exception e) {

e.printStackTrace();

}finally{

StudentDao.closeAll(conn, pstmt, rs);

}returnstudents;

}

}

package org.student.entity;

package org.student.entity;

public class Student {

privateintsno;

private String sname;

privateintsage;

private String shobby;

@Override

public String toString() {return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", shobby=" + shobby + "]";

}

public Student() {

}

public Student( String sname,intsage, String shobby) {this.sname =sname;this.sage =sage;this.shobby =shobby;

}

public Student(int sno, String sname, intsage, String shobby) {this.sno =sno;this.sname =sname;this.sage =sage;this.shobby =shobby;

}

publicintgetSno() {returnsno;

}

publicvoid setSno(intsno) {this.sno =sno;

}

public String getSname() {returnsname;

}

publicvoidsetSname(String sname) {this.sname =sname;

}

publicintgetSage() {returnsage;

}

publicvoid setSage(intsage) {this.sage =sage;

}

public String getShobby() {returnshobby;

}

publicvoidsetShobby(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 {

publicbooleanAddStudent(Student student) {boolean flag=false;if(!StudentDao.isExist(student.getSno())) {

StudentDao.AddStudent(student);

flag=true;

}else{

System.out.println("此人已存在");

}returnflag;

}//根据学号进行删除

public boolean DeleteStudent(intsno) {boolean flag=false;if(StudentDao.isExist(sno)) {

StudentDao.DeleteStudent(sno);

flag=true;

}else{

System.out.println("此人不存在");

}returnflag;

}//根据学号进行修改

public boolean UpdateStudent(intsno,Student student) {boolean flag=false;if(StudentDao.isExist(sno)) {

StudentDao.UpdateStudent(sno,student);

flag=true;

}else{

System.out.println("此人不存在");

}returnflag;

}//根据学号查询学生

public Student Query(intsno) {returnStudentDao.Query(sno);

}//查询全部学生

public ListQueryAll(){returnStudentDao.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 {

protectedvoiddoGet(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= newStudent(no,name,age,hobby);

StudentService studentservice= newStudentService();boolean result=studentservice.AddStudent(student);//out对象的获取方法

PrintWriter out =response.getWriter();if(result) {

out.println("添加成功");

}else{

out.println("添加失败");

}

}

protectedvoiddoPost(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 {

protectedvoiddoGet(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= newStudentService();boolean result=studentservice.DeleteStudent(no);//out对象的获取方法

PrintWriter out =response.getWriter();if(result) {

out.println("删除成功");

response.sendRedirect("QueryAllStudentServlet");

}else{

out.println("删除失败");

}

}

protectedvoiddoPost(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 {

protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

response.setContentType("text/html; charset=utf-8");

StudentService studentservice= newStudentService();

List students=studentservice.QueryAll();//out对象的获取方法

PrintWriter out =response.getWriter();

request.setAttribute("students", students);

request.getRequestDispatcher("index.jsp").forward(request, response);

}

protectedvoiddoPost(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 {

protectedvoiddoGet(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= newStudentService();

Student student=studentservice.Query(no);//out对象的获取方法

PrintWriter out =response.getWriter();

out.println(student);

request.setAttribute("student", student);

request.getRequestDispatcher("studentinfo.jsp").forward(request, response);

}

protectedvoiddoPost(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 {

protectedvoiddoGet(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 = newStudent(name,age,hobby);

StudentService studentservice= newStudentService();boolean result=studentservice.UpdateStudent(no,student);//out对象的获取方法

PrintWriter out =response.getWriter();if(result) {

out.println("修改成功");

response.sendRedirect("QueryAllStudentServlet");

}else{

out.println("修改失败");

}

}

protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//TODO Auto-generated method stub

doGet(request, response);

}

}

106088fbf80b7fd22f41b009a4cf8e31.png

d2ae960401fe3199b0c320d19dc5b520.png

83c0664e1def91dfe8cdcf470db1deb9.png

d6edcd12df0aa7e83ba44694f4261888.png

1ee3d117d4f9e0ac5080df0d01afbea3.png

c3217590bee3aad6c7f83f8dbe22d189.png

7198f4bc5bf4223bd31c29baa717f1a0.png

68f724bad5a33d9a9f6bd2ca7369ecb7.png

2dd8be09d711a42c81068704ff828403.png

点击删除

43e8f4d162f003aacd8872d077110d4f.png

进行查询

416f32683309e58d050a9915e49f2fae.png

进行修改

c5618fd5421e357b8204d56793d03d0f.png

今天在测试过程中遇到了Servlet找不到的问题,就是因为我多加了个空格

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值