MVC四层架构实现用户注册

整体的目录结构

MVC四层架构实现用户注册_第1张图片

我们从上向下依次写代码

controller(Servlet文件)

package com.sz.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sz.entity.User;
import com.sz.service.UserService;
import com.sz.service.Impl.UserServiceImpl;

/**
 * 向用户中添加信息,注册
 */
/**
 * Servlet implementation class UserSaveController
 */
@WebServlet("/UserSaveController")
public class UserSaveController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserSaveController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码集
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		
		String name = request.getParameter("uname");
		int age = Integer.parseInt(request.getParameter("age"));
		String birth = request.getParameter("birth");
		double salary = Double.parseDouble(request.getParameter("salary"));
		
		UserService service = new UserServiceImpl();
		
		//创建输出流
		PrintWriter pw = response.getWriter();
		User u = new User(0,name,age,birth,salary);
		if(service.saveUser(u)) {//成功
			pw.print("

用户注册成功

"
); }else {//失败 pw.print("

用户注册失败

"
); } pw.flush(); pw.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

dao包(.class文件)

package com.sz.dao;

import com.sz.entity.User;
import com.sz.util.JDBCUtil;

/**
 * 数据访问层
 * @author 樊**
 *
 */
public class UserDAO {
	
	public int insertUser(User user) {
		String sql = "insert into t_stu values(default,'"+user.getUname()+"','"+user.getAge()+"','"+user.getBirth()+"','"+user.getSalary()+"')";
		return JDBCUtil.executeSQL(sql);
	}
}

entity包(.class文件)

package com.sz.entity;

public class User {
	private int id;
	private String uname;
	private int age;
	private String birth;
	private double salary;
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getBirth() {
		return birth;
	}
	public void setBirth(String birth) {
		this.birth = birth;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public User(int id, String uname, int age, String birth, double salary) {
		super();
		this.id = id;
		this.uname = uname;
		this.age = age;
		this.birth = birth;
		this.salary = salary;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", uname=" + uname + ", age=" + age + ", birth=" + birth + ", salary=" + salary + "]";
	}
}

service下的Impl包中的UserServiceImpl(.class)

在这里插入图片描述

package com.sz.service.Impl;

import com.sz.dao.UserDAO;
import com.sz.entity.User;
import com.sz.service.UserService;

public class UserServiceImpl implements UserService{

	private UserDAO dao = new UserDAO();
	
	@Override
	public boolean saveUser(User user) {
		if(dao.insertUser(user) > 0) {
			return true;
		} else {
			return false;
		}
	}
}

标service包下的UserService(接口)

在这里插入图片描述

package com.sz.service;

import com.sz.entity.User;

public interface UserService {
	public boolean saveUser(User user); 
	
}

util包

package com.sz.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 操作数据库的工具类
 * @author 樊**
 *
 */
public class JDBCUtil {
	private static final String DB_USER_NAME = "root";//数据库的用户名
	private static final String DB_PASSWORD ="root";//数据库密码
	private static final String DB_NAME = "student";//数据库名称
	private static final String IP = "127.0.0.1";//127.0.0.1安装mysql数据库的服务器的ip地址
	private static final String	URL="jdbc:mysql://"+IP+":3306/"+DB_NAME;//mysql连接地址
	//private static final String URL = "jdbc:mysql://"+IP+":3306/"+DB_NAME+"?serverTimezone=UTC";//mysql连接地址
	
	private static Connection conn;//创建连接对象
	private static Statement stmt;//执行sql语句的对象,执行命令的对象
	private static ResultSet rs;//保存select之后查询结果的数据的对象
	
	/**
	 * 获得连接对象
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private static Connection getCon() throws ClassNotFoundException, SQLException{
		//加载mysql驱动
		//Class.forName("com.mysql.cj.jdbc.Driver");
		Class.forName("com.mysql.jdbc.Driver");
		if(conn == null || conn.isClosed()){//防止多次赋值
			conn = DriverManager.getConnection(URL, DB_USER_NAME, DB_PASSWORD);
		}
		return conn;
	}
	
	/**
	 * 获得Statement对象,用于执行sql语句
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private static Statement openStmt() throws ClassNotFoundException, SQLException{
		stmt = getCon().createStatement();
		return stmt;
	}
	
	/**
	 * 执行数据库的增(insert)、删(delete)、改(update)的操作
	 * @param sql
	 * @return
	 */
	public static int executeSQL(String sql){
		int i = 0;
		try {
			i = openStmt().executeUpdate(sql);//执行sql语句
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			//关闭数据库相关对象
			close();
		}
		return i;
	}
	/**
	 * 执行数据库查询(select)的操作
	 * @param sql
	 * @return
	 */
	public static ResultSet search(String sql){
		try {
			rs = openStmt().executeQuery(sql);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * 关闭数据库的方法
	 */
	public static void close(){
		try {
			if(rs != null){
				rs.close();//关闭ResultSet,顺序很重要不要错
			}
			if(stmt != null){
				stmt.close();//关闭Statement
			}
			if(conn != null){
				conn.close();//关闭Connection对象
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}

regedit.jsp(编码集都是UTF-8 记得改要不然全是乱码)

<%@ 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>
	<form action="UserSaveController" method="get">
		用户名:<input name="uname" type="text" size="12"/><br/>
 		年龄:<input name="age" type="text" size="12"/><br/>
  		生日:<input name="birth" type="text" size="12"/><br/>
 	    工资:<input name="salary" type="text" size="12"/><br/>
  		<input type="submit" value="注册"/>
  		<input type="reset" value="重置"/>
	</form>
</body>
</html>

数据库中的结构如下:

MVC四层架构实现用户注册_第2张图片

注意:要记得的改项目的编码集为utf-8。

下面开始测试:

浏览器中输入如下网址:http://127.0.0.1:8080/20210911/regrdit.jsp会出现如下页面。
MVC四层架构实现用户注册_第3张图片
然后输入信息入下。
MVC四层架构实现用户注册_第4张图片
点击注册。跳转到如下界面。
在这里插入图片描述
然后返回到你的数据库,刷新数据库。会看到刚才注册的信息出现到了数据库中。
MVC四层架构实现用户注册_第5张图片

至此,恭喜你已经完成了MVC四层架构的用户注册模式。说说我自己的感受吧,第一次接触四层架构的时候比较绕,绕来绕去的,想在网上找资料,结果发现全都是付费的,这对于我这个穷人来讲实在是太难受了,所以索性自己跟老师学会了,自己发布一个博客,方便我后期自己学习。

你可能感兴趣的:(java,mvc)