I tried to make a login function in Java

キャプチャ.PNG

Motivation made

At the training school, we decided to create an app with a team of eight people, but the login function was essential as a functional requirement. I want to divide the pages that can be displayed according to the registered role, but I didn't know how to do it. It's 3 consecutive holidays and let's make it!

function

Good thing

I made it in about 4 hours. I think it would have taken 3 to 5 times longer three months ago. I'm growing up.

environment

Java version 13.0.1 mysql 8.0

DAO

AccountDAO.java


package dao;

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

import model.AccountBeans;

public class AccountDAO {
	//Information used to connect to the database
	final String jdbcId = "root";
	final String jdbcPass = "password";
	final String jdbcUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=JST";

	//Find a login account
	public AccountBeans findAccount(AccountBeans ab) {

		//Preparation of return value
		AccountBeans returnAb = new AccountBeans();

		//Connect to database
		try (Connection con = DriverManager.getConnection(jdbcUrl, jdbcId, jdbcPass)) {

			String sql = "SELECT loginId, pass, name, roleId FROM account WHERE loginId = ? AND pass = ?";
			PreparedStatement ps= con.prepareStatement(sql);

			ps.setString(1, ab.getLoginId());
			ps.setString(2, ab.getPass());

			ResultSet rs = ps.executeQuery();


			if (rs.next()) {
				//Set the found account information as the return value
				returnAb.setLoginId(rs.getString("loginId"));
				returnAb.setPass(rs.getString("pass"));
				returnAb.setName(rs.getString("name"));
				returnAb.setRole(rs.getInt("roleId"));
			} else {
				//Returns null if there is no account
				return null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return returnAb;
	}
}

AccountRegisterDAO.java


package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import model.AccountBeans;

public class AccountRegisterDAO {
	//Information used to connect to the database
		final String jdbcId = "root";
		final String jdbcPass = "password";
		final String jdbcUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=JST";

	public  AccountRegisterDAO(AccountBeans ab) {

		try (Connection con = DriverManager.getConnection(jdbcUrl, jdbcId, jdbcPass)) {

			String sql = "INSERT INTO account (loginId, pass, name, roleId) VALUES (?, ?, ?, ?)";
			PreparedStatement ps= con.prepareStatement(sql);

			ps.setString(1, ab.getLoginId());
			ps.setString(2, ab.getPass());
			ps.setString(3, ab.getName());
			ps.setInt(4, ab.getRole());

			int r = ps.executeUpdate();

			if(r != 0) {
				System.out.println("Successful new registration!");
			} else {
				System.out.println("New registration failure(No Д`)Sick ...");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

servlet

AccountCheck.java


package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 model.AccountBeans;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccountCheck() {
        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

		//Get login information from session
		HttpSession session = request.getSession();
		AccountBeans ab = (AccountBeans) session.getAttribute("account");

		//Sort the forward destination by roll
		if(ab.getRole() == 1) {
			RequestDispatcher rd = request.getRequestDispatcher("admin.jsp");
			rd.forward(request, response);
		} else if(ab.getRole() == 2) {
			RequestDispatcher rd = request.getRequestDispatcher("user.jsp");
			rd.forward(request, response);
		} else {
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
	}

	/**
	 * @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);
	}
}

AccountRegister.java


package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 dao.AccountRegisterDAO;
import model.AccountBeans;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccountRegister() {
        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

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String loginId = request.getParameter("loginId");
		String pass = request.getParameter("pass");
		int role = Integer.parseInt(request.getParameter("role"));

		// register.Set the value received from jsp to beans
		AccountBeans ab = new AccountBeans();
		ab.setName(name);
		ab.setLoginId(loginId);
		ab.setPass(pass);
		ab.setRole(role);

		//Register account in DB
		AccountRegisterDAO ard = new AccountRegisterDAO(ab);

		//Save account information in session
		HttpSession session = request.getSession();
		session.setAttribute("account", ab);

		RequestDispatcher rd = request.getRequestDispatcher("registerSuccess.jsp");
		rd.forward(request, response);

	}

}

AccountSearch.java


package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 dao.AccountDAO;
import model.AccountBeans;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccountSearch() {
        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

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String loginId = request.getParameter("loginId");
		String pass = request.getParameter("pass");

		// login.Set the login ID and pass received from jsp in the beans
		AccountBeans ab = new AccountBeans();
		ab.setLoginId(loginId);
		ab.setPass(pass);

		//Search for an account
		//Get the searched account information
		AccountDAO ad = new AccountDAO();
		AccountBeans returnAb = ad.findAccount(ab);

		if(returnAb != null) {
			//Register account information & role in session
			HttpSession session = request.getSession();
			session.setAttribute("account", returnAb);

			RequestDispatcher rd = request.getRequestDispatcher("loginSuccess.jsp");
			rd.forward(request, response);

		} else {
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
	}
}

Logout.java


package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        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
		HttpSession session = request.getSession();
		session.invalidate();

		RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
		rd.forward(request, response);
	}

	/**
	 * @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);
	}
}

filter

Filter.java


package filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class Filter
 */
@WebFilter("/*")
public class Filter implements javax.servlet.Filter {

    /**
     * Default constructor.
     */
    public Filter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		request.setCharacterEncoding("UTF-8");

		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}

JavaBeans

AccountBeans.java


package model;

import java.io.Serializable;

public class AccountBeans implements Serializable {
	private static final long serialVersionUID = 1L;

	private String loginId;
	private String pass;
	private String name;
	private int role;

	public String getLoginId() {
		return loginId;
	}
	public void setLoginId(String loginId) {
		this.loginId = loginId;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getRole() {
		return role;
	}
	public void setRole(int role) {
		this.role = role;
	}
}

JSP

admin.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin page</title>
</head>
<body>
This is a page for administrators.<br>
<c:choose>
<c:when test="${account.role == 1 }">
Confirmation of registration details.
<p>Login ID:<c:out value="${account.loginId }"></c:out></p>
<p>password:<c:out value="${account.pass }"></c:out></p>
<p>name:<c:out value="${account.name }"></c:out></p>
<p>Role: Administrator</p>
<p><a href="/login/Logout"><button type="button" >Log out</button></a></p>
<a href="user.jsp"><button type="button" >To user page</button></a>
</c:when>
<c:when test="${account.role == 2 }">
<a href="user.jsp">To user page</a>
</c:when>
<c:otherwise>
<a href="login.jsp">Go to login page</a>
</c:otherwise>
</c:choose>
</body>
</html>

error.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
I failed to login.<br>
<a href="login.jsp"><button>Go to login page</button></a>
</body>
</html>

login.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login screen</title>
</head>
<body>
<form action="/login/AccountSearch" method="post">
USER ID:<input type="text" name="loginId" required><br>
password:<input type="password" name="pass" required><br>
<input type="submit" value="Login"><br>
</form>
<p>
If you have not registered your account, click here ↓<br>
<a href="register.jsp"><button>sign up</button></a>
</p>
</body>
</html>

loginSuccess.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login successful</title>
</head>
<body>
Login was successful!
<p><a href="/login/AccountCheck"><button type="button" name="aaa" >To user or administrator page</button></a></p>
</body>
</html>

register.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sign up</title>
</head>
<body>
<form action="/login/AccountRegister" method="post">
<p>Please enter all</p>
<p>
<input type="radio" name="role" value="1">Register as an administrator
<input type="radio" name="role" value="2" checked>Register as a user
</p>
name:<input type="text" name="name" required><br>
USER ID:<input type="text" name="loginId" required><br>
password:<input type="password" name="pass" required><br>
<input type="submit" value="Registration"><br>
</form>
</body>
</html>

registerSuccess.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Completion of registration</title>
</head>
<body>
New registration completed!
<p><a href="/login/AccountCheck"><button type="button" name="aaa" >To user or administrator page</button></a></p>
</body>
</html>

user.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User information</title>
</head>
<body>
This is the user page.<br>
<c:choose>
<c:when test="${account.role == 2 }">
Confirmation of registration details.
<p>Login ID:<c:out value="${account.loginId }"></c:out></p>
<p>password:<c:out value="${account.pass }"></c:out></p>
<p>name:<c:out value="${account.name }"></c:out></p>
<p>Role: User</p>
<p><a href="/login/Logout"><button type="button" >Log out</button></a></p>
<a href="admin.jsp"><button type="button" >Go to admin page</button></a>
</c:when>
<c:when test="${account.role == 1 }">
<a href="admin.jsp">Go to admin page</a>
</c:when>
<c:otherwise>
<a href="login.jsp">Go to login page</a>
</c:otherwise>
</c:choose>

</body>
</html>

Table structure

キャプチャ.PNG

Recommended Posts

I tried to make a login function in Java
I tried to make a client of RESAS-API in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I tried to create a Clova skill in Java
I tried to make a talk application in Java using AI "A3RT"
I just wanted to make a Reactive Property in Java
I want to make a function with kotlin and java!
I tried to convert a string to a LocalDate type in Java
[Java] I tried to make a maze by the digging method ♪
I tried to make a group function (bulletin board) with Rails
java I tried to break a simple block
I did Java to make (a == 1 && a == 2 && a == 3) always true
I tried to implement deep learning in Java
I tried to output multiplication table in Java
I tried to create Alexa skill in Java
How to make a follow function in Rails
I tried to break a block with java (1)
I tried to make a parent class of a value object in Ruby
"Teacher, I want to implement a login function in Spring" ① Hello World
I tried metaprogramming in Java
I tried to implement Firebase push notification in Java
# 2 [Note] I tried to calculate multiplication tables in Java.
I want to define a function in Rails Console
I tried to implement the Euclidean algorithm in Java
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
[Small story] I tried to make the java ArrayList a little more convenient
How to make a Java container
I tried to interact with Java
I tried using JWT in Java
I tried to summarize Java learning (1)
I tried to summarize Java 8 now
How to make a Java array
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
[Beginner] I made a program to sell cakes in Java
I want to make a list with kotlin and java!
I tried using Hotwire to make Rails 6.1 scaffold a SPA
I tried to make Java Optional and guard clause coexist
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried using Dapr in Java to facilitate microservice development
I tried to implement a buggy web application in Kotlin
I tried to make a message function of Rails Tutorial extension (Part 1): Create a model
I tried using Elasticsearch API in Java
How to make a Java calendar Summary
I tried a calendar problem in Ruby
I tried to create a simple map app in Android Studio
I tried to implement Ajax processing of like function in Rails
Easy to make Slack Bot in Java
I tried to illuminate the Christmas tree in a life game
I tried to make a reply function of Rails Tutorial extension (Part 3): Corrected a misunderstanding of specifications
I tried to summarize Java lambda expressions
I tried to write code like a type declaration in Ruby
I tried the new era in Java
I tried setting Java beginners to use shortcut keys in eclipse
[Unity] I tried to make a native plug-in UniNWPathMonitor using NWPathMonitor
How to make a Discord bot (Java)
Make a login function with Rails anyway
I tried to make an Android application with MVC now (Java)
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.