一、问题描述
设计一个登录界面,若是老用户,则显示用户名、密码、出生年月、性别、照片;
若是新用户,则提供注册页面,包括用户名、密码、出生年月、性别、照片。
将用户的信息保存到数据库中,其中照片仅将文件名保存在表中,图片保存在服务器的img目录中。
二 、实现思路
三、实现步骤
1、创建数据库。 为了避免用户注册时使用重复的用户名,这里要将用户的name设为主键。
2、创建前端的页面,文件名为log.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录注册页面</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container right-panel-active">
<!-- 登录 signin-->
<div class="container__form container--signin">
<form action="./Log.jsp" class="form" id="form2" method="post">
<h2 class="form__title">欢迎登录</h2>
<input type="text" placeholder="用户名" class="input" name="user"/>
<input type="password" placeholder="密码" class="input" name="psd"/>
<input type = "submit" value="登录" class="btn">
</form>
</div>
<!-- 注册 signup-->
<div class="container__form container--signup">
<!-- 上传文件表单enctype属性必须为“multipart/form-data” -->
<form action="/myproject/upLoad" class="form" id="form1" method="post" enctype="multipart/form-data">
<h2 class="form__title">注册账号</h2>
<input type="text" placeholder="用户名" class="input" name="user1"/>
<input type="password" placeholder="密码" class="input" name="psd1"/>
<input type="text" placeholder="性别" class="input" name="sex"/>
<input type="text" placeholder="出生日期" class="input" name="birth"/>
上传照片
<input type="file" class="input" name="pic">
<input type = "submit" value="注册" class="btn">
</form>
</div>
<!-- 叠加部分 -->
<div class="container__overlay">
<div class="overlay">
<div class="overlay__panel overlay--left">
<button class="btn" id="signIn">已有账号,直接登录</button>
</div>
<div class="overlay__panel overlay--right">
<button class="btn" id="signUp">没有账号,点击注册</button>
</div>
</div>
</div>
</div>
</body>
<script src="./script.js"></script>
</html>
3. 装饰一下HTML,创建他的css文件,命名为“style.css”
:root {
--white: #e9e9e9;
--gray: #333;
--blue: #0367a6;
--lightblue: #008997;
--button-radius: 0.7rem;
--max-width: 758px;
--max-height: 520px;
font-size: 16px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body {
align-items: center;
background-color: var(--white);
background: url("bg.jpeg");
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
display: grid;
height: 100vh;
place-items: center;
}
.form__title {
font-weight: 300;
margin: 0;
margin-bottom: 1.25rem;
}
.link {
color: var(--gray);
font-size: 0.9rem;
margin: 1.5rem 0;
text-decoration: none;
}
.container {
background-color: var(--white);
border-radius: var(--button-radius);
box-shadow: 0 0.9rem 1.7rem rgba(0, 0, 0, 0.25),
0 0.7rem 0.7rem rgba(0, 0, 0, 0.22);
height: var(--max-height);
max-width: var(--max-width);
overflow: hidden;
position: relative;
width: 100%;
}
.container__form {
height: 100%;
position: absolute;
top: 0;
transition: all 0.6s ease-in-out;
}
.container--signin {
left: 0;
width: 50%;
z-index: 2;
}
.container.right-panel-active .container--signin {
transform: translateX(100%);
}
.container--signup {
left: 0;
opacity: 0;
width: 50%;
z-index: 1;
}
.container.right-panel-active .container--signup {
animation: show 0.6s;
opacity: 1;
transform: translateX(100%);
z-index: 5;
}
.container__overlay {
height: 100%;
left: 50%;
overflow: hidden;
position: absolute;
top: 0;
transition: transform 0.6s ease-in-out;
width: 50%;
z-index: 100;
}
.container.right-panel-active .container__overlay {
transform: translateX(-100%);
}
.overlay {
background-color: var(--lightblue);
background: url("bg.jpeg");
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
left: -100%;
position: relative;
transform: translateX(0);
transition: transform 0.6s ease-in-out;
width: 200%;
}
.container.right-panel-active .overlay {
transform: translateX(50%);
}
.overlay__panel {
align-items: center;
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
position: absolute;
text-align: center;
top: 0;
transform: translateX(0);
transition: transform 0.6s ease-in-out;
width: 50%;
}
.overlay--left {
transform: translateX(-20%);
}
.container.right-panel-active .overlay--left {
transform: translateX(0);
}
.overlay--right {
right: 0;
transform: translateX(0);
}
.container.right-panel-active .overlay--right {
transform: translateX(20%);
}
.btn {
background-color: var(--blue);
background-image: linear-gradient(90deg, var(--blue) 0%, var(--lightblue) 74%);
border-radius: 20px;
border: 1px solid var(--blue);
color: var(--white);
cursor: pointer;
font-size: 0.8rem;
font-weight: bold;
letter-spacing: 0.1rem;
padding: 0.9rem 4rem;
text-transform: uppercase;
transition: transform 80ms ease-in;
}
.form > .btn {
margin-top: 1.5rem;
}
.btn:active {
transform: scale(0.95);
}
.btn:focus {
outline: none;
}
.form {
background-color: var(--white);
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
padding: 0 3rem;
height: 100%;
text-align: center;
}
.input {
background-color: #fff;
border: none;
padding: 0.9rem 0.9rem;
margin: 0.5rem 0;
width: 100%;
}
@keyframes show {
0%,
49.99% {
opacity: 0;
z-index: 1;
}
50%,
100% {
opacity: 1;
z-index: 5;
}
}
4. 创建JavaScript文件,命名为“script.js”
// 获取元素和点击操作
const signInBtn = document.getElementById("signIn");
const signUpBtn = document.getElementById("signUp");
const fistForm = document.getElementById("form1");
const secondForm = document.getElementById("form2");
const container = document.querySelector(".container");
signUpBtn.addEventListener("click", () => {
container.classList.add("right-panel-active");
});
signInBtn.addEventListener("click", () => {
container.classList.remove("right-panel-active");
});
前端效果
5.登录功能判断页面。命名为"Log.jsp"
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用户名密码检验</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
//创建数据库连接
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=user";
String user="sa";
String password="123456";
Connection conn = DriverManager.getConnection(url,user,password);
Statement stmt = null;
ResultSet rs = null;
String name = request.getParameter("user");
String psd = request.getParameter("psd");
String sql_1 = "select * from user01 where name='"+ name+ "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql_1);
//如果数据库中存在该用户
if(rs.next()){
String real_psd = rs.getNString("password").trim();
if(psd.equals(real_psd)){
out.println("登录成功");
}
else{
out.println("密码错误");
}
}else{
out.println("用户名不存在");
}
%>
</body>
</html>
6.登录功能页面,命名为“upLoad.java”
package com.mypackage;
import java.io.IOException;
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.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class upLoad
*/
@WebServlet("/upLoad")
public class upLoad extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public upLoad() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String []data= new String[5];//创建一个数组,用于存放非文件类型的数据,以及文件名
//上传文件
try {
//得到上传文件的保存目录。 将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String realPath = this.getServletContext().getRealPath("/img");// /WEB-INF/files
System.out.println("文件存放位置:"+realPath);
//设置临时目录。 上传文件大于缓冲区则先放于临时目录中
String tempPath = "D:\\tempFile";
System.out.println("临时文件存放位置:"+tempPath);
//判断存放上传文件的目录是否存在(不存在则创建)
File f = new File(realPath);
if(!f.exists()&&!f.isDirectory()){
System.out.println("目录或文件不存在! 创建目标目录。");
f.mkdir();
}
//判断临时目录是否存在(不存在则创建)
File f1 = new File(tempPath);
if(!f1.isDirectory()){
System.out.println("临时文件目录不存在! 创建临时文件目录");
f1.mkdir();
}
/**
* 使用Apache文件上传组件处理文件上传步骤:
*
**/
//1、设置环境:创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置上传文件的临时目录
factory.setRepository(f1);
//2、核心操作类:创建一个文件上传解析器。
ServletFileUpload upload = new ServletFileUpload(factory);
//解决上传"文件名"的中文乱码
upload.setHeaderEncoding("UTF-8");
//3、判断enctype:判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
System.out.println("不是上传文件,终止");
//按照传统方式获取数据
return;
}
//==获取输入项==
//限制单个上传文件大小3M)
upload.setFileSizeMax(1024*1024*3);
//限制总上传文件大小(3M)
upload.setSizeMax(1024*1024*3);
//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
List<FileItem> items =upload.parseRequest(request);
System.out.println();
for(int i=0;i<items.size();i++){
FileItem item = items.get(i);
//如果fileitem中封装的是普通输入项的数据(输出名、值)
if(item.isFormField()){
String filedName = item.getFieldName();//普通输入项数据的名
//解决普通输入项的数据的中文乱码问题
String filedValue = item.getString("UTF-8");//普通输入项的值
data[i]=filedValue;
System.out.println(data[i]);
}else{
//如果fileitem中封装的是上传文件,得到上传的文件名称,
String fileName = item.getName();//上传文件的名
//将文件名写入数组中
data[4]=fileName;
//多个文件上传输入框有空 的 异常处理
if(fileName==null||"".equals(fileName.trim())){ //去空格是否为空
continue;// 为空,跳过当次循环, 第一个没输入则跳过可以继续输入第二个
}
//注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
//处理上传文件的文件名的路径,截取字符串只保留文件名部分。//截取留最后一个"\"之后,+1截取向右移一位("\a.txt"-->"a.txt")
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
//拼接上传路径。存放路径+上传的文件名
String filePath = realPath+"\\"+fileName;
//构建输入输出流
InputStream in = item.getInputStream(); //获取item中的上传文件的输入流
OutputStream out = new FileOutputStream(filePath); //创建一个文件输出流
//创建一个缓冲区
byte b[] = new byte[1024];
//判断输入流中的数据是否已经读完的标识
int len = -1;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))!=-1就表示in里面还有数据
while((len=in.read(b))!=-1){ //没数据了返回-1
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath+"\\"+filename)当中
out.write(b, 0, len);
}
//关闭流
out.close();
in.close();
//删除临时文件
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
item.delete();//删除处理文件上传时生成的临时文件
System.out.println("文件上传成功");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
throw new RuntimeException("服务器繁忙,文件上传失败");
}
//连接数据库,并将数据写入数据库中
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=user";
String user="sa";
String password="123456";
//
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Connection conn = DriverManager.getConnection(url,user,password);
String sql = "insert into user01 values(?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,data[0]);
pstmt.setString(2,data[1]);
pstmt.setString(3,data[2]);
pstmt.setString(4,data[3]);
pstmt.setString(5,data[4]);
pstmt.executeUpdate();
conn.close();
//页面跳转
request.getRequestDispatcher("/reg_success.jsp").forward(request,response);
} catch (SQLException e1) {
e1.printStackTrace();
response.sendError(response.SC_NOT_FOUND,e1.getMessage());
}
}
}
7.创建注册成功后的跳转页面,命名为“reg_success.jsp”
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>注册成功</title>
</head>
<body>
注册成功
</body>
</html>
8.eclipse工程文件目录
这里有几个包需要导入
四、问题总结
1.环境问题
ServletFileUpload.isMultipartContent(request)方法需要用Tomcat8.5版本(10以下应该可以),原来用的Tomcat10,一直说我没有导入包。
2.文件上传
(1)form表单enctype属性必须为“multipart/form-data”才能上传文件,但在此情况下无法用request.getParameter()获取非文件数据。
(2)form表单中<input type="file">框里显示的内容跟浏览器有关,有些会将路径也显示出来,有些则只显示文件名。建议使用谷歌浏览器。
3.数据库操作
在执行数据库操作时,这里用到了两种方法创建
方法一:creatStatement()
stmt = conn.createStatement();
rs = stmt.executeQuery(sql_1);
方法二:preparedStatement()
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Connection conn = DriverManager.getConnection(url,user,password);
String sql = "insert into user01 values(?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,data[0]);
pstmt.setString(2,data[1]);
pstmt.setString(3,data[2]);
pstmt.setString(4,data[3]);
pstmt.setString(5,data[4]);
pstmt.executeUpdate();
方法二在参数设置上灵活性更好。