目录
1.创建数据库表(MySQL中)。
2.根据数据库表在model包下创建User类
3.写登录界面login.jsp
4.写登录时负责跳转的servlet,LoginServlet.java
5.根据LoginServlet中所用到的UserService中的login方法才能完成登录,所以我们要在service包中的UserService编写login方法
6.login方法要通过UserDao对象调用Dao层方法与数据库交互,接下来写Dao层的UserDao类
7.写一个注册界面register.jsp
8.Servlet帮助提交注册的数据,RegisterServlet.java
9.同登录时的思路一样,接下来要在service包中的UserService类添加register()方法完成注册
10.register方法要与数据库进行交互,存取信息,所以在Dao层的UserDao类编写相应的方法与数据库进行交互
11.完整的UserDao类,UserService类代码如下:
12.测试记录
1.修改上下文目录:编辑
2.数据库表:
3.注册登录页面:
4.表中存取的信息:
5.用过滤器解决乱码问题,在filter包中进行编译:
6.乱码没解决之前的登录情况:
7.添加完过滤器后,注册与登录信息
8.注意
用IDEA写一个简单的用户注册与登录项目,如下为目录结构:
这是基本的框架,是MVC的思想。
下面对各个包进行解释:
Dao(数据持久层):这个包下的Java文件为与数据库进行交互的类
filter(过滤器):这个包下为过滤器,用于统一全站编码,主要解决中文乱码
model(模型):这个包下的Java文件为实体类
service(服务层):这个包下的类主要用于编写业务逻辑,并通过调用Dao层类中对应的方法操作数据库
servlet(控制器):里面的类为项目前台的servlet类
utils(工具类):包中的类为项目中所需要的工具类
以上都是src目录结构
web目录:
web文件夹根目录下的JSP文件都是前台系统的页面文件
lib包放需要的jar包
完整的目录结构为:
熟悉了目录结构,大致了解了MVC思想,接下来就开始我们的项目:
由于要实现的功能比较简单,项目也很小,需求简单,我们可以从数据库自顶向下写。
登录需要一个用户信息表,用户登录需要用户名(name)和密码(password),表中必须要有的字段就是用户名和密码。
注册需要的表跟登录用的一张表,方便注册完用户直接可以登录该用户。
这样,就可以向表中添加别的字段,比如说:性别(sex),住址(address),出生日期(birthday)。
附上数据库表单:
CREATE DATABASE test;
USE test;
CREATE TABLE user(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (40),
sex VARCHAR(40),
address VARCHAR(60),
birthday VARCHAR(60),
password VARCHAR(40)
)CHARACTER SET utf8 COLLATE utf8_general_ci;
package model;
public class User {
private int id;
private String name;
private String sex;
private String address;
private String birthday;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<%--
Created by IntelliJ IDEA.
User: 5201314xf
Date: 2022/5/20
Time: 13:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
登录页面
${msg }
${failMsg }
package servlet;
import model.User;
import service.UserService;
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 = "/LoginServlet")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserService();
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String password=request.getParameter("password");
User user=userService.login(name,password);
if (user==null){
request.setAttribute("failMsg","姓名或者密码输入有误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else {
request.getSession().setAttribute("user",user);
request.getRequestDispatcher("/index.jsp").forward(request,response);
}
}
}
根据登录时表单输入的用户名和密码查找用户
public User login(String name,String password){
User user=null;
try {
user=userDao.selectByNamePassword(name,password);
}catch (SQLException e){
e.printStackTrace();
}
if (user!=null){
return user;
}
try {
user=userDao.selectByNamePassword(name,password);
}catch (SQLException e){
e.printStackTrace();
}
if (user!=null){
return user;
}
return null;
}
在此之前,需要在utils包下写工具类C3p0utils.java,我连接数据库用的是C3P0数据库连接池,要在src根目录下创建名称为c3p0-config.xml(名字必须为这个,不可更改),以下为C3p0utils.java 和 c3po-config.xml
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=false
root
123456
30000
10
30
100
10
200
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=false
root
123456
5
15
package utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
public class C3p0Utils {
private static DataSource ds;
static {
ds=new ComboPooledDataSource();
}
public static DataSource getDataSource(){
return ds;
}
}
Dao层UserDao方法:
//通过用户名和密码查询用户,(用于登录)
public User selectByNamePassword(String name,String password) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="select * from user where name=? and password=?";
return runner.query(sql,new BeanHandler(User.class),name,password);
}
登录写完了,下面写注册功能
<%--
Created by IntelliJ IDEA.
User: 5201314xf
Date: 2022/5/20
Time: 13:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
注册新用户
${msg }
package servlet;
import model.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
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;
import java.lang.reflect.InvocationTargetException;
@WebServlet(name = "RegisterServlet",urlPatterns = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private UserService userService=new UserService();
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user=new User();
try {
BeanUtils.copyProperties(user,request.getParameterMap());
}catch (IllegalAccessException e){
e.printStackTrace();
}catch (InvocationTargetException e){
e.printStackTrace();
}
if (userService.register(user)){
request.setAttribute("msg","注册成功,请登录!");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else {
request.setAttribute("msg","用户名或地址重复,请重新填写!");
request.getRequestDispatcher("/register.jsp").forward(request,response);
}
}
}
我这里通过验证地址和名字来判断用户是否重复,因为我的数据库没有多余的字段,你可以在表中多加一个email字段来用于验证,不过,方法都是一样的
public boolean register(User user){
try {
if (userDao.isNameExit(user.getName())){
return false;
}
if (userDao.isAddressExit(user.getAddress())){
return false;
}
userDao.addUser(user);
return true;
}catch (SQLException e){
e.printStackTrace();
}
return false;
}
//通过姓名判断用户是否存在(用于注册信息)
public boolean isNameExit(String name) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="select * from user where name=?";
User user=runner.query(sql,new BeanHandler(User.class),name);
if (user==null){
return false;
}else {
return true;
}
}
//通过地址判断地址是否存在,我这里用于和姓名一起判断用户是否存在,注册用户时,甄别
public boolean isAddressExit(String address) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="select * from user where address=?";
User user=runner.query(sql,new BeanHandler(User.class),address);
if (user==null){
return false;
}else {
return true;
}
}
//添加用户,当用户名或地址不重复的时候就可以把新用户注册进数据库了
public void addUser(User user) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="insert into user (name,sex,address,birthday,password) values (?,?,?,?,?)";
runner.update(sql,user.getName(),user.getSex(),user.getAddress(),user.getBirthday(),user.getPassword());
}
UserDao类:
package Dao;
import model.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import utils.C3p0Utils;
import javax.sql.DataSource;
import java.sql.SQLException;
public class UserDao {
//通过用户名和密码查询用户,(用于登录)
public User selectByNamePassword(String name,String password) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="select * from user where name=? and password=?";
return runner.query(sql,new BeanHandler(User.class),name,password);
}
//通过姓名判断用户是否存在(用于注册信息)
public boolean isNameExit(String name) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="select * from user where name=?";
User user=runner.query(sql,new BeanHandler(User.class),name);
if (user==null){
return false;
}else {
return true;
}
}
//通过地址判断地址是否存在,我这里用于和姓名一起判断用户是否存在,注册用户时,甄别
public boolean isAddressExit(String address) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="select * from user where address=?";
User user=runner.query(sql,new BeanHandler(User.class),address);
if (user==null){
return false;
}else {
return true;
}
}
//添加用户,当用户名或地址不重复的时候就可以把新用户注册进数据库了
public void addUser(User user) throws SQLException{
QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
String sql="insert into user (name,sex,address,birthday,password) values (?,?,?,?,?)";
runner.update(sql,user.getName(),user.getSex(),user.getAddress(),user.getBirthday(),user.getPassword());
}
}
UserService类:
package service;
import Dao.UserDao;
import model.User;
import java.sql.SQLException;
public class UserService {
private UserDao userDao=new UserDao();
public User login(String name,String password){
User user=null;
try {
user=userDao.selectByNamePassword(name,password);
}catch (SQLException e){
e.printStackTrace();
}
if (user!=null){
return user;
}
try {
user=userDao.selectByNamePassword(name,password);
}catch (SQLException e){
e.printStackTrace();
}
if (user!=null){
return user;
}
return null;
}
public boolean register(User user){
try {
if (userDao.isNameExit(user.getName())){
return false;
}
if (userDao.isAddressExit(user.getAddress())){
return false;
}
userDao.addUser(user);
return true;
}catch (SQLException e){
e.printStackTrace();
}
return false;
}
}
这里建议把那个/example_war_exploded改成/,会比较方便。
此为数据库的表,因为还没有在表中插入字段值,所以建议先注册,这样就有用户信息了,可以进行登录。
从这里可以看到输入的中文信息都没有被编译,乱码了,要解决,所以要在filter包中写一个过滤器解决全站中文乱码问题
filter:
package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(filterName = "ToFilter",urlPatterns = "/*")
public class ToFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
虽然乱码但是不影响登录
因为我的index.jsp里面是默认的内容,没有添加任何东西,你可以往里面添加“登入成功”,来完善。
用完过滤器,完美解决中文乱码。
相关的jar包大家可以百度一下,都可以获取到的。