JAVA_web:使用HTML (jsp)+ Bootstrap + Servlet(Web层) + Servicec层 + DAO层 + Spring JdbcTemplate + Druid + MySQL
前言
逻辑不是太难,重要的是用心认认真真的自己把代码写出来。可以先模仿,毕竟一开始谁不是面向百度编程??
先贴项目目录,可以照着我这个创建文件夹。其中每一块的的代码我都会贴出来供大家参考使用。需要完整文件的请留下邮箱。
如有错误之处,请各位大佬指点一二。 在之后这代码还是会根据的老师的讲解进行一些改进,如果有兴趣的话可以关注了解下。
一、1.SQLyog中创建smart数据库,t_user表,插入初始化数据。
我自己使用的是SQLyog,你如果使用别的也是可以的。这没有规定的,那个用起来舒服你用那个。
CREATE DATABASE `smart` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; -- 创建smart数据库,使用utf8mb4编码保存数据
USE `smart`; -- 打开smart数据库
DROP TABLE IF EXISTS `t_user`; -- 如果t_user表存在,删除
CREATE TABLE `t_user` ( -- 创建t_user表
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`email` varchar(25) DEFAULT NULL,
`phone` varchar(16) DEFAULT NULL,
`gender` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
insert into `t_user`(`id`,`username`,`password`,`email`,`phone`,`gender`)
values (1,'admin','222','admin@gmail.com','13797745745',1);
二、2.IDEA中创建web工程logindemo,工程
src目录下拷入druid.properties (这个是JDBC 数据库的配置文件)
web目录下拷入css,js目录 (因为完全是自己编写,没有前端妹子帮助开发)
把jar包拷入lib目录 (不用说都懂吧! 不懂的请百度)
工程目录下创建dbscript目录,拷入smart.sql (这个是上面的创建数据库的代码)
文件名称:druid.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smart?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8&autoReconnect=true
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
三、创建JdbcUtils.java,读取配置参数,创建数据库连接池
package com.smart.login.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
/**
* 获取连接池
*
* 初始化连接池
*
*
*/
public class JdbcUtils {
private static DataSource ds;
static {
try {
// 加载配置文件
Properties pro = new Properties();
//使用 ClassLoader 加载配置文件 ,获取字节输入流
InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
// 初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
}catch(Exception ex){
ex.printStackTrace();
}
}
//获取连接池对象
public static DataSource getDataSource() {
return ds;
}
}
四、创建实体类User.java, 实体类中的属性和t_user表中的字段一致。
package com.smart.login.entity;
public class User implements java.io.Serializable{
private int id;
private String username;
private String password;
private String email;
private String phone;
private int gender; // 0---女 1---男
public User() {}
public User(int id, String username, String password, String email, String phone, int gender) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.gender = gender;
}
public User(String username, String password, String email, String phone, int gender) {
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.gender = gender;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", gender=" + gender +
'}';
}
}
五、创建DAO层,提供UserDao接口和UserDaoImpl实现类。
登录:select * from t_user where username=? and password=?
User findUser(String username,String password);
注册:insert into t_user values (null,?,?,?,?,?);
int insertUser(User user);
UserDaoImpl实现类
package com.smart.login.dao.impl;
import com.smart.login.dao.entity.User;
import com.smart.login.dao.UserDao;
import com.smart.login.dao.util.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDaoImpl implements UserDao {
//使用spring来简化 JDBCtempalte操作
private JdbcTemplate jt = new JdbcTemplate(JdbcUtils.getDataSource());
@Override
public User findUser(String username, String password) {
String sql = "select * from t_user where username=? and password=?";
return (User) jt.queryForList(sql,new BeanPropertyRowMapper<User>(User.class),username,password);
}
@Override
public int insertUser(User user) {
String sql="inset into t_user values (null,?,?,?,?,?)";
return jt.update(sql,user.getUsername(),user.getPassword(),user.getEmail(),user.getPhone(),user.getGender());
}
}
提供UserDao接口
package com.smart.login.dao;
import com.smart.login.dao.entity.User;
public interface UserDao {
User findUser(String username, String password);
int insertUser(User user);
}
六、创建Service层,提供UserService接口和UserServiceImpl实现类。
登录功能:User login(String username,String passwod)
注册功能:int register(Useruser);
UserService接口
package com.smart.login.service;
import com.smart.login.entity.User;
public interface UserService {
User login(String username, String passwod);
int register(User user);
}
UserServiceImpl实现类
package com.smart.login.service.impl;
import com.smart.login.dao.UserDao;
import com.smart.login.dao.impl.UserDaoImpl;
import com.smart.login.entity.User;
import com.smart.login.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl(){
userDao = new UserDaoImpl();
}
@Override
public User login(String username, String password) {
if(username != null && password != null){
return userDao.findUser(username, password);
}
return null;
}
@Override
public int register(User user) {
if(user != null){
return userDao.insertUser(user);
}
return 0;
}
}
七、创建Web层,LoginServlet, RegisterServlet
LoginServlet
package com.smart.login.web;
import com.smart.login.dao.entity.User;
import com.smart.login.service.UserService;
import com.smart.login.service.impl.UserServiceImpl;
import javax.servlet.RequestDispatcher;
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 java.io.IOException;
@WebServlet(name = "LoginServlet" ,urlPatterns="/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this .doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String username =request.getParameter("username");
String password =request.getParameter("password");
UserService userService = new UserServiceImpl();
User user=userService.login(username,password);
if(user.getUsername() !=null && user.getPassword()!=null){
//跳转到主界面home.html
RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.html");
rd.forward(request, response);
}else {
//跳转到登录界面login.html
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
rd.forward(request, response);
}
}
}
RegisterServlet
package com.smart.login.web;
import com.smart.login.dao.entity.User;
import com.smart.login.service.UserService;
import com.smart.login.service.impl.UserServiceImpl;
import javax.servlet.RequestDispatcher;
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 java.io.IOException;
@WebServlet(name = "LoginServlet" ,urlPatterns="/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this .doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String username =request.getParameter("username");
String password =request.getParameter("password");
UserService userService = new UserServiceImpl();
User user=userService.login(username,password);
if(user.getUsername() !=null && user.getPassword()!=null){
//跳转到主界面home.html
RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.html");
rd.forward(request, response);
}else {
//跳转到登录界面login.html
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
rd.forward(request, response);
}
}
}
八、创建login.jsp home.jsp register.jsp
- .创建 login.html
用户登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"/>
<script src="./js/jquery-3.5.1.js" type="text/javascript"></script>
<script src="./js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container" style="width: 400px;margin-top: 100px">
<h1 class="display-4" style="text-align: center">用户登录</h1>
<form action="/logindemo/login" method="POST">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" name="username" class="form-control" id="username" placeholder="请输入用户名"><br/>
</div>
<div class="form-group">
<label>密码:</label>
<input type="password" name="password" class="form-control" placeholder="请输入密码"><br/>
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn btn-primary" type="submit" value="登录"><a href="/logindemo/register.jsp">没有用户,请先注册</a>
</div>
</form>
</div>
</body>
</html>
2.创建home.jsp
主界面登录成功后的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主界面</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"/>
<script src="./js/jquery-3.5.1.js" type="text/javascript"></script>
<script src="./js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<h1 class="disabled-1" style="text-align: center">我是主界面</h1>
</div>
</body>
</html>
3创建 register.jsp
用户注册的界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册用户</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"/>
<script src="./js/jquery-3.5.1.js" type="text/javascript"></script>
<script src="./js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container" style="width: 400px;margin-top: 100px">
<h1 class="display-4" style="text-align: center">用户注册</h1>
<form action="/logindemo/register" method="POST">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" name="username" class="form-control" id="username" placeholder="请输入用户名"><br/>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"><br/>
</div>
<div class="form-group">
<label for="email">邮箱:</label>
<input type="email" name="email" class="form-control" id="email"><br/>
</div>
<div class="form-group">
<label for="phone">电话:</label>
<input type="text" name="phone" class="form-control" id="phone"><br/>
</div>
<div class="form-group">
性别:
<input type="radio" name="gender" value="1">男
<input type="radio" name="gender" value="0" checked>女
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn btn-primary" type="submit" value="注册">
<a href="/logindemo/login.html">已有用户,返回登录</a>
</div>
</form>
</div>
</body>
</html>
八、运行截图
1.这个对应的是login.html
2.这个对应的是 home.jsp
3.这个对应的是
九:总结
如果想理解上面的代码必须要先理解,我下面放的这张图片。代码是一个一个敲出来的。希望我的文章对你有所帮助。