0% found this document useful (0 votes)
7 views7 pages

Advanced Jakarta EE Student Management Guide

This document provides a comprehensive guide for enhancing a Jakarta EE Student Management System, covering architecture reinforcement, user experience improvements, REST API expansion, authentication, deployment, and analytics. It includes step-by-step instructions, code snippets, and best practices for implementing features such as DTOs, bean validation, logging, DataTables integration, and Docker deployment. The guide emphasizes maintaining separate configurations for development and production, using HTTPS, and implementing proper testing and CI/CD processes.

Uploaded by

iamnoir8080
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Advanced Jakarta EE Student Management Guide

This document provides a comprehensive guide for enhancing a Jakarta EE Student Management System, covering architecture reinforcement, user experience improvements, REST API expansion, authentication, deployment, and analytics. It includes step-by-step instructions, code snippets, and best practices for implementing features such as DTOs, bean validation, logging, DataTables integration, and Docker deployment. The guide emphasizes maintaining separate configurations for development and production, using HTTPS, and implementing proper testing and CI/CD processes.

Uploaded by

iamnoir8080
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Student Management System — Next Level Guide

(Step-by-step)
This document contains step-by-step instructions and the full contents of altered or newly added files to
take your Jakarta EE Student Management System (package: [Link])
to the next levels of maturity: architecture hardening, UX improvements, REST API, security, deployment,
and analytics. Paste these files into your NetBeans project and follow the instructions in each section.

LEVEL 1 — Data & Architecture Reinforcement


1.1 Add DTO ([Link]). Purpose: decouple presentation from persistence. Create new file:
package [Link];

public class StudentDTO {


private int id;
private String name;
private String email;
private String course;
private double gpa;

public StudentDTO() {}

public StudentDTO(int id, String name, String email, String course, double gpa) {
[Link] = id; [Link] = name; [Link] = email; [Link] = course; [Link] = gpa;
}

public int getId() { return id; }


public void setId(int id) { [Link] = id; }
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public String getEmail() { return email; }
public void setEmail(String email) { [Link] = email; }
public String getCourse() { return course; }
public void setCourse(String course) { [Link] = course; }
public double getGpa() { return gpa; }
public void setGpa(double gpa) { [Link] = gpa; }
}

Mapping: create simple helper methods (or use ModelMapper). Add this helper in a util class:
package [Link];

import [Link];
import [Link];

public class Mapper {


public static StudentDTO toDTO(Student s) {
if (s == null) return null;
return new StudentDTO([Link](), [Link](), [Link](), [Link](), [Link]());
}
public static Student toEntity(StudentDTO d) {
if (d == null) return null;
Student s = new Student([Link](), [Link](), [Link](), [Link]());
[Link]([Link]());
return s;
}
}

1.2 Add Bean Validation to the Student entity. Replace your [Link] with the version below (uses
[Link] annotations):
package [Link];

import [Link].*;
import [Link].*;

@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue(strategy = [Link])
private int id;

@NotBlank
@Size(max = 100)
private String name;

@NotBlank
@Email
@Size(max = 100)
private String email;

@Size(max = 100)
private String course;

@DecimalMin("0.0")
@DecimalMax("4.0")
private double gpa;

public Student() { }

public Student(String name, String email, String course, double gpa) {


[Link] = name; [Link] = email; [Link] = course; [Link] = gpa;
}

public int getId() { return id; }


public void setId(int id) { [Link] = id; }
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public String getEmail() { return email; }
public void setEmail(String email) { [Link] = email; }
public String getCourse() { return course; }
public void setCourse(String course) { [Link] = course; }
public double getGpa() { return gpa; }
public void setGpa(double gpa) { [Link] = gpa; }
}

1.2b Example of server-side validation in the servlet using Validator API (add to doPost before persisting):
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

// inside doPost, after creating Student entity 'student'


ValidatorFactory factory = [Link]();
Validator validator = [Link]();
Set<ConstraintViolation<Student>> violations = [Link](student);
if (![Link]()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation<Student> v : violations) {
[Link]([Link]()).append(": ").append([Link]()).append("\n");
}
setFlashMessage(request, "Validation failed: " + [Link]());
[Link]("students"); // or forward back to form with errors
return;
}

1.3 Add logging to DAO and Servlet. Example logger in [Link]:


package [Link];

import [Link];
import [Link];
import [Link].*;
import [Link];

@Stateless
public class StudentDAO {
private static final Logger logger = [Link]([Link]());

@PersistenceContext(unitName = "studentPU")
private EntityManager em;

public void addStudent(Student student) {


[Link](student);
[Link]("Added student id=" + [Link]());
}
// other methods with logging...
}

LEVEL 2 — User Experience Revolution


2.1 Create a [Link] template and fragment includes. This keeps the UI consistent. Add two fragments
under WEB-INF/fragments: [Link] and [Link] (these were provided earlier). You can also create
[Link] to include header, content, footer. Example [Link]:
<%@ include file="WEB-INF/fragments/[Link]" %>
<jsp:include page="${content}" />
<%@ include file="WEB-INF/fragments/[Link]" %>

2.2 DataTables integration for searchable, pageable tables. Add jQuery and DataTables includes and
initialize the table. Updated [Link] snippet (add to head and bottom):
<!-- DataTables CSS/JS (add to header) -->
<link rel="stylesheet" href="[Link]
<script src="[Link]
<script src="[Link]

<!-- Initialize table -->


<script>
$(document).ready(function() {
$('#studentsTable').DataTable({
"pageLength": 10
});
});
</script>

<!-- ensure your table has id studentsTable -->


<table id="studentsTable" class="table table-striped"> ... </table>

2.3 Toasts and validation feedback: update servlet to forward validation messages to request and show
them in the form using Bootstrap alerts. Example alert snippet for [Link]:
<c:if test="${not empty errors}">
<div class="alert alert-danger">
<ul>
<c:forEach var="err" items="${errors}">
<li>${err}</li>
</c:forEach>
</ul>
</div>
</c:if>

LEVEL 3 — REST API Expansion


3.1 Add JAX-RS resource to expose JSON endpoints. Create [Link] under package
[Link]:
package [Link];

import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];

@Path("/students")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class StudentResource {

@Inject
private StudentDAO dao;

@GET
public List<Student> getAll() {
return [Link]();
}

@GET
@Path("{id}")
public Response getById(@PathParam("id") int id) {
Student s = [Link](id);
if (s == null) return [Link]([Link].NOT_FOUND).build();
return [Link](s).build();
}

@POST
public Response create(Student student) {
[Link](student);
return [Link]([Link]).build();
}

@PUT
@Path("{id}")
public Response update(@PathParam("id") int id, Student student) {
[Link](id);
[Link](student);
return [Link]().build();
}

@DELETE
@Path("{id}")
public Response delete(@PathParam("id") int id) {
[Link](id);
return [Link]().build();
}
}

3.2 Register JAX-RS by creating an Application subclass: [Link]


package [Link];

import [Link];
import [Link];

@ApplicationPath("/api")
public class ApplicationConfig extends Application { }

LEVEL 4 — Authentication and Roles


4.1 Simple session-based authentication (filter + login page). Create a User entity (simplified) and a
LoginServlet + AuthFilter. Example [Link]:
package [Link];

import [Link].*;

@Entity
@Table(name = "app_user")
public class User {
@Id @GeneratedValue(strategy = [Link])
private int id;
private String username;
private String password; // in prod, store hashed passwords!
private String role;
// getters/setters...
}

4.2 AuthFilter to protect /students endpoints:


package [Link];

import [Link].*;
import [Link];
import [Link].*;
import [Link];

@WebFilter("/students")
public class AuthFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = [Link](false);
if (session == null || [Link]("user") == null) {
((HttpServletResponse) res).sendRedirect([Link]() + "/[Link]"); return;
}
[Link](req, res);
}
}

4.3 Simple [Link] (form) and LoginServlet example (validate against User table):
<!-- [Link] -->
<%@ page contentType="text/html;charset=UTF-8" %>
<form method="post" action="login">
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit">Login</button>
</form>
// [Link] (simplified)
package [Link];

import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link];

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Inject private UserDAO userDAO;
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
String u = [Link]("username");
String p = [Link]("password");
User user = [Link](u);
if (user != null && [Link]().equals(p)) {
[Link](true).setAttribute("user", user);
[Link]([Link]() + "/students"); return;
}
[Link]("error","Invalid credentials"); [Link]("[Link]").forward(req,
resp);
}
}

LEVEL 5 — Professional Deployment and Scaling


5.1 Docker Compose (Payara + MySQL). Create [Link]:
version: '3.8'
services:
mysql:
image: mysql:8.0
restart: always
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: studentdb
ports:
- "3306:3306"
volumes:
- mysql-data:/var/lib/mysql

payara:
image: payara/server-full:6.2025.9
depends_on:
- mysql
ports:
- "8080:8080"
- "4848:4848"
volumes:
- ./[Link]:/opt/payara/deployments/[Link]
- ./[Link]:/opt/payara/payara41/glassfish/domains/domain1/lib/[Link]

volumes:
mysql-data: {}

5.2 Dockerfile (optional) for building your app image:


FROM payara/server-full:6.2025.9
COPY target/[Link] /opt/payara/deployments/[Link]
COPY [Link] /opt/payara/payara41/glassfish/domains/domain1/lib/
# environment variables and asadmin commands can be used to create JDBC resources at runtime

5.3 Flyway for DB migrations. Add Flyway config and initial migration script V1__create_student_table.sql
under src/main/resources/db/migration/:
-- V1__create_student_table.sql
CREATE TABLE student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
course VARCHAR(100),
gpa DECIMAL(3,2)
);

LEVEL 6 — Data Intelligence (Analytics & Charts)


6.1 Add a small analytics JSP ([Link]) using [Link]. Example [Link] snippet:
<canvas id="gpaChart" width="400" height="200"></canvas>
<script src="[Link]
<script>
const ctx = [Link]('gpaChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Math','CS','Physics'],
datasets: [{ label: 'Average GPA', data: [3.3,3.6,3.1] }]
}
});
</script>

6.2 Example REST endpoint to get avg GPA per course (add to StudentResource):
@GET
@Path("/stats/avg-gpa-by-course")
public Map<String, Double> avgGpaByCourse() {
// example JPQL grouping
List<Object[]> rows = [Link]("SELECT [Link], AVG([Link]) FROM Student s GROUP BY
[Link]").getResultList();
Map<String, Double> map = new HashMap<>();
for (Object[] r : rows) [Link]((String) r[0], ((Number) r[1]).doubleValue());
return map;
}

Final notes:
• Always maintain development and production configuration separately. • Use HTTPS in production and
never store plaintext passwords. • Add proper testing (unit + integration) and CI/CD for automated builds
and deployments. • Consider migrating to a lightweight microprofile architecture if you break the app into
services.
The files above are intentionally comprehensive but concise. Copy the relevant pieces into your NetBeans
project (matching packages and paths) and rebuild.

You might also like