一、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 hereController
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);
}
}
登录失败,返回登录页面
二、三层架构
与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
学生信息列表学号 | 姓名 | 年龄 | 爱好 |
---|
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);
}
}
点击删除
进行查询
进行修改
今天在测试过程中遇到了Servlet找不到的问题,就是因为我多加了个空格