J'ai décidé de créer une application avec une équipe de 8 personnes dans une école de formation, mais la fonction de connexion était essentielle comme exigence fonctionnelle. Je souhaite diviser les pages qui peuvent être affichées en fonction du rôle enregistré, mais je ne savais pas comment faire. C'est 3 jours fériés consécutifs et faisons-le!
Je l'ai fait en environ 4 heures. Je pense que cela aurait pris 3 à 5 fois plus longtemps il y a trois mois. Je grandis.
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 {
//Informations utilisées pour la connexion à la base de données
final String jdbcId = "root";
final String jdbcPass = "password";
final String jdbcUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=JST";
//Trouver un compte de connexion
public AccountBeans findAccount(AccountBeans ab) {
//Préparation de la valeur de retour
AccountBeans returnAb = new AccountBeans();
//Se connecter à la base de données
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()) {
//Définir les informations de compte trouvées comme valeur de retour
returnAb.setLoginId(rs.getString("loginId"));
returnAb.setPass(rs.getString("pass"));
returnAb.setName(rs.getString("name"));
returnAb.setRole(rs.getInt("roleId"));
} else {
//Renvoie null s'il n'y a pas de compte
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 {
//Informations utilisées pour la connexion à la base de données
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("Nouvelle inscription réussie!");
} else {
System.out.println("Nouvel échec d'enregistrement(Non Д`)Malade ...");
}
} 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
//Obtenir les informations de connexion de la session
HttpSession session = request.getSession();
AccountBeans ab = (AccountBeans) session.getAttribute("account");
//Trier la destination de renvoi par rouleau
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.Définissez la valeur reçue de jsp sur beans
AccountBeans ab = new AccountBeans();
ab.setName(name);
ab.setLoginId(loginId);
ab.setPass(pass);
ab.setRole(role);
//Enregistrer un compte dans DB
AccountRegisterDAO ard = new AccountRegisterDAO(ab);
//Enregistrer les informations de compte dans la 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.Définissez l'ID de connexion et le pass reçu de jsp dans les beans
AccountBeans ab = new AccountBeans();
ab.setLoginId(loginId);
ab.setPass(pass);
//Rechercher un compte
//Obtenez les informations de compte recherchées
AccountDAO ad = new AccountDAO();
AccountBeans returnAb = ad.findAccount(ab);
if(returnAb != null) {
//Enregistrer les informations de compte et le rôle dans la 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>Page d'administration</title>
</head>
<body>
Ceci est une page pour les administrateurs.<br>
<c:choose>
<c:when test="${account.role == 1 }">
Confirmation des détails d'inscription.
<p>Identifiant de connexion:<c:out value="${account.loginId }"></c:out></p>
<p>mot de passe:<c:out value="${account.pass }"></c:out></p>
<p>Nom:<c:out value="${account.name }"></c:out></p>
<p>Rôle: Administrateur</p>
<p><a href="/login/Logout"><button type="button" >Se déconnecter</button></a></p>
<a href="user.jsp"><button type="button" >Vers la page utilisateur</button></a>
</c:when>
<c:when test="${account.role == 2 }">
<a href="user.jsp">Vers la page utilisateur</a>
</c:when>
<c:otherwise>
<a href="login.jsp">Aller à la page de connexion</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>
Je n'ai pas réussi à me connecter.<br>
<a href="login.jsp"><button>Aller à la page de connexion</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>Écran de connexion</title>
</head>
<body>
<form action="/login/AccountSearch" method="post">
IDENTIFIANT D'UTILISATEUR:<input type="text" name="loginId" required><br>
mot de passe:<input type="password" name="pass" required><br>
<input type="submit" value="S'identifier"><br>
</form>
<p>
Si vous n'avez pas enregistré votre compte, cliquez ici ↓<br>
<a href="register.jsp"><button>s'inscrire</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>Connexion réussie</title>
</head>
<body>
La connexion a réussi!
<p><a href="/login/AccountCheck"><button type="button" name="aaa" >Vers la page utilisateur ou administrateur</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>s'inscrire</title>
</head>
<body>
<form action="/login/AccountRegister" method="post">
<p>Veuillez tout saisir</p>
<p>
<input type="radio" name="role" value="1">S'inscrire en tant qu'administrateur
<input type="radio" name="role" value="2" checked>S'inscrire en tant qu'utilisateur
</p>
Nom:<input type="text" name="name" required><br>
IDENTIFIANT D'UTILISATEUR:<input type="text" name="loginId" required><br>
mot de passe:<input type="password" name="pass" required><br>
<input type="submit" value="enregistrement"><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>Achèvement de l'inscription</title>
</head>
<body>
Nouvelle inscription terminée!
<p><a href="/login/AccountCheck"><button type="button" name="aaa" >Vers la page utilisateur ou administrateur</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>Informations de l'utilisateur</title>
</head>
<body>
Ceci est la page utilisateur.<br>
<c:choose>
<c:when test="${account.role == 2 }">
Confirmation des détails d'inscription.
<p>Identifiant de connexion:<c:out value="${account.loginId }"></c:out></p>
<p>mot de passe:<c:out value="${account.pass }"></c:out></p>
<p>Nom:<c:out value="${account.name }"></c:out></p>
<p>Rôle: utilisateur</p>
<p><a href="/login/Logout"><button type="button" >Se déconnecter</button></a></p>
<a href="admin.jsp"><button type="button" >Aller à la page d'administration</button></a>
</c:when>
<c:when test="${account.role == 1 }">
<a href="admin.jsp">Aller à la page d'administration</a>
</c:when>
<c:otherwise>
<a href="login.jsp">Aller à la page de connexion</a>
</c:otherwise>
</c:choose>
</body>
</html>
Recommended Posts