Author: RANAIVOSON NY Hoavisoa Misandratra (ETU002556)
A lightweight Java-based web framework designed to handle servlet-based applications with custom annotations for routing, file uploads, data validation, and authentication management. It emphasizes extensibility and ease of use within servlet-compatible environments.
- Overview
- Requirements
- Features
- Project Timeline (Sprints)
- Test Project (Usage Example)
- Setup Instructions (Compiling the Framework)
- Deploying the Test Project
- Usage Notes
- Bug Reports
The Handmade Framework is a custom-built Java web framework that simplifies the development of servlet-based applications. It provides features like custom annotations for routing, file uploads, form validation, and authentication/authorization management. The framework is designed to be extensible and easy to integrate into servlet-compatible servers.
Warning: In case there is an error in the compilation of the classes, please delete the duplicated classes that do not match the package structure.
To use the Handmade Framework, you need:
- Java: Version 8 or higher
- Servlet-Compatible Server: A server capable of running servlet applications (e.g., Apache Tomcat, Jetty)
- Dependencies: Gson library for JSON serialization (included in Sprint 9)
The framework offers a comprehensive set of tools for modern web development:
- Custom Annotations: Define controllers, routes, parameters, and authentication with annotations like
@Url,@Get,@Post,@Restapi,@Param,@ModelAttribute,@Authentified, and@Role. - File Upload Handling: Upload and manage files using the
FileUploadclass, including methods for getting file type, content, and saving to a specified folder. - Data Validation: Validate form inputs using a dedicated
Validatorclass and annotations:@NotNull: Ensures a field is not null.@Email: Validates the field is a properly formatted email address.@Range: Checks if a numeric value is within a specified range [min/max](cite: 1).@Length: Enforces a maximum length for a string field.
- Form Validation Management: Dedicated classes (
MessageValue.java,FormValidation.java) manage form errors, allowing for the resending of users to forms with error messages and old input values. - Authentication & Authorization: Secure methods and entire classes using:
@Authentified: Requires an authenticated user.@Role: Restricts access based on user role[s](cite: 1).
- REST API Support: Handle JSON responses with the
@Restapiannotation and utilize theModelView.toJson()method [requires Gson](cite: 1). - Session Management: Use
MySessionfor session-based operations, including areset()function to delete all session data. - Error Handling: Custom exceptions with
MyExceptionallow for detailed error reporting, including custom error codes and the ability to specify the underlying cause of an exception. - Model/View Utilities:
ModelViewhelps prepare the view, and also handles thebase_urlconfiguration fromweb.xmlfor universal redirection and includes aDecimalFormat(formatter) for US-style number formatting in views. - Data Type Support: Enhanced support for parameter and field types including
int,double,float,String,java.sql.Date,Time,Timestamp, andboolean.
- Sprint 0: Initial Setup with
FrontController.javaandcompilate.bat. - Sprint 1: Core Controller Logic with
AnnotationController.java,ControllerScanner.java. - Sprint 2: Annotation organization and addition of
Mapping.java. - Sprint 3: Reflection utility (
Refflect.java) andinvokeMappedMethod. - Sprint 4: Model-View Support with
ModelView.javaand return type verification. - Sprint 5: Enhanced error checks for package scanning, duplicate URLs, and request handling.
- Sprint 6: Parameter handling with
@Paramand reflection logic for parameters without an annotation. - Sprint 7: Model binding with
@ModelAttributeand@ModelField. - Sprint 8: Session management with
MySession.javaand enhanced reflection methods. - Sprint 9: REST API Support with
@Restapi,ModelView.toJson(), and content type handling. - Sprint 10: HTTP Verb Annotations (
@Urlrenamed fromGet.java),@Get, and@Postwith verb validation inFrontController.
- VerbAction: Created
VerbAction.javato map method names to HTTP verbs. - Mapping: Refactored
Mapping.javato useSet<VerbAction> ls_verbActionfor multiple methods per URL. - Exceptions: Introduced
MyException.javawith custom error codes. - Refactoring: Created
FrontControllerMethod.javato separate method-related logic fromFrontController.java.
- URL Concatenation:
FrontControllerMethodnow concatenatesAnnotationControllername withUrlannotation value. - View Dispatching:
ModelView.prepareModelViewadjusted for correct view pathing. - FileUpload: Added
FileUpload.javafor handling file uploads usingPartobjects and methods for saving, getting type, and content.
- Type Checking: Improved parameter and field type validation in
Mapping.javato includejava.sql.DateandString, throwingIllegalStateExceptionfor unsupported types. - Validation Annotations: Added
@NotNull,@Email,@Range, and@Length. - Validator: Created
Validator.javato centralize field validation logic.
- Error Objects: Added
MessageValue.java(error message + old input value) andFormValidation.java[list of errors](cite: 1). - Error Handling:
MyException.javaconstructor updated to include anexception_cause. - Form Resubmission:
Mapping.javaupdated to capture validation errors inFormValidation, add submitted values, and forward the user back to the form with errors, preventing multiple forwards.
- Sprint 15 (Method-Level): Added
@Authentifiedand@Roleannotations and implementedverifyMethodPermissioninMapping.java. - Sprint 16 (Class-Level): Modified
@Authentifiedand@Roleto be applicable at the class level, implementedverifyClassPermission.
- Data Types: Added support for
boolean,Time, andTimestampin parameter handling. - ModelView: Rectified
prepareModelViewfor the root route (/) and to ensure universal pathing by changing../to/. Addedbase_urlhandling fromweb.xmlfor redirection. AddedDecimalFormat(formatter) to request attributes for decimal number display. - Validation: Corrected logic in
Validator.rangeCheckfor handling empty min/max values. - Model: Added handling for the
@Ignoredannotation to skip field processing and@DefaultNullto set a field tonullby default. - Session: Added
MySession.reset()to clear session data. - Error Handling: Updated
FrontController.doGet/doPostto include a button to return to thebase_urlon exception.
- Package Refactoring: Modified all classes from
srcto use the package namecom.thekingjoker18.handmade_frameworkto prevent conflicts when the framework is used as a library. - Test Project Uploaded: Uploaded a complete test project to the GitHub repository to provide a tangible example of how to use the framework.
- Web.xml Example: Updated the
web.xml.exampleto reflect the new package name for the controller servlet.
To see a practical, working example of how to use this framework, please see the test project included in the main GitHub repository.
This test project demonstrates:
- Controller setup
- Form handling (simple and model-based)
- File uploads
- Session management (login/logout)
- Data validation
It also includes a detailed HOWTOUSE.md file that guides you through the examples.
Follow these steps to compile the framework into a .jar file, which you can then include in your own web projects.
-
Clone the Repository:
git clone <repository-url>
-
Install Java 8+: Ensure Java 8 or higher is installed.
-
Add Dependencies: Ensure all dependencies (like
servlet-api.jarandgson.jar) are available. Thecompilate.batscript expects them in..\test\lib. -
Compile the Framework:
-
On Windows:
- Navigate to the
developmentfolder (wherecompilate.batis located). - Important: Before running, you must edit
compilate.batand change thelibanddestinationvariables to point to your project'slibfolder. - Run the
compilate.batscript. - This will compile the Java source files, create the
handmade_framework.jarfile, and copy it to your specifieddestinationfolder[cite: 4].
- Navigate to the
-
On Linux/macOS: Run the following commands from the framework's root directory.
Note: You must adjust the
LIB_DIRandDESTINATION_DIRvariables to match your project's paths.#!/bin/bash # --- CONFIGURATION --- # Adjust these paths to your dependencies and target project LIB_DIR="../test/lib" DESTINATION_DIR="../test/lib" # --------------------- SRC_DIR="./src/com/thekingjoker18/handmade_framework" BIN_DIR="./bin" JAR_NAME="handmade_framework.jar" # Clean and create bin directory echo "Cleaning old build..." rm -rf "$BIN_DIR" mkdir -p "$BIN_DIR" # Find all java files and compile them echo "Compiling source files..." find "$SRC_DIR" -name "*.java" > sources.txt javac --release 8 -d "$BIN_DIR" -cp "$LIB_DIR/*" @sources.txt rm sources.txt # Create the JAR file echo "Creating JAR file..." jar cvf "$JAR_NAME" -C "$BIN_DIR" . # Copy JAR to destination echo "Copying $JAR_NAME to $DESTINATION_DIR..." cp "$JAR_NAME" "$DESTINATION_DIR/" echo "Compilation complete."
-
-
Add to Your Project: Place the generated
handmade_framework.jarfile into theWEB-INF/libdirectory of the web application project you are developing.NB: Don't forget to verify if your
web.xmlfollows the given example on the 'main' repository for proper framework configuration.
The included test project has its own deployment script, deploiement.bat, to automate building and deploying it to a Tomcat server.
-
Compile the Framework First: Before deploying the test project, you must first compile the framework (see steps above) and ensure the
handmade_framework.jaris in the test project'slibfolder. -
Configure Deployment Script:
- Navigate to the test project's root folder.
- Important: Open
deploiement.batin a text editor. - You must change the
webappsvariable to match thewebappsdirectory of your Tomcat (or other) server. - Example:
set "webapps=C:\Program Files\Apache-Tomcat-9.0\webapps"
-
Run the Deployment Script:
- Execute
deploiement.bat. - The script will:
- Create a temporary staging directory.
- Copy your test project's web files (JSPs, CSS),
web.xml, and all libraries (including the framework.jar) into it. - Compile your test project's
.javafiles (controllers, models, servlets). - Bundle everything into a
.warfile. - Copy the
.warfile directly to your server'swebappsdirectory[cite: 2], where it will be automatically deployed.
- Execute
- Compilation Errors: If you encounter duplicate class errors, remove any conflicting classes that do not match the package structure.
- Annotations: Use
@Url,@Get,@Post, and@Restapito define routes and HTTP methods. - Validation: Apply
@NotNull,@Email,@Range, and@Lengthto enforce data constraints. - File Uploads: Use
FileUploadfor handling file uploads in controller methods. - Authentication: Secure methods or classes with
@Authentifiedand@Role. - ModelView: Access the request attribute
formatter(aDecimalFormat) in your JSPs to format decimal numbers using the US style (#,###.##).
For bug reports or feature requests, please open an issue on the project's repository.