javaweb+mysql登录注册实现

javaweb+mysql登录注册实现

创建动态web项目: Saber1

在这里插入图片描述

新建servlet

LoginServlet

package com.saber.login;

import java.io.IOException;
import java.sql.SQLException;

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

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.saber.register.User;
import com.saber.utils.DataSourceUtils;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");

		// 1、获得用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 2、调用一个业务方法进行该用户查询
		User login = null;
		
			try {
				login = login(username, password);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		// 3、通过user是否为null判断用户名和密码是否正确
		if (login != null) {
			// 用户名和密码正确 登录成功 跳转到网站的首页
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		} else {
			/*用户名或密码错误
			跳回当前login.jsp
			使用转发 转发到login.jsp 向request域中存储错误信息*/
			request.setAttribute("loginInfo", "用户名或密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	public User login(String username, String password) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from user where username=? and password=?";
		User user = runner.query(sql, new BeanHandler<User>(User.class), username, password);
		return user;
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

RegisterServlet

package com.saber.register;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;

import com.saber.utils.DataSourceUtils;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1.设置request的编码---只适合post方式
		request.setCharacterEncoding("UTF-8");

		/*2.使用BeanUtils进行自动映射封装
		BeanUtils工作原理:将map中的数据 根据key与实体的属性的对应关系封装
		只要key的名字与实体的属性 的名字一样 就自动封装到实体中*/
		Map<String, String[]> properties = request.getParameterMap();
		User user = new User();
		
			try {
				BeanUtils.populate(user, properties);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
			//3、将参数传递给一个业务操作方法
			try {
				regist(user);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		
		//4、认为注册成功跳转到登录页面
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}

	//注册的方法
	public void regist(User user) throws SQLException{
		//操作数据库
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "insert into user(username,password,name,email,birthday,sex) values(?,?,?,?,?,?)";
		
		runner.update(sql,user.getUsername(),user.getPassword(),user.getName(),
				user.getEmail(),user.getBirthday(),user.getSex());
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

新建class

User
自动封装,快捷键:shift+alt+s

package com.saber.register;

public class User {

	private String username;
	private String password;
	private String name;
	private String email;
	private String birthday;
	private String sex;
	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 getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", name=" + name + ", email=" + email
				+ ", birthday=" + birthday + ", sex=" + sex + "]";
	}
	

}

DataSourceUtils

package com.saber.utils;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;


public class DataSourceUtils {

	private static DataSource dataSource = new ComboPooledDataSource();

	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	// 直接可以获取一个连接池
	public static DataSource getDataSource() {
		return dataSource;
	}

	// 获取连接对象
	public static Connection getConnection() throws SQLException {

		Connection con = tl.get();
		if (con == null) {
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}

/*
	// 开启事务
	public static void startTransaction() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.setAutoCommit(false);
		}
	}

	// 事务回滚
	public static void rollback() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.rollback();
		}
	}

	// 提交并且 关闭资源及从ThreadLocall中释放
	public static void commitAndRelease() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.commit(); // 事务提交
			con.close();// 关闭资源
			tl.remove();// 从线程绑定中移除
		}
	}

	// 关闭资源方法
	public static void closeConnection() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.close();
		}
	}

	public static void closeStatement(Statement st) throws SQLException {
		if (st != null) {
			st.close();
		}
	}

	public static void closeResultSet(ResultSet rs) throws SQLException {
		if (rs != null) {
			rs.close();
		}
	}
*/

}

新建xml

c3p0-config.xml
自己根据自身情况修改

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql:///saber3</property>
	</default-config> 
</c3p0-config> 

web.xml
创建动态web项目时自动生成的(先不要点finish,点击next两次,勾选xml自动生成),可以不创建

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Saber1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

新建css

style.css

@charset "UTF-8";
body{
	background-size:100%;
}

.center2 {
    position: absolute;
    width: 300px;
    height: 200px;
    /*background: #fcc;*/
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.an{
	background: no-repeat scroll 0 0 rgba(0, 0, 0, 0);
	height: 20px;
	width: 200px;
}
.ans{
	background: no-repeat scroll 0 0 rgba(0, 0, 0, 0);
	height: 35px;
	width: 200px;
}

新建jsp

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>萌新注册</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body style="background-image:url(image/beijing.jpg)">
<form action="/Saber1/RegisterServlet" method="post">
    <center class="center2">  
        <input type="text" class="an" name="username" placeholder="请输入账号  Username"><br/>
        <input type="password" class="an" name="password" placeholder="请输入密码  Psaaword"><br/>
        <input type="password" class="an" name="password" placeholder="请重新输入密码"><br/>
        
        <input type="text" class="an" name="name" placeholder="请输入昵称  Name"><br/>
        <input type="email" class="an" name="email" placeholder="邮箱:[email protected]"><br/>
        <input type="date" class="an" name="birthday" placeholder="生日:1999-9-1"><br/>
        
        <input type="radio" name="sex" value="男">男
        <input type="radio" name="sex" value="女">女
        <input type="radio" name="sex" value="保密">保密<br/>
        
        <label><a href="./login.jsp">已有账号?立即登录</a></label><br/>
        <input type="submit" class="ans" name="submit" value="注册  REGISTER">  
    </center>
</from>
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>绅士登录</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
</head>
<body style="background-image:url(image/beijing.jpg)">
<form action="/Saber1/LoginServlet" method="post">
    <center class="center2">
    	<div><%=request.getAttribute("loginInfo")==null?"":request.getAttribute("loginInfo")%></div>
    	
        <input type="text" class="an" id="username" name="username" placeholder="Username"><br/>
        <input type="password" class="an" id="inputPassword3" name="password" placeholder="Password"><br/>
        
        <label><a href="./register.jsp">没有账号?立即注册</a></label>
        <input type="submit" class="ans" name="submit" value="登录  LOGIN">  
    </center>
</from>
</body>
</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>宪兵队阁下</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body style="background-image:url(image/index.jpg)">

		<div>
			<a href="./register.jsp">注册</a>
			<a href="./login.jsp">退出</a>
		</div>
		<hr/>
		
<center class="center2">
	<div>
		<h1>欢迎您</h1>
	</div>
</center>
</body>
</html>

导入jar包

下载好之后,拖到WEB-INF—>lib目录下
https://pan.baidu.com/s/1at75DsPOJ3_z2HjjFqH4RA

在本地连接中 新建saber3数据库

然后执行该sql命令,用来创建user数据表

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50540
Source Host           : localhost:3306
Source Database       : saber3

Target Server Type    : MYSQL
Target Server Version : 50540
File Encoding         : 65001

Date: 2019-12-18 16:07:42
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `name` varchar(20) NOT NULL,
  `email` varchar(30) NOT NULL,
  `birthday` varchar(50) NOT NULL,
  `sex` varchar(10) NOT NULL,
  PRIMARY KEY (`id`,`username`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'qq', 'qq', 'qq', '[email protected]', '', '男');
INSERT INTO `user` VALUES ('2', 'qq', '22', 'qq', '[email protected]', '', '男');
INSERT INTO `user` VALUES ('3', '1', '1', '1', '[email protected]', '', '男');
INSERT INTO `user` VALUES ('4', '2', '2', '2', '[email protected]', '', '男');
INSERT INTO `user` VALUES ('5', '2', '[email protected]', '2', '[email protected]', '222', '男');
INSERT INTO `user` VALUES ('8', '1', '1', '2', '[email protected]', '1', '男');
INSERT INTO `user` VALUES ('9', '12', '12', '12', '[email protected]', '', '女');
INSERT INTO `user` VALUES ('10', '1', '1', '1', '[email protected]', '1', '保密');

在这里插入图片描述在这里插入图片描述

最终效果如下

在这里插入图片描述在这里插入图片描述在这里插入图片描述
在这里插入图片描述

发布了10 篇原创文章 · 获赞 4 · 访问量 754

猜你喜欢

转载自blog.csdn.net/weixin_43701595/article/details/103630365