概述
话说:
各位读者晚上好!终于到了2018!2018年的第一篇博客哈!前面中断了不少篇,并非作者怠惰了,确实感觉“拿不出手”,嘿嘿。经过一段时间积累,这次就连续的发表一个系列吧——BBS论坛。
还是很基础很基础的东西,不过,从前端到后端,都是自己写的,完整的记录一个初级的小项目,也是很有纪念意义滴。
技术:
JSP+Servlet + 前端(HTML + CSS+JavaScript + Ajax)
整体难度系数:★★☆☆☆
开发环境:Eclipse Oxygen 2017.6
目录:
- 整体介绍
- 前期准备
- 登录、注册界面及基本验证
1.整体介绍
首页:论坛帖子展示;搜索;分栏目;
个人中心:对当前用户帖子的增删改查;
个人资料:个人头像上传及昵称、密码的修改。
整体效果如下:
2.前期准备
1.数据库准备
这个小项目整体用到四张表:
用户表-user
帖子表-text
栏目表-category
回复表-reply
表之间的关系比较简单:text表和userId categoryId对应,一个用户可以发多个帖子,每个帖子对应唯一的栏目;
栏目表独立;
回复表reply和userId textId对应,一个评论对应一个用户,可以有多个评论,一个帖子也有多个评论。这些关系具体有什么用呢?在写SQL语句的时候,要考虑到。
整体表结构如下:
不为效率为熟悉命令,全部用cmd命令创建,创建命令如下及初始化部分数据(虚构):
#创建数据库
create database db_bbs;
use db_bbs;
#创建表
create table user (
userId int auto_increment primary key,
userName varchar(50) not null,
userNick varchar(50) not null,
password varchar(50) not null,
rePassword varchar(50) ,
sex varchar(2),
phone varchar(50),
email varchar(50),
IDNumber varchar(100),
hobby varchar(50),
province varchar(20),
introduce varchar(1000),
loginTime varchar(50),
registerTime varchar(50)
);
#创建帖子表
create table text (
textId int auto_increment primary key comment "帖子Id",
title varchar(100) not null,
context varchar(3000) not null,
textTime varchar(50),
categoryId int,
userId int
)comment="帖子表";
#栏目表
create table category (
categoryId int auto_increment primary key,
categoryName varchar(50) not null
);
#评论表
create table reply (
replyId int auto_increment primary key,
replyContext varchar(10000) not null,
replyTime varchar(50),
textId int,
userId int
);
#模拟用户
insert into user (userName,userNick,password) values
("admin","微笑感染嘴角","000000"),
("admin1","舍我其谁","111111");
#模拟帖子
insert into text (title,context,textTime,categoryId,userId) values
("这是小美的第一条帖子,关于Java的","Java从入门到放弃","2017-12-30 10:38:23",1,1),
("这是小美的第二条帖子,关于MySQL的","MySQL从入门到放弃","2017-12-30 10:39:23",2,2),
("这是小美的第三条帖子,关于大数据的","大数据从入门到放弃","2017-12-30 10:40:23",3,1),
("这是小美的第四条帖子,关于人工智能的","人工智能从入门到放弃","2017-12-30 10:41:23",4,1),
("这是小美的第六条帖子,关于HTML5的","HTML5从入门到放弃","2017-12-30 10:42:23",5,1),
("这是小美的第七条帖子,关于生活的","生活从围城内到围城外","2017-12-30 10:50:23",6,2);
#模拟栏目
insert into category (categoryName) values
("Java"),
("MySQL"),
("大数据"),
("人工智能"),
("HTML5"),
("生活"),
("有趣有料");
#模拟评论
insert into reply (replyContext,replyTime,textId,userId) values
("哎呦喂,不错奥!","2017-12-30 10:48:43",1,1),
("哎呦喂,不错奥!","2017-12-30 10:49:45",1,1),
("哎呦喂,不错奥!","2017-12-30 10:50:45",1,1),
("哎呦喂,不错奥!","2017-12-30 10:48:45",1,1),
("哎呦喂,不错奥!","2017-12-30 10:52:45",1,1),
("哎呦喂,不错奥!","2017-12-30 10:48:45",2,1),
("哎呦喂,不错奥!","2017-12-30 10:55:45",2,1),
("哎呦喂,不错奥!","2017-12-30 10:58:45",2,1),
("哎呦喂,不错奥!","2017-12-30 10:59:45",2,1),
("哎呦喂,不错奥!","2017-12-30 10:32:45",3,1),
("哎呦喂,不错奥!","2017-12-30 10:12:45",3,1),
("哎呦喂,不错奥!","2017-12-30 10:11:45",3,1),
("哎呦喂,不错奥!","2017-12-30 10:10:45",4,1),
("哎呦喂,不错奥!","2017-12-30 10:14:45",4,1);
#查出来的结果应该是这样的:
# 评论数:5 4 3 2 0 0
2.包的准备
按照MVC分层设计思想,建好包之后如下:
3.登录注册
3.1 注册
3.1.1 注册页面设计
3.1.2 User实体类
3.1.3 前端验证
3.1.4 service dao controller
3.2 登录
3.2.1 登录页面设计
3.2.2 前端简单验证
3.2.2 service dao controller
3.1 注册
3.1.1 注册页面设计
注册获取信息比较全,前端验证比较简单,只是对非空做了判断,未加入正则表达式。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!--Author:Meice 2017年12月30日下午12:16:04 -->
<!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 href="css/register.css" rel="styleSheet" type="text/css">
<!--非常重要的样式写在里面 -->
<style type="text/css">
textarea{
resize: none;
}
</style>
<!--引入JS验证 -->
<script type="text/javascript" src="js/register.js"></script>
</head>
<body>
<!-- 引入头部-->
<jsp:include page="head.jsp"></jsp:include>
<!-- 注册界面-->
<div id="registerForm">
<form name="regForm" action="addUser" method="get" onsubmit=" return checkRegisterForm()" >
<!-- border="1px solid red" -->
<table cellspacing="15" cellpadding="10" style="padding-left: 60px">
<tr>
<!-- align="center" -->
<td colspan="2" style="font-size:30px;font-weight:bolder;color:green;padding-left:130px;">注册</td>
</tr>
<tr>
<td colspan="2"><span id="regInfo" style="color:red;font-size:15px;font-weight:bolder;"></span></td>
</tr>
<tr>
<td>用户名</td>
<td>
<input type="text" name="userName" class="myInput" />
</td>
</tr>
<tr>
<td>昵称</td>
<td>
<input type="text" name="userNick" class="myInput">
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="password" class="myInput">
</td>
</tr>
<tr>
<td>确认密码</td>
<td>
<input type="password" name="rePassword" class="myInput">
</td>
</tr>
<tr>
<td>手机号</td>
<td>
<input type="text" name="phone" class="myInput">
</td>
</tr>
<tr>
<td>邮箱</td>
<td>
<input type="text" name="email" class="myInput">
</td>
</tr>
<tr>
<td>身份证号</td>
<td>
<input type="text" name="IDNumber" class="myInput">
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女
</td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" name="hobby" value="篮球">篮球
<input type="checkbox" name="hobby" value="游泳">游泳
<input type="checkbox" name="bobby" value="象棋">象棋
<input type="checkbox" name="bobby" value="钢琴">钢琴
<input type="checkbox" name="hobby" value="蹦极">蹦极
</td>
</tr>
<tr>
<td>省份</td>
<td>
<select name="province">
<option value="" >选择省份</option>
<option value="陕西">陕西</option>
<option value="北京">北京</option>
<option value="广东">广东</option>
<option value="上海">上海</option>
</select>
</td>
</tr>
<tr>
<td>自我介绍</td>
<td>
<textarea name="introduce" placeholder="来段自我介绍呗..." cols="45" rows="3"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="注册" style="width: 100px;height:30px;">
<input type="reset" value="重置" style="width:100px;height:30px;">
</td>
</tr>
</table>
</form>
</div>
<!--引入尾部 -->
<jsp:include page="foot.jsp"></jsp:include>
</body>
</html>
这里面头部和尾部直接加入另外的页面,使用的是include标签,非常灵活。
3.1.2 User实体类
注册是获取用户信息的关键环节,这里就尽可能多的获取信息喽。
package com.hmc.pojo;
/**
*
*2017年12月30日
*User:Meice
*下午8:23:36
*/
public class User {
//用户表
/**
*
* userId int auto_increment primary key,
userName varchar(50) not null,
userNick varchar(50) not null,
password varchar(50) not null,
rePassword varchar(50) ,
sex varchar(2),
phone varchar(50),
email varchar(50),
IDNumber varchar(100),
hobby varchar(50),
province varchar(20),
introduce varchar(1000),
loginTime varchar(50),
registerTime varchar(50)
*/
private int userId;
private String userName;
private String userNick;
private String password;
private String rePassword;
private String sex;
private String phone;
private String email;
private String IDNumber;
private String hobby;
private String province;
private String introduce;
private String loginTime;
private String registerTime;
public User() {}
public User(int userId, String userName, String userNick, String password, String rePassword, String sex,
String phone, String email, String iDNumber, String hobby, String province, String introduce,
String loginTime, String registerTime) {
super();
this.userId = userId;
this.userName = userName;
this.userNick = userNick;
this.password = password;
this.rePassword = rePassword;
this.sex = sex;
this.phone = phone;
this.email = email;
IDNumber = iDNumber;
this.hobby = hobby;
this.province = province;
this.introduce = introduce;
this.loginTime = loginTime;
this.registerTime = registerTime;
}
public User( String userName, String userNick, String password, String rePassword, String sex,
String phone, String email, String iDNumber, String hobby, String province, String introduce
,String registerTime) {
this.userName = userName;
this.userNick = userNick;
this.password = password;
this.rePassword = rePassword;
this.sex = sex;
this.phone = phone;
this.email = email;
IDNumber = iDNumber;
this.hobby = hobby;
this.province = province;
this.introduce = introduce;
this.registerTime = registerTime;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserNick() {
return userNick;
}
public void setUserNick(String userNick) {
this.userNick = userNick;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRePassword() {
return rePassword;
}
public void setRePassword(String rePassword) {
this.rePassword = rePassword;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIDNumber() {
return IDNumber;
}
public void setIDNumber(String iDNumber) {
IDNumber = iDNumber;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public String getLoginTime() {
return loginTime;
}
public void setLoginTime(String loginTime) {
this.loginTime = loginTime;
}
public String getRegisterTime() {
return registerTime;
}
public void setRegisterTime(String registerTime) {
this.registerTime = registerTime;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", userNick=" + userNick + ", password=" + password
+ ", rePassword=" + rePassword + ", sex=" + sex + ", phone=" + phone + ", email=" + email
+ ", IDNumber=" + IDNumber + ", hobby=" + hobby + ", province=" + province + ", introduce=" + introduce
+ ", loginTime=" + loginTime + ", registerTime=" + registerTime + "]";
}
}
3.1.3 前端验证
用JavaScript做简单的非空验证:
register.js
function checkRegisterForm() {
//alert("进来了!");
var regForm = document.regForm;
var userName = regForm.userName.value;
var userNick = regForm.userNick.value;
var password = regForm.password.value;
var rePassword = regForm.rePassword.value;
var phone = regForm.phone.value;
var email = regForm.email.value;
var IDNumber = regForm.IDNumber.value;
var sex = regForm.sex.value;
var hobby = regForm.hobby;
var province = regForm.province.value;
var introduce = regForm.introduce.value;
//alert(introduce);
//获取提示信息span对象
var regInfo = document.getElementById("regInfo");
if(userName == "") {
regInfo.innerHTML = "请填写【用户名】:";
regForm.userName.focus();
return false;
}else if(userNick == "") {
regInfo.innerHTML = "请填写【昵称】";
regForm.userNick.focus();
return false;
} else if(password == "") {
regInfo.innerHTML = "请填写【密码】";
regForm.password.focus();
return false;
}else if(rePassword == "") {
regInfo.innerHTML = "请【确认密码】";
regForm.rePassword.focus();
return false;
}else if(phone == "") {
regInfo.innerHTML = "请填写【手机号】";
regForm.phone.focus();
return false;
}else if(email == "") {
regInfo.innerHTML = "请填写【邮箱】";
regForm.email.focus();
return false;
}else if(IDNumber == "") {
regInfo.innerHTML = "请输入【身份证号】";
regForm.IDNumber.focus();
return false;
}else if(sex == "") {
regInfo.innerHTML = "请选择【性别】";
//regForm.sex.focus();//这里千万不能聚焦!
return false;
}else if(!checkHobby()) {
regInfo.innerHTML = "请选择【爱好】";
//regForm.hobby.focus();//这里也类似
//alert(hobby);
return false;
}else if(province == "") {
regInfo.innerHTML = "请选择【省份】";
return false;
}else if(introduce == "") {
regInfo.innerHTML = "请填写【自我介绍】";
regForm.introduce.focus();
return false;
}else {
return true;
}
/**
if(select.selectedIndex ==0){
alet("进来了");
regInfo.innerHTML = "请选择【省份】";//存在的问题是没法验证省份是否选择,总是进不了选择语句!
return false;
}
*/
}
//判断复选框 要知道爱好是个数组,不能直接.value的来判断啊 纠结了近1个多小时!
function checkHobby() {
var regForm = document.regForm;
var hobby = regForm.hobby;
var flag = false;
for(var i=0;i<hobby.length;i++) {
if(hobby[i].checked){
flag = true;
break;
}else {
}
}
return flag;
}
当然,加入正则更加精确,同时可以使用jQuery 自带的验证。
3.1.4 service dao controller
UserRegisterDao
UserRegisterDaoImpl
UserRegisterService
UserRegisteServiceImpl
UserRegisterServlet
UserRegisterDao
package com.hmc.dao;
import com.hmc.pojo.User;
/**
*
*2017年12月30日
*User:Meice
*下午8:33:32
*/
public interface UserRegisterDao {
//1.增加用户方法
int addUser(User user);
//2.封装Cud方法
int Cud(String sql,Object[] params);
}
UserRegisterDaoImpl
package com.hmc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.hmc.pojo.User;
import com.hmc.util.DBUtil;
import com.hmc.util.GetPreparedStatementUtil;
/**
*
*2017年12月30日
*User:Meice
*下午8:34:06
*/
public class UserRegisterDaoImpl implements UserRegisterDao {
//注册用户 此方法完全可以用Cud方法取而代之!
@Override
public int addUser(User user) {
Connection conn = DBUtil.getConn();
PreparedStatement ps = null;
String sql = "insert into user (userName,userNick,password,rePassword,sex,hobby,province,introduce,registerTime,email,IDNumber,phone) values "
+ "(?,?,?,?,?,?,?,?,?,?,?,?)";
Object[] params = {user.getUserName(),user.getUserNick(),user.getPassword(),user.getRePassword(),user.getSex(),user.getHobby(),user.getProvince(),user.getIntroduce(),user.getRegisterTime(),user.getEmail(),user.getIDNumber(),user.getPhone()};
ps = GetPreparedStatementUtil.getPs(conn, ps, sql, params);
//执行语句
try {
int result = ps.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.closeConn(conn, ps, null);
}
return 0;
}
//增删改
@Override
public int Cud(String sql, Object[] params) {
Connection conn = DBUtil.getConn();
PreparedStatement ps = null;
ps = GetPreparedStatementUtil.getPs(conn, ps, sql, params);
//执行语句
try {
int result = ps.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.closeConn(conn, ps, null);
}
return 0;
}
}
UserRegisterService
package com.hmc.service;
import com.hmc.pojo.User;
/**
*
*2017年12月30日
*User:Meice
*下午8:31:29
*/
public interface UserRegisterService {
//1.注册用户方法
int addUser(User user);
//2.封装Cud方法
int Cud(String sql,Object[] params);
}
UserRegisteServiceImpl
package com.hmc.service;
import com.hmc.dao.UserRegisterDaoImpl;
import com.hmc.pojo.User;
/**
*
*2017年12月30日
*User:Meice
*下午8:32:58
*/
public class UserRegisterServiceImpl implements UserRegisterService {
//注册用户
@Override
public int addUser(User user) {
return new UserRegisterDaoImpl().addUser(user);
}
//增删改
@Override
public int Cud(String sql, Object[] params) {
return new UserRegisterDaoImpl().Cud(sql, params);
}
}
UserRegisterServlet
这里就给数据库增加一条数据即可。
package com.hmc.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hmc.pojo.User;
import com.hmc.service.UserRegisterServiceImpl;
import com.hmc.util.GetFormatTimeUtil;
/**
*
*2017年12月30日
*User:Meice
*下午8:20:24
*/
public class UserRegisterServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进来了");
//1.接收页面用户注册的值
String userName = req.getParameter("userName");
String userNick = req.getParameter("userNick");
String password = req.getParameter("password");
String rePassword = req.getParameter("rePassword");
String sex = req.getParameter("sex");
String[] hobbies = req.getParameterValues("hobby");
String province = req.getParameter("province");
String introduce = req.getParameter("introduce");
String email = req.getParameter("email");
String IDNumber = req.getParameter("IDNumber");
String phone = req.getParameter("phone");
String registerTime = GetFormatTimeUtil.getFormatTime(24);
System.out.println("注册用户信息:"+userName +" "+userNick+" "+password+" "+rePassword+" "+sex+" "+hobbies+" "+province
+ " "+introduce+" "+email+" "+IDNumber+" "+phone+" "+registerTime);
//String hobby = hobbies.toString();//行不通[Ljava.lang.String;@7c18b07b
String hobby = "";
for(int i=0;i<hobbies.length;i++) {
hobby += hobbies[i]+"";
}
System.out.println(hobby);
User user = new User();
user.setUserName(userName);
user.setUserNick(userNick);
user.setPassword(rePassword);
user.setRePassword(rePassword);
user.setSex(sex);
user.setHobby(hobby);
user.setProvince(province);
user.setIntroduce(introduce);
user.setRegisterTime(registerTime);
user.setEmail(email);
user.setPhone(phone);
user.setIDNumber(IDNumber);
//2.调用为user表插入数据的方法
UserRegisterServiceImpl urs = new UserRegisterServiceImpl();
int result = urs.addUser(user);
//3.跳转页面 用户注册成功,跳转登录界面,用户注册失败,弹出框给提示!
if(result>0) {
//注册成功!提示恭喜注册成功!2S后跳转登录界面
Thread thread = new Thread();
//resp.getWriter().write("<script type='text/javascript'>alert('系统将在222');</script>");
try {
thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resp.sendRedirect("login.jsp");
}else {
//注册失败,提示失败,重新注册!
resp.sendRedirect("register.jsp");
}
}
}
3.2 登录
3.2.1 登录页面设计
3.2.2 前端简单验证
3.2.2 service dao controller
3.2 登录
3.2.1 登录页面设计
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!--Author:Meice 2017年12月30日下午3:20:45 -->
<!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 href="css/login.css" rel="styleSheet" type="text/css"> -->
<link href="css/login.css" rel="stylesheet" type="text/css">
<!--引入外部JS -->
<script type="text/javascript" src="js/login.js"></script>
</head>
<body>
<%
String userName = "";
String password = "";
Cookie[] cookies = request.getCookies();
//判断是否为null这一步很关键,如果没有判断,第一次访问没有任何cookie,就报错NullPointException 第二次访问,才会访问到。
if(cookies!= null) {
for(int i=0;i<cookies.length;i++) {
if(cookies[i].getName().equals("userName")) {
userName = cookies[i].getValue();
System.out.println("cookie里面的用户名:"+userName);
}
if(cookies[i].getName().equals("password")) {
password = cookies[i].getValue();
System.out.println("cookie里面的密码:"+password);
}
}
}
%>
<!-- 引入头部 -->
<jsp:include page="head.jsp"></jsp:include>
<!-- 登录首页 -->
<div id="loginForm">
<form name="loginForm" action="login" method="get" onsubmit="return checkLoginForm()" >
<table cellspacing="20" >
<tr>
<td colspan="2" align="center" style="font-size:25px;font-weight:bolder;color:green">登录</td>
<span><a href="register.jsp">还没有账号?立即注册</a></span>
</tr>
<tr>
<td colspan="2">
<span id="loginInfo" style="font-size:15px;color:red;font-weight:bolder;"></span>
</td>
</tr>
<tr>
<td align="center">用户名</td>
<td>
<input type="text" name="userName" class="myInput" value="<%=userName %>">
</td>
</tr>
<tr>
<td align="center">密 码</td>
<td>
<input type="password" name="password" class="myInput" value="<%=password %>" >
</td>
</tr>
<tr>
<td align="center">验证码</td>
<td>
<input type="text" name="code" class="myInput">
</td>
<img scr="">
</tr>
<tr>
<td colspan="2" align="center">
<input id="remember" name="remember" value="1" type="checkbox" style="width: 18px;height: 18px;"> 记住我? <a href="#">忘记密码?</a>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="登录" style="width: 150px;height: 35px;">
</td>
</tr>
</table>
</form>
</div>
<!--引入尾部 -->
<jsp:include page="foot.jsp"></jsp:include>
</body>
</html>
3.2.2 前端简单验证
login.js
//登录简单验证
function checkLoginForm() {
//alert("进来了");
//获取表单元素
var lgForm = document.loginForm;
var userName = lgForm.userName.value;
var password = lgForm.password.value;
var code = lgForm.code.value;
var lgInfo = document.getElementById("loginInfo");
if(userName == "") {
//alert("用户名为空!");
lgInfo.innerHTML = "请填写【用户名】";
lgForm.userName.focus();
return false;
}else if(password == "") {
lgInfo.innerHTML = "请填写【密码】";
lgForm.password.focus();
return false;
}else if(code == "") {
lgInfo.innerHTML = "请填写【验证码】";
lgForm.code.focus();
return false;
}else {
return true;
}
}
3.2.2 service dao controller
UserLoginDao
UserLoginDaoImpl
UserLoginService
UserLoginServiceImpl
UserLoginServlet
UserLoginDao
这个底层就是对登录用户查一下,并且返回一个用户,到时候首页面方便取值
package com.hmc.dao;
import java.util.List;
import com.hmc.pojo.User;
/**
*
*2017年12月31日
*User:Meice
*下午1:10:00
*/
public interface UserLoginDao {
//查 返回一个用户 返回用户列表都可以
List<User> listUser (String sql,Object... params);
}
UserLoginDaoImpl
package com.hmc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.hmc.pojo.User;
import com.hmc.util.DBUtil;
import com.hmc.util.GetPreparedStatementUtil;
/**
*
*2017年12月31日
*User:Meice
*下午1:11:25
*/
public class UserLoginDaoImpl implements UserLoginDao {
@Override
public List<User> listUser(String sql, Object... params) {
Connection conn = DBUtil.getConn();
List<User> list = new ArrayList<>();
PreparedStatement ps = null;
ps = GetPreparedStatementUtil.getPs(conn, ps, sql, params);
ResultSet rs = null;
//执行方法
try {
rs = ps.executeQuery();
while(rs != null && rs.next()) {
User user = new User();
user.setUserId(rs.getInt("userId"));
user.setUserName(rs.getString("userName"));
user.setUserNick(rs.getString("userNick"));
user.setPassword(rs.getString("password"));
user.setRePassword(rs.getString("rePassword"));
user.setSex(rs.getString("sex"));
user.setHobby(rs.getString("hobby"));
user.setProvince(rs.getString("province"));
user.setIntroduce(rs.getString("introduce"));
user.setLoginTime(rs.getString("loginTime"));
user.setRegisterTime(rs.getString("registerTime"));
user.setEmail(rs.getString("email"));
user.setPhone(rs.getString("phone"));
user.setIDNumber(rs.getString("IDNumber"));
list.add(user);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.closeConn(conn, ps, rs);
}
return null;
}
}
UserLoginService
package com.hmc.service;
/**
*
*2017年12月31日
*User:Meice
*下午1:08:21
*/
import java.util.List;
import com.hmc.pojo.User;
public interface UserLoginService {
//查 返回一个用户 返回用户列表都可以
List<User> listUser (String sql,Object... params);
}
UserLoginServiceImpl
package com.hmc.service;
import java.util.List;
import com.hmc.dao.UserLoginDaoImpl;
import com.hmc.pojo.User;
/**
*
*2017年12月31日
*User:Meice
*下午1:10:32
*/
public class UserLoginServiceImpl implements UserLoginService {
@Override
public List<User> listUser(String sql, Object... params) {
//调用UserLoginDao方法
return new UserLoginDaoImpl().listUser(sql, params);
}
}
UserLoginServlet
这里就主要实现:判断用户是否存在,存在就登录,然后把用户放到cookie或者session里面
package com.hmc.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hmc.pojo.TextShow;
import com.hmc.pojo.User;
import com.hmc.service.TextShowService;
import com.hmc.service.TextShowServiceImpl;
import com.hmc.service.UserLoginService;
import com.hmc.service.UserLoginServiceImpl;
import com.hmc.util.GetFormatTimeUtil;
import com.hmc.util.GetStrToInt;
/**
*
*2017年12月31日
*User:Meice
*上午9:06:13
*/
public class UserLoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("执行登录操作....");
//1.接收登录参数
String userName = req.getParameter("userName");
String password = req.getParameter("password");
String code = req.getParameter("code");
String remember = req.getParameter("remember");
//2.所有的操作前提都是用户存在
UserLoginService uls = new UserLoginServiceImpl();
String sql = "select * from user where userName = ? and password = ?";
Object[] params = {userName,password};
List<User> list = uls.listUser(sql, params);
User user = null;
//避免java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
if(list.size()>0) {
user = list.get(0);
}
//用户存在情况在存在cookie里面
if(user ==null) {
//证明用户不存在,提示登录失败,重新登录
System.out.println("用户不存在,请重新登录");
resp.sendRedirect("login.jsp");
}else {
//根据是会否记住,选择是否存Cookie
if( remember!= null && remember.equals("1")) {
System.out.println("增加存储到Cookie的操作。。。。。");
Cookie cookie = new Cookie("userName", userName);
Cookie cookie2 = new Cookie("password", password);
cookie.setMaxAge(60*60*24*10);
cookie2.setMaxAge(60*60*24*10);
//当然是在添加cookie之前设置生命时间
resp.addCookie(cookie);
resp.addCookie(cookie2);
}
//3.无论记住与否,都要存在session里面,并且调用方法跳转首页显示帖子
//保存一下登录时间
String loginTime = GetFormatTimeUtil.getFormatTime(24);
user.setLoginTime(loginTime);
System.out.println("登录用户所有信息:"+user);
req.getSession().setAttribute("user", user);
req.getRequestDispatcher("textShow").forward(req, resp);
}
}
}
补充:
既然都发表了,那把注册、登录CSS样式也带上吧,里面部分属性方便以后查看。
register.css
login.css
register.css
@CHARSET "UTF-8";
/*--Author:Meice
2017年12月30日 下午12:59:07*/
/*设置整体注册框位置 */
#registerForm{
width:500px;
height:500px;
margin:40px 0px 0px 450px;
}
/*设置对应Input框样式 */
.myInput{
width: 200px;
height: 30px;
}
/* 设置外边框 */
#registerForm table{
border-style: inset;
border-color: green;
}
login.css
@CHARSET "UTF-8";
/*--Author:Meice
2017年12月30日 下午3:32:25*/
*{
margin:0px;
padding:0px;
}
/* 设置登录框整体样式 */
#loginForm{
/* border:1px solid red; */
margin:50px 0px 200px 500px;
width:440px;
height:410px;
border-style: inset;
border-color:green;
}
/* 设置input样式 因为这里比较统一,好设置*/
.myInput{
width:220px;
height:30px;
}
/* 去掉a标签下划线 */
a{
text-decoration:none;
}
/*表格居中 */
#loginForm table{
margin-left:50px;
}
哈哈,是不是有点繁琐~有点事无巨细的感觉。罢了,就这样吧,这次目的是完成的过程,笔者也把整体过程录制了下来。
好了,各位读者朋友,再会!下篇将实现展示首页。
最后
以上就是端庄灰狼为你收集整理的小确幸BBS论坛-1-前期准备的全部内容,希望文章能够帮你解决小确幸BBS论坛-1-前期准备所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复