关于动态web一个用户登录和注册的小页面

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
    • 这是一个关于动态web一个用户登录和注册的小页面
  • 一、导入项目需要的包and项目需要创建文件总览图
  • 二、具体操作
    • 1.创建项目文件(略)
    • 2.创建数据库
    • 3.链接数据库
  • 三、登录和注册部分
    • 1.创建dao 层
    • 2.创建sevice层
    • 3.User.java和UserBean.java的创建
    • 4.servlet层的创建
  • 四、web页面的创建
    • 1.login.jsp
    • 2.zhuce.jsp
    • 3.index.jsp
    • 4.welcome.jsp
  • 总结


前言

这是一个关于动态web一个用户登录和注册的小页面

一、导入项目需要的包and项目需要创建文件总览图

关于动态web一个用户登录和注册的小页面_第1张图片

二、具体操作

1.创建项目文件(略)

2.创建数据库

代码如下(示例):

create table user(
	id int primary key auto_increment,
	name varchar(40),
	password varchar(40),
	email varchar(60),
	birthday date
);

insert into user(name,password,email,birthday) 
values('zhangsan','123456','zs@sina.com','1980-12-04');
insert into user(name,password,email,birthday) 
values('lisi','123456','lisi@sina.com','1981-12-04');
insert into user(name,password,email,birthday)
values('wangwu','123456','wangwu@sina.com','1979-12-04');

此处需要在数据库中进行关于动态web一个用户登录和注册的小页面_第2张图片


3.链接数据库

创建c3p0连接配置

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
  <default-config>
	<property name="driverClass">com.mysql.jdbc.Driver</property>
	<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
	<property name="user">root</property>
	<property name="password">sjk1234</property>
    <property name="initialPoolSize">10</property> 
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
  </default-config>
</c3p0-config>

连接c3p0

package com.gx.web.Utils;

import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {
   //0声明
	public static DataSource dataSource=null;
	static{
		//ComboPooledDataSource csp=new ComboPooledDataSource();
		//dataSource=csp;
		dataSource=new ComboPooledDataSource();
	}
	//返回值
	public static DataSource getDataSource() {
		return dataSource;
	}
	public static void main(String[] args) throws SQLException  {
		System.out.println(dataSource.getConnection());
	}
}

三、登录和注册部分

1.创建dao 层

package web.dao;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.gx.web.Utils.C3P0Utils;
import com.gx.web.exmple.User;

public class DButillsdao {
	public User login(String name,String pwd) throws SQLException{
	//1.创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
	//2.写SQL语句
		String sql="select * from user where name=? and password=?";

		//3.调用方法执行SQL语句
		User user=(User)runner.query(sql, new BeanHandler(User.class),new Object[]{name,pwd});
	    return user;
	} 
     public boolean insert(User user) throws SQLException {
 		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
 		
 		String s="insert into user(name,password,email) values(?,?,?)";
 		//
 		int n=runner.update(s,new Object[]{user.getName(),user.getPassword(),user.getEmail()});
 		if (n>0) {
			return true;
		} else {
			return false;
		}
	}
     public User find(String name) throws SQLException {
    		//1.创建QueryRunner对象
 		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
 	       //2.写SQL语句
 		String sql="select * from user where name=? ";
 		//3.调用方法执行SQL语句
 		User user=(User)runner.query(sql, new BeanHandler(User.class),new Object[]{name});
 	    return user;
	}
}

2.创建sevice层

package com.gw.web.sevice;

import java.sql.SQLException;
import com.gx.web.exmple.User;
import web.dao.DButillsdao;

public class DBusersevice {
	DButillsdao dao=new DButillsdao();
     public User login(String name,String pwd) throws SQLException {
		//实例化dao
    	 User user=(User)dao.login(name, pwd);
    	 return user;
	}
     public boolean insert(User user) throws SQLException {
		boolean b=dao.insert(user);
		return b;
	}
     public User find(String name) throws SQLException {
		User user=(User)dao.find(name);
		return user;
	}
}

3.User.java和UserBean.java的创建

User.java

package com.gx.web.example;

import java.util.Date;

public class User {
	private int id;
	private String name;
	private String password;
	private String email;
	private Date birthday;
	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 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 Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", birthday="
				+ birthday + "]";
	}



}

UserBean.java

package com.gx.web.example;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class UserBean {
	private int id;
	private String name;
	private String password;
	private String repassword;
	private String email;
	private Date birthday;
	
	private Map<String,String> errors=new HashMap<String,String>();
	public boolean vaidate() {
		boolean b = true;
		if (name==null||name.trim().equals("")) {
			errors.put("name", "用户名不能为空");
			b=false;
		}
		
		if (password==null||password.trim().equals("")) {
			errors.put("password", "密码名不能为空");
			b=false;
		}
		else if (password.length()<3||password.length()>5) {
			errors.put("password", "密码为3-5个字符");
			b=false;
		}
		if (password!=null&&!password.equals(repassword)) {
			errors.put("repassword", "您输入的两次密码不一致");
			b=false;
		}
		if (email==null||email.trim().equals("")) {
			errors.put("email", "邮箱不能为空");
			b=false;
		}
		else if (email.matches("")) {
			errors.put("email", "邮箱的格式有误");
			b=false;
		}
		return b;
	}
		
	//向MAP添加错误
	public void setErrorMsg(String err,String errMsg) {
		if ((err!=null)&&(errMsg!=null)) {
			errors.put(err, errMsg);
		}
	}
	
	
	public Map<String, String> getErrors() {
		return errors;
	}



	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 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 getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "UserBean [id=" + id + ", name=" + name + ", password=" + password + ", repassword=" + repassword
				+ ", email=" + email + ", birthday=" + birthday + "]";
	}
	
	

}

4.servlet层的创建

login.java

package com.gw.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
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 javax.servlet.http.HttpSession;
import com.gw.web.sevice.DBusersevice;
import com.gx.web.example.User;

/**
 * Servlet implementation class login
 */
@WebServlet("/login")
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public login() {
        // 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 {
		//0.中文处理
				request.setCharacterEncoding("utf-8");
				response.setContentType("text/html;charset=utf-8");
				//2接受参数
				String name=request.getParameter("username");
				String userpwd=request.getParameter("userpwd");
				String yzm=request.getParameter("yzm");
				//实例化session
				HttpSession session=request.getSession();
				String wcode=(String)session.getAttribute("wcode");
				if (yzm.equals(wcode)) {
					//3实例化DButillsdao
					//DButillsdao dao=new DButillsdao();
					//3实例化DBusersevice
					DBusersevice sevice=new DBusersevice();
					//4调用登录方法
					User user=null;
					try {
						user=(User)sevice.login(name,userpwd);
						if (user!=null) {
							response.sendRedirect("/login/welcome.jsp");
						}
						else {
							response.getWriter().write("账户或者密码错误");
						}
					} catch (SQLException e) {
						// TODO: handle exception
						e.printStackTrace();
					}

				}
				else {
					response.getWriter().write("验证码错误");
				}

			}

}

zhuce.java

package com.gw.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.Provider.Service;
import java.sql.SQLException;

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 org.apache.commons.beanutils.BeanUtils;

import com.gw.web.sevice.DBusersevice;
import com.gx.web.example.User;
import com.gx.web.example.UserBean;

/**
 * Servlet implementation class zhuce
 */
@WebServlet("/zhuce")
public class zhuce extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public zhuce() {
        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 {
		//0.中文处理
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//封装、检验、获取
		UserBean bean=new UserBean();
		try {
			BeanUtils.populate(bean, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		boolean f=bean.vaidate();	
		if (!f) {
			request.setAttribute("bean", bean);
			request.getRequestDispatcher("/zhuce.jsp").forward(request, response);
		}
		
		
		
		//2.接受参数
		User user=new User();
		try {
			//3.获取参数并封装
			BeanUtils.populate(user, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//4.实例化service
		DBusersevice service=new DBusersevice();
		User u=null;
		try {
			u=service.find(user.getName());
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (u!=null) {
			request.setAttribute("MM", "用户名已经存在");
			request.getRequestDispatcher("/zhuce.jsp").forward(request, response);
			return ;
		}
		else {
			//5.调用insert
			boolean b=false;
			try {
				b=service.insert(user);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (b) {
				response.getWriter().write("注册成功");
			}
			else {
				response.getWriter().write("注册失败");
			}
		}
		
	}

}

package com.gw.web.servlet;

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 javax.servlet.http.HttpSession;

import cn.dsna.util.images.ValidateCode;

/**
 * Servlet implementation class valicode
 */
@WebServlet("/valicode")
public class valicode extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public valicode() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.
		ValidateCode codes=new ValidateCode(150,30,4,10);
		//2.
		String s=codes.getCode();
		//3.
		HttpSession session=request.getSession();
		session.setAttribute("wcode", s);
		//4.
		codes.write(response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

四、web页面的创建

1.login.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>
head>
<body>

<form  action="/zhuce/login" method="post">
<tr>
<td>用户名:td>
<td><input type="text" name="username">td>
tr>

<tr>
<td>密码:td>
<td><input type="text" name="userpwd">td>
tr>

<tr>
<td>验证码:td>
<td><input type="text" name="yzm">
<img id="code" alt="" src="/zhuce/valicode"><br/><br/>
td>
tr>

<tr>
<td><input type="submit" value="登录"><br/><br/>td>

tr>
form>

body>
html>

2.zhuce.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
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>Insert title heretitle>
head>
<body>

<form  action="/zhuce/zhuce" method="post">
<table width="70%" border="0" cellspacing="2">
<tr>
<td cellspacing="3"><h1>新会员注册h1>td>
tr>
<tr>
<td type="text-align:right;width:20%">会员名:td>
<td align="left" width="20%"><input type="text" id="name" name="name">td>
<td type="text-align:left; width:60%">
<font color="red">${MM} font>
<font color="red">${bean.errors.name} font>
 font>

td>
tr>
<tr>
<td type="text-align:right;width:20%">密码:td>
<td align="left" width="20%"><input type="text" id="repassword" name="repassword">td>
<td type="text-align:left; width:60%">
<font color="red">${bean.errors.password}font>td>td>
tr>
<tr>
<td type="text-align:right;width:20%">确认密码:td>
<td align="left" width="20%"><input type="text" id="password" name="password">td>
<td type="text-align:left; width:60%">
<font color="red">${bean.errors.repassword}font>td>td>
tr>

<tr>
<td type="text-align:right;width:20%">会员邮箱:td>
<td align="left" width="20%"><input type="text" id="email" name="email">td>
<td type="text-align:left; width:60%">
<font color="red">${bean.errors.email}font>
td>
tr>
<tr >
<td><input type="submit" value="重置">td>
<td><input type="submit" value="注册">td>
tr>

table>
form>
body>
html>

3.index.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ 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>Insert title heretitle>
head>
<body>
<a href="${pageContext.request.contextPath}/login.jsp">登录a>
<a href="${pageContext.request.contextPath}/zhuce.jsp">注册a>
body>
html>

4.welcome.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>Insert title heretitle>
head>
<body>
登录成功!
body>
html>

总结

(这是一个非常非常基础的实验项目,仅供自己自娱自乐。。。)

你可能感兴趣的:(数据库,java)