当前位置:网站首页>Implementation of simple registration and login

Implementation of simple registration and login

2022-07-25 20:35:00 Royal shadow time

  1. The login page :
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript">
// Refresh the picture 
	function _click() {
		var d = new Date();
		// When the path changes , Will refresh the picture , and get Method followed by a ? The number will refresh , Create an event object here , Then make the path change constantly through combination 
		document.getElementById("img").src = "${pageContext.request.contextPath}/img?"+ d.getMilliseconds();
	}
	// Modify the submission address of the same form 
	function chaAction(v){
		var form3=document.getElementById("form3");
		if(v==1){
			form3.action="${pageContext.request.contextPath}/login";
		}
		if(v==2){
			form3.action="register.jsp";
		}
		form3.submit();
	}
	function save(){
		var save=document.getElementById("savepwd");
		var hid=document.getElementById("hid");
		if(save.checked)
		{
			// Selected , Means to save the user   password 
			hid.setAttribute("value","1");
		}
	}
</script>
<style type="text/css">
	table{
		margin: 30px auto;
		border:1px solid #B3CDDB;
		font-family:" Microsoft YaHei ";
		color:white;
	}
	td{
		padding:10px;
		height:40px;
	}
	.but{
		background-color: white;
		border:0 none; 
		height:30px;
		width:70px;
		font:15px bold ;
		font-family:" Microsoft YaHei ";
		color:#2088B7;
		font-weight:bold;
	}
	#img{
		vertical-align:middle;	
	}
	body{
		background: url("2.jpg");
	}
</style>
</head>
<body>

<%
	// The access is saved in session User name in , Put the user name in the input field 
	//String username =(String)request.getSession().getAttribute("username");
//	 obtain cookie Array of 
		Cookie[] arr=request.getCookies();
		String name =null;
		String pwd=null;
// Traversal array 
if(arr!=null)
	{
	for(Cookie c : arr)
	{
		String name1=c.getName();
		String value=c.getValue();
		// The order here needs attention , In judgment username yes cookie Medium username
		if("name".equals(name1))
		{
			name=value;
		}
		if("pwd".equals(name1))
		{
			pwd=value;
		}
	}
	
	}
%>
	<form action="" method="post" id="form3">
		<table>
			<tr align="center">
				<td colspan="2"><font color="#FF00FF"><b><font color="white"> The user login </font></b></font></td>
			</tr>
			<tr>
				<td colspan="2"><font color=red>${errMsg}</font></td>
			</tr>
			<tr>
				<td> user name :</td>
				<td><input type="text" name="name" value="<%=name==null?"":name%>"></td>
			</tr>
			<tr>
				<td> password :</td>
				<td><input type="password" name="password" value="<%=pwd==null?"":pwd%>"  style="vertical-align:middle;"></td>
			</tr>
			<tr>
				<td id="ctd"> Verification Code </td>
				<td>
<%--			 To create a verification code name attribute , Give Way servlet Get the value entered in the verification code 	--%>
				<input type="text" name="imgCode">
				<img src="${pageContext.request.contextPath}/img" id="img" οnclick="_click() ">
				<a href="javascript:void(0)" οnclick="_click()" style="text-decoration:none;"><font color="#B3CDDB"> Can't see , In a </font></a>
				</td>
			</tr>
			<tr>
<%--	 By modifying the value To achieve the goal 		--%>
				<td><input type="hidden" name="hid" id="hid" value="0"></td>
				<td><input type="checkbox" οnclick="save()" id="savepwd"> Whether to save the user password </td>
			</tr>
			<tr >
				<td align="center" colspan="2"><input type="submit" class="but" value=" Sign in " οnclick="chaAction(1)">
				<input type="submit" class="but" value=" register " οnclick="chaAction(2)"></td>
			</tr>
		</table>
	</form>
</body>
</html>

2. Registration success page :

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'welcome.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="refresh" content="3;login.jsp">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<style type="text/css">
	body{
			background: url("2.jpg");
		}
	div{
		height: 200px;
		margin-top: 90px;
	}

</style>
  </head>
  
  <body>
    <div align="center" ><font color="white" size="4"><b> Registered successfully ,3 Seconds later, jump to the login page </b></font></div>
  </body>
</html>

3. Registration page :

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="root" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title> Registration page </title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">  
	 
	<script type="text/javascript">
    	function _changImg(){
    		document.getElementById("img").src = "${root}/img?" + new Date().getTime();
    	}
    	function chaAction(v){
    		var form1=document.getElementById("form1");
    		if(v==1){
    			form1.action="${root}/registerServlet";
    		}
    		if(v==2){
    			form1.action="login.jsp";
    		}
    		form1.submit();
    	}
    </script>
    <style type="text/css">
	table{
		margin: 30px auto;
		border:1px solid #B3CDDB;
		font-family:" Microsoft YaHei ";
		color:white;
	}
	td{
		padding:5px;
		height:33px;
	}
	.but{
		background-color: white;
		border:0 none; 
		height:30px;
		width:70px;
		font:15px bold ;
		font-family:" Microsoft YaHei ";
		color:#2088B7;
		font-weight:bold;
	}
	#img{
		vertical-align:middle;	
	}
	body{
		background: url("2.jpg");
	}
</style>
  </head>
  <body>
  	<center>
<%--   Here you can use ${root}  perhaps ${pageContext.Request.contextPath}  To get the current project path 	--%>
  		<form action="" method="post" id="form1">
			<table>
				<tr align="center">
				<td colspan="2"><font color="#FF00FF"><b><font color="white"> User registration </font></b></font></td>
			</tr>
			<tr>
				<td name="errMsg" align="center"><font color="red">${errMsg }</font></td>
			</tr>
				<tr>
					<td> user name <font color="red">*</font></td>
					<td><input type="text" name="name"/></td>
				</tr>			
				<tr>
					<td> password </td>
					<td><input type="password" name="password"/></td>
				</tr>			
				<tr>
					<td> Confirm the password </td>
					<td><input type="password" name="repassword"/></td>
				</tr>	
				<tr>
					<td> Age </td>
					<td><input type="text" name="age"/></td>
				</tr>			
				<tr>
					<td> Gender </td>
					<td>
						<input type="radio" name="sex" value=" male "/> male 
						<input type="radio" name="sex" value=" Woman "/> Woman 
					</td>
				</tr>			
				<tr>
					<td> mailbox </td>
					<td><input type="text" name="email"/></td>
				</tr>	
				<tr>
					<td> Birthday </td>
					<td><input type="text" name="birthday" id="birthday"/></td>
				</tr>			
				<tr>
					<td> hobby </td>
					<td>
						<input type="checkbox" name="hobby" value="C"/>C
						<input type="checkbox" name="hobby" value="C++"/>C++
						<input type="checkbox" name="hobby" value="Java"/>Java
						<input type="checkbox" name="hobby" value="IOS"/>IOS
						<input type="checkbox" name="hobby" value="PHP"/>PHP
						<input type="checkbox" name="hobby" value="Android"/>Android
					</td>
				</tr>			
				<tr>
					<td> Address </td>
					<td>
						<select name="address">
							<option value="none">-- Please select an address --</option>
							<option value=" Beijing "> Beijing </option>
							<option value=" Shanghai "> Shanghai </option>
							<option value=" nanjing "> nanjing </option>
							<option value=" Guangzhou "> Guangzhou </option>
							<option value=" Shenzhen "> Shenzhen </option>
						</select>
					</td>
				</tr>
				<tr>
					<td> Self description </td>
					<td>
						<textarea cols="40" rows="10" name="description"></textarea>
					</td>
				</tr>				
				<tr>
					<td> Enter verification code </td>
					<td>
						<input type="text" name="checkImg" />
						<img style="cursor: pointer;" alt="" src="${root }/img" id="img" οnclick="_changImg();"/>
    					<a href="javascript:void(0);" οnclick="_changImg();" style="text-decoration:none"><font color="#B3CDDB"> Can't see , In a </font></a>
					</td>
				</tr>				
				<tr>
	  				<td colspan="2" align="center"><input type="submit" value=" register " class="but" οnclick="chaAction(1)"/>
	  				<input type="submit" class="but" value=" Return to login " οnclick="chaAction(2)"></td>
	  			</tr>
			</table>  		
  		</form>
  	</center>
  </body>
</html>
					
4. The login page :
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
	body{
			background: url("2.jpg");
		}
	div{
		height: 200px;
		margin-top: 90px;
	}

</style>
  </head>
  
  <body>
     <div align="center" ><marquee><font color="white" size="4"><b> Login successful </b></font></marquee></div>
  </body>
</html>


5. User class :
package com.yynh.domain;

import java.sql.Date;

/**
 * @author wjn  And day13 data user Table corresponding implementation class 
 */
public class User {

	private int id;
	private String name;
	private String password;
	private int age;
	private String sex;
	private String email;
	private String hobby;
	private String address;
	private String description;
	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	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 + ", age=" + age + ", sex=" + sex + ", email=" + email + ", hobby=" + hobby + ", address=" + address + ", description=" + description + ", birthday=" + birthday + "]";
	}

}
6. Tool class :
package com.yynh.utils;

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

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {
	//  establish c3p0 Kaiyuan connection pool object , Pass in the specified configuration 
	static ComboPooledDataSource cpds = new ComboPooledDataSource();

	//  Release resources 
	public static void release(Connection conn, ResultSet rs, Statement stmt) {
		try {
			//  In order to prevent rs No exception is reported , Judge 
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		//  If there is an exception in the judgment , Just put rs assignment null, Avoid problems 
		rs = null;
		//  If it is select operation , Continue to call the other two exceptions 
		release(conn, stmt);
	}

	//  Release resources for secondary optimization , Through function rewriting , To distinguish whether it is select operation 
	public static void release(Connection conn, Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
			}
		} catch (Exception e2) {
		}
		stmt = null;
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e2) {
		}
		conn = null;
	}

	public static Connection getCon() throws Exception {
		//  Get connections through the connection pool 
		Connection conn = cpds.getConnection();
		//  take conn return 
		return conn;
	}

}

7. The configuration file
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<!--  The default configuration ,c3p0 The framework loads this default configuration by default  -->
	<default-config>
		<!--  To configure JDBC  Four basic attributes  -->
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/day13</property>
		<property name="user">root</property>
		<property name="password">123</property>
	</default-config> <!-- This app is massive! -->
</c3p0-config>

8. Verification Code :
package com.yynh.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

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

public class ImgServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//  Image verification code 
		//  Create a canvas 
		//  Set length and width 
		int width = 120;
		int height = 35;
		// imageType  It refers to the format of color , Here we use rgb
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//  Get the brush from the canvas , getGraphics() graphics
		Graphics2D g = bi.createGraphics();
		//  Fill in the background color 
		g.setColor(Color.white);
		//  Fill in the range 
		g.fillRect(0, 0, width, height);
		//  bound box 
		g.setColor(Color.red);
		//  Fill in the border 
		g.drawRect(0, 0, width - 1, height - 1);
		//  Generate four random data 
		//  Prepare the data  ctrl+shift+x  Capitalize the selected text , Ctrl + shift +y  Lower the selected text 
		String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		//  Set a random object 
		Random r = new Random();
		//  Set a variable to save the verification code 
		String code = "";
		//  loop 
		for (int i = 1; i < 5; i++) {
			//  Rotate the canvas 
			//  Get a random value , First get a range in -1-1  Random number between , Re reduction 0.5 You get one 0-0.5 Random number between 
			double theta = (Math.random() - 0.5);
			//  Rotate a certain angle 
			g.rotate(theta, 22 * i, height / 2);
			//  Set the font , Pass a font object 
			g.setFont(new Font(" Song style ", Font.ITALIC, 27));
			//  Set random colors   adopt color Constructor to pass parameters 
			g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
			//  Randomly obtain a subscript according to the length of the string , Then get a character by subscript , Then it becomes a string 
			String str = data.charAt(r.nextInt(data.length())) + "";
			//  Write characters to the canvas , And adjust the position 
			g.drawString(str, i * 22, 30);
			//  Rotate the canvas back 
			g.rotate(-theta, 22 * i, height / 2);
			//  Splice each character together 
			code += str;
		}
		//  Set up session preservation code
		request.getSession().setAttribute("checkCode", code);
		//  Drew interference 
		for (int i = 1; i < 7; i++) {
			//  Set random colors 
			g.setColor(new Color(r.nextInt(100) + 100, r.nextInt(100) + 100, r.nextInt(100) + 100));
			//  Draw lines on the canvas   Two values determine a point , Two points define a line 
			g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
		}
		//  Output canvas to browser 
		ImageIO.write(bi, "jpg", response.getOutputStream());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
9. Sign in servlet
package com.yynh.web;

import java.io.IOException;

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.yynh.domain.User;
import com.yynh.service.ServiceLogin;
import com.yynh.service.ServiceUser;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//  Solve the mess 
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//  Get the verification code saved locally 
		String checkCode = (String) request.getSession().getAttribute("checkCode");
		//  Print verification code 
		System.out.println(checkCode);
		//  Get the verification code entered by the user 
		String imgCode = request.getParameter("imgCode");
		System.out.println(imgCode);
		//  Remove the local verification code 
		request.getSession().removeAttribute("checkCode");
		//  First step : Determine whether the verification code is correct 
		if (imgCode == null || !imgCode.equalsIgnoreCase(checkCode)) {
			//  When the verification code is not entered or is different from the local verification code , Request forwarding   There is no need to add the item name for forwarding 
			request.setAttribute("errMsg", " The verification code is wrong ");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		//  get data 
		User user = new User();
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		user.setName(name);
		user.setPassword(password);
		//  Call business 
		ServiceUser su = new ServiceLogin();
		int i = su.loginUser(user);
		if (i == 1) {
			//  Represents a successful login 
			Cookie cookie = new Cookie("name", name);
			//  Setup time 
			cookie.setMaxAge(60 * 60 * 24);
			//  Set the path 
			cookie.setPath("/");
			response.addCookie(cookie);
			String hid = request.getParameter("hid");
			System.out.println("woshi" + hid);
			if (hid.equals("1")) {
				Cookie coo = new Cookie("pwd", password);
				//  Setup time 
				cookie.setMaxAge(60 * 2);
				//  Set the path 
				cookie.setPath("/");
				response.addCookie(coo);
			}

			//  Save user objects to session in 
			request.getSession().setAttribute("user", user);
			//  Redirect to success page 
			response.sendRedirect(request.getContextPath());
			return;
		}
		if (i == 0) {
			//  Represents user name or secret error 
			request.setAttribute("errMsg", " Wrong user name or password ");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		if (i == -1) {
			//  Represents an exception 
			request.setAttribute("errMsg", " server is busy , Try again later ");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
	}

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

}
10 register servlet
package com.yynh.web;

import java.io.IOException;
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 com.yynh.domain.User;
import com.yynh.service.ServiceUser;
import com.yynh.service.ServiceUserCheck;

public class RegisterServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//  Solve the mess 
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//  Get the verification code saved locally 
		String checkCode = (String) request.getSession().getAttribute("checkCode");
		//  Print verification code 
		System.out.println(checkCode);
		//  Get the verification code entered by the user 
		String checkImg = request.getParameter("checkImg");
		System.out.println(checkImg);
		//  Remove the local verification code 
		request.getSession().removeAttribute("checkCode");
		//  First step : Determine whether the verification code is correct 
		if (checkImg == null || !checkImg.equalsIgnoreCase(checkCode)) {
			//  When the verification code is not entered or is different from the local verification code , Request forwarding   There is no need to add the item name for forwarding 
			request.setAttribute("errMsg", " The verification code is wrong ");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		//  Encapsulated data , Call the business layer to process business 
		User user = new User();
		//  Get all properties 
		Map<String, String[]> map = request.getParameterMap();
		//  obtain javabean
		try {
			//  Encapsulate data into javaBean in 
			BeanUtils.populate(user, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//  The second step : Package hobbies separately 
		String[] hobby = request.getParameterValues("hobby");
		String temp = "";
		for (String s : hobby) {
			temp = temp + "," + s;
		}
		//  Remove the starting comma 
		temp = temp.substring(1);
		user.setHobby(temp);
		System.out.println(user);

		//  The third step : call service Layer handles business 
		ServiceUser sUser = new ServiceUserCheck();
		//  Receive the returned value 
		int i = sUser.register(user);
		//  Process the returned value 
		if (i == 1) {
			//  On behalf of successful registration , Jump to the success page 
			//  Jump requires project name 
			response.sendRedirect(request.getContextPath() + "/welcome.jsp");
			return;
		} else if (i == 0) {
			//  Representative registration failed , User name already exists 
			//  Prompt information 
			request.setAttribute("errMsg", " The user name has been registered ");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		} else {
			//  It means there is an exception 
			request.setAttribute("errMsg", " server is busy , Please try again later ");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//  call doGet Method 
		doGet(request, response);
	}

}

11. Sign in service
package com.yynh.service;

import com.yynh.dao.UserDao;
import com.yynh.dao.UserDaoReg;
import com.yynh.domain.User;

public class ServiceLogin implements ServiceUser {

	@Override
	public int register(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int loginUser(User user) {
		UserDao ud = new UserDaoReg();
		int i = ud.login(user);
		if (i == 1) {
			//  Represents a successful login 
			return 1;
		} else {
			return i;
		}
	}

}
12. register service
package com.yynh.service;

import com.yynh.dao.UserDao;
import com.yynh.dao.UserDaoReg;
import com.yynh.domain.User;

/**
 * @author yynh_
 * @ Register for business 
 */
public class ServiceUserCheck implements ServiceUser {
	public int register(User user) {
		UserDao ud = new UserDaoReg();
		//  Determine whether the user name has been registered 
		int i = ud.findUser(user.getName());
		if (i == 1) {
			//  Representatives can register users 
			//  Encrypted password   There is no way to login after encryption 
			// String pwd = MD5Utils.getPwd(user.getPassword());
			//  Store the encrypted results in user in 
			// user.setPassword(pwd);
			//  Registered successfully 
			return ud.registerUser(user);
		} else {
			//  Represents that the user name already exists or there is an exception 
			return i;
		}
	}

	public int loginUser(User user) {
		return 0;
	}

}

13. dao layer
package com.yynh.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.yynh.domain.User;
import com.yynh.utils.JDBCUtils;

public class UserDaoReg implements UserDao {
	//  The user login 
	public int login(User user) {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			//  Get the connection 
			conn = JDBCUtils.getCon();
			String sql = "select * from user where name=? and password=?";
			//  Get send sql object 
			stmt = conn.prepareStatement(sql);
			//  Set properties 
			stmt.setString(1, user.getName());
			stmt.setString(2, user.getPassword());
			//  send out sql, Accept return value 
			rs = stmt.executeQuery();
			if (rs.next()) {
				//  The password and user name are correct , You can log in. 
				return 1;
			} else {
				//  Represents incorrect 
				return 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			JDBCUtils.release(conn, rs, stmt);
		}
	}

	//  Registered users 
	public int registerUser(User user) {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			//  Get the connection 
			conn = JDBCUtils.getCon();
			String sql = "insert into user values(null,?,?,?,?,?,?,?,?,?)";
			//  Get send sql object 
			stmt = conn.prepareStatement(sql);
			//  Set properties 
			stmt.setString(1, user.getName());
			stmt.setString(2, user.getPassword());
			stmt.setInt(3, user.getAge());
			stmt.setString(4, user.getSex());
			stmt.setString(5, user.getEmail());
			stmt.setString(6, user.getHobby());
			stmt.setString(7, user.getAddress());
			stmt.setString(8, user.getDescription());
			stmt.setDate(9, user.getBirthday());
			stmt.executeUpdate();
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	//  Query whether the user name exists 
	public int findUser(String name) {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			//  Get the connection 
			conn = JDBCUtils.getCon();
			String sql = "select * from user where name=?";
			//  Get send sql object 
			stmt = conn.prepareStatement(sql);
			//  Set properties 
			stmt.setString(1, name);
			//  send out sql, Accept return value 
			rs = stmt.executeQuery();
			if (rs.next()) {
				//  It means that there is a duplicate user name 
				return 0;
			} else {
				//  No duplicate can be registered 
				return 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			JDBCUtils.release(conn, rs, stmt);
		}
	}

}
effect :



For the first time in csdn Post , alas , I don't understand the typesetting here , I don't know what it will look like .......

原网站

版权声明
本文为[Royal shadow time]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/201/202207191053327964.html

随机推荐