目录
6、程序结构
6.1 MVC介绍
MVC: Model View Controller 模型(vo、dao、service等)、视图(jsp页面)、控制器(servlet)
-
Model(模型层):
- 业务逻辑处理
- 操作数据库
- 实体类
-
View(视图层):
- 展示数据模型
- 提供人机交互的操作
-
Controller(控制层)
- 接收用户的请求
- 转给业务层处理所需数据,获取处理后的数据
- 视图跳转(转发、重定向)
主要的基层结构:
1、 View 就是页面的开发。页面分为静态页面和动态页面。用于页面的编写语言有:HTML、DIV+CSS、Javascript、Ajax、ExtJs、Jquery、Jsp。流行的页面框架有:Freemarker、Vue等等。
View页面提交的方式有:
A. 通过form 表单提交
B. 在JavaScript中通过Ajax等方式提交
C. 通过浏览器的地址栏直接输入地址 提交
2、Servlet Interface :它的作用是处理从View页面提交过来的请求,并进行处理,然后将请求发送到Web服务器,最后将服务器的响应回送到浏览器。
每个Servlet必须实现javax.servlet.Servlet接口,而Servlet API提供了一个javax.servlet.HttpServlet类来实现Servlet接口。所以代码中只要Extends HttpServlet 就可以了。
Servlet 获取View页面提交过来的数据方式有:
3、ControlServlet extends HttpServlet:当一个类继承了HttpServlet时,只需要在doGet或者doPost方法中写相应的代码即可
4、Services:业务逻辑处理的服务类。ControlServlet获取数据后,调用相应的Services来处理业务逻辑。Services调用DAO-interface的实现类来执行相对应的数据库操作
5、DAO-Interface : DAO是Data Access Object数据访问接口,作为一个数据访问接口层,它主要的作用隐藏数据访问的具体代码,以提高系统的安全性和便利性。作为业务逻辑层的Services不管具体的数据访问代码,它只管调用指定的接口方法。
6、DAO—Implement :数据访问的具体实现类,里面执行对数据库的操作。比如: 查询、删除、修改、新增、执行试图、执行存储过程、创建表机构,删除表机构、修改表结构.
7、DataBase:数据库,存储数据的地方。
6.2 大致结构
根据MVC的基本结构在构建项目一般要创建如下的结构:
6.2.1 util包
util包主要封装一些辅助性的工具类,如JDBC连接数据库、封装一些常量等等。
几种常见的工具类:
-
JDBC连接数据库
添加MySQL的Maven依赖:
<!--添加mysql的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
创建util工具类DBHelper
package com.yu.util;
import com.mysql.cj.jdbc.Driver;
import sun.security.pkcs11.Secmod;
import java.sql.*;
public class DBHelper {
//创建单例
private DBHelper(){}
private static DBHelper dbh = new DBHelper();
public static DBHelper getDbh(){
return dbh;
}
//创建连接数据库的Connection
public Connection linkMysql() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://ip地址:3306/库名?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false";
String user = "root";
String password = "数据库密码";
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库,Connection相当于数据
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
//增删改的操作
public void update(String sql, Object...param) {
Connection conn = null;
/*执行sql语句的有两个对象:PreparedStatement和Statement
1、PreparedStatement是预编译的,对于批量处理可以大大提高效率. 也叫JDBC存储过程
它第一次执行消耗是很高的. 它的性能体现在后面的重复执行.
2、在对数据库只执行一次性存取的时侯,用 Statement 对象进行处理。
*/
PreparedStatement ps = null;
try {
conn = this.linkMysql();
ps = conn.prepareStatement(sql);
//设置sql语句的未知数
for(int i=0; i<param.length; i++){
ps.setObject(i+1,param[i]);
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
this.close(conn,ps,null);
}
}
//关闭
public void close(Connection conn, PreparedStatement ps, ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
6.2.2 vo包
vo类保存实体对象,每个类对应数据库的一张表,属性为表中每一个字段,如果其中的字段和其他表关联,则改为这个关联表的对象。当dao读取数据库的数据时,相应的数据保存到相应的实体类的对象中。
6.2.3 dao包
dao中的类是对数据库进行操作的,主要是对数据的增删改查等等操作。
dao创建的一般步骤为先创建dao的结构,在创建实现类来实现这个接口。
-
以登陆为例,先创建一个接口
public interface UserinfoDao{ Userinfo getUserifoByID(int id); Userinfo verifyUsernameAndPassword(String username , String password); void deleteUserinfoByID(int id); void setPassByID(String newPass ,int id); void addUserinfo(Userinfo userinfo); }
-
实现类
public class UserinfoDaoImpl implements UserinfoDao { //将实现类创建成单例模式 private static UserinfoDaoImpl userinfoDao = null; private UserinfoDaoImpl(){ if(userinfoDao!=null){ throw new RuntimeException(); } } public static UserinfoDaoImpl getUserinfoDaoImpl(){ if (userinfoDao == null) { synchronized (UserinfoDaoImpl.class) { if (userinfoDao == null) { userinfoDao = new UserinfoDaoImpl(); } } } return userinfoDao; } //实现接口中的方法 //根据用户名和密码返回用户,主要用于验证登陆时输入的验证码问题 public Userinfo verifyUsernameAndPassword(String username, String password){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Userinfo userinfo = null; try { conn = DBHelper.getDbh().linkMysql(); String sql = "SELECT user_info.id,user_info.user_name,user_info.password FROM user_info WHERE user_info.user_name=? AND user_info.password=?" ; ps = conn.prepareStatement(sql); //给sql语句中的?赋值 ps.setString(1,username); ps.setString(2,password); rs = ps.executeQuery(); if (rs.next()){ rs.next(),指针下移,返回值为Boolean userinfo = new Userinfo(); userinfo.setId(rs.getInt("id")); userinfo.setUsername(rs.getString("user_name")); userinfo.setPassword(rs.getString("password")); } } catch (Exception e) { e.printStackTrace(); }finally { DBHelper.getDbh().close(conn,ps,rs); } return userinfo; } //根据获取用户信息 public Userinfo getUserifoByID(int id){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Userinfo user = null; try { conn = DBHelper.getDbh().linkMysql(); String sql = "SELECT * FROM user_info WHERE id = ?"; ps= conn.prepareStatement(sql); ps.setInt(1,id); rs = ps.executeQuery(); if(rs.next()){ user = new Userinfo(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("user_name")); user.setPassword(rs.getString("password")); } } catch (Exception e) { e.printStackTrace(); }finally { DBHelper.getDbh().close(conn,ps,rs); } return user; } //根据id删除用户 public void deleteUserinfoByID(int id){ String sql = "DELETE FROM user_info WHERE user_info.id = ?"; DBHelper.getDbh().update(sql,id); } //根据id修改密码 public void setPassByID(String newPass ,int id){ String sql = "UPDATE user_info SET user_info.password = ? WHERE user_info.id = ?"; DBHelper.getDbh().update(sql,newPass,id); } //增加用户信息 public void addUserinfo(Userinfo userinfo){ String sql = "INSERT INTO user_info(user_info.user_name,user_info.password) VALUE (?,?)"; DBHelper.getDbh().update(sql,userinfo.getUsername(),userinfo.getPassword()); } }
6.2.4 jsp页面
进行数据交互和展示数据模型
1、form表单
2、Ajax
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<%String path = request.getContextPath();%>
<html>
<head>
<title>Title</title>
<script src="${path}/js/jquery-3.6.0.min.js"></script>
<script>
$(function () {
//点击退出登陆,注销用户
$("#cancellation").click(function () {
window.location="${path}/CancellationServlet";
});
//显示所有用户
$("#showUser").click(function () {
$.ajax({
url: "${path}/ShowUserServlet", //请求路径
data:{ //发送的数据
userId: $("#userid").val()
},
success:function (data) { //成功后执行的回调函数
$("#showSuccess").html(data);
}
});
});
});
</script>
</head>
<body>
<span>登陆成功:用户名:${userinfo.username},
密码:${userinfo.password}</span>
<div class="cancellation" id="cancellation">退出登陆</div>
<input type="number" id="userid" placeholder="请输入用户id">
<button class="showUser" id="showUser">显示用户</button>
<span id="showSuccess"></span>
</body>
</html>
6.2.5 servlet
主要是接收前端的数据,进行页面的转发等操作
1、登陆
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取前端的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//调用service层处理逻辑
LoginService loginService = new LoginServiceImpl();
Userinfo userinfo = loginService.login(username, password);
//userinfo==null说明用户名密码错误 !=null则登陆成功
//进行页面的转发或重定向
if(userinfo != null){
request.getSession().setAttribute(Constant.USER_SESSION,userinfo);
//重定向到主页
response.sendRedirect(request.getContextPath()+"/jsp/mainview/success.jsp");
}else{
//转到登陆界面,显示登陆失败
request.setAttribute("error", Constant.LOGIN_FAIL);
request.getRequestDispatcher("/jsp/login/login.jsp").forward(request,response);
}
}
}
2、处理ajax
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取前端的数据
String userId = request.getParameter("userId");
//调用service层处理逻辑
UserService UserService = new UserServiceImpl();
Userinfo user = UserService.getUser(Integer.valueOf(userId));
//给ajax请求传递数据
if(user==null){
response.getWriter().print("无此人");
}else{
response.getWriter().print("id:"+user.getId()+",用户名:"+user.getUsername()+",密码:"+user.getPassword());
}
}
}
6.2.6 service包
service和dao类似,需要先创建一个service的接口,然后通过实现类来实现接口
-
接口
public interface LoginService { Userinfo login(String username , String password); }
-
实现类
public class LoginServiceImpl implements LoginService { //获得dao的对象 private UserinfoDao userinfoDao; public LoginServiceImpl(){ userinfoDao = UserinfoDaoImpl.getUserinfoDaoImpl(); } //登陆操作 @Override public Userinfo login(String username, String password) { //验证用户名和密码 Userinfo userinfo = userinfoDao.verifyUsernameAndPassword(username, password); return userinfo; } }
6.2.7 Filter
…….
6.2.8 Listener
………