In this article, I will discuss some important key points and requirements to understand the Java project that is built using JSP, Servlet, and MYSQL.
Used tools and Technologies with the uses
These are the web applications in java and using JSP, Servlet, MYSQL, Tomcat, Maven, and following MVC. Now, let’s in detail the use of these tools.
What is Maven and Why Maven?
Maven is a project build automation tool and its also used to manage dependencies management. Now what I mean by dependencies management is, Let’s understand this by an example.
Before maven If we need to use other java services with our java application like MYSQL connection, Servlet, Logger, Junit. Then we have to download the jar file and add those jar files into the lib folder of the project.
But assume, their project is running on my machine and all the jars are stored in some folder in my machine and everything is working fine. Now If I move the project to another machine and put those jars at any other location same machine.
But the project assumes the jar location as the previous machine. So the code will not work because the jar is not found at the required location.
Now maven comes into the picture and gives a solution to download the required jar/libraries in real time while building the project. and keep the jar at the dynamic location so it will be the same for all machines and servers.
Where I will find maven dependencies?
In the project, check the pom.xml file, you will get the dependency under the <dependencies></dependencies> tag.
Below is an example of the logger dependency
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency>
To get the dependency you can just visit the official website of maven “https://mvnrepository.com/“, Search for the required dependency and grab the code and add it to your pom.xml. Once you save the pom.xml automatic project will build and it will add the jar to the maven dependency section.
Model View Controller(MVC)
MVC is known as model view controller, where the Model handles the database transactions or classes and methods that will help to create transactions, view defines the frontend of the application, the page elements that the user can view and see to perform the operations, and controller used to handle the request and response.
Let’s understand the MVC in detail in terms of project development.
While we working on MVC architecture the flow of the program execution will be View ==> Controller ==> Model
View:
As the name suggests, The visual things that the user can see come under the view part, Also we can say the view is similar to the front.
To develop the view part of any application the basic and important technologies are HTML, CSS, and Bootstrap.
Controller:
The controller is the mediator between the View and the Model. It will handle the requests and responses. It gets a request from the view and sends the request to the model to perform the required operations and at the same time, It gets the response from the model and forwards or redirects the same response to the view.
Model:
The model is the last layer of MVC, Model is used to manage the database transactions. While you working on an application where we need to store the information and it’s using any kind of database then to communicate with the database we need to write some model classes that contain the source code from required operations like Add/Edit/Delete and View the data.
Request and Response Flow(MVC flow/Project Code Flow)
Request:
- View to Controller
- Controller to model
- Model to database
Response:
- Database to Model
- Model to controller
- Controller to view
Project folder structure
src/main/java
“src/main/java” is the root folder of java code, this contains all the Java packages that are required to manage the backend of the application. following are the packages inside the “src/main/java”.
Beans
Java beans are the classes that provide a getter and setter of each attribute of the entity. It will help to convert the attributes into objects.
Let’s understand by an example, we have a user as an entity, User may have multiple attributes like Name, Email, Password, etc. So the UserBean will help to set these attribute values into an object and same time get these attribute values from an object.
Define an entity:
public class UserBean extends BaseBean{ private String userName; private String emailId; private String password; private String repeatPassword; private long phoneNo; private String gender; private long roleid; private String roleName; public long getRoleid() { return roleid; } public void setRoleid(long roleid) { this.roleid = roleid; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepeatPassword() { return repeatPassword; } public void setRepeatPassword(String repeatPassword) { this.repeatPassword = repeatPassword; } public long getPhoneNo() { return phoneNo; } public void setPhoneNo(long phoneNo) { this.phoneNo = phoneNo; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getKey() { return id+""; } public String getValue() { return emailId; } }
Set attributes value into an object
protected BaseBean populateBean(HttpServletRequest request) { UserBean bean = new UserBean(); bean.setId(DataUtility.getLong(request.getParameter("id"))); bean.setUserName(DataUtility.getString(request.getParameter("userName"))); bean.setEmailId(DataUtility.getString(request.getParameter("emailId"))); bean.setPassword(DataUtility.getString(request.getParameter("password"))); bean.setRepeatPassword(DataUtility.getString(request.getParameter("repeatpassword"))); bean.setPhoneNo(DataUtility.getLong(request.getParameter("phoneNo"))); bean.setGender(DataUtility.getString(request.getParameter("gender"))); bean.setRoleid(2); bean.setRoleName("User"); populateDTO(bean, request); return bean; }
Get Attributes value from an Object
public long Update(UserBean bean) { System.out.println("in model update method"); int pk = 0; try { Connection conn = JDBCDataSource.getConnection(); PreparedStatement ps = conn.prepareStatement( "update USER set userName=?, emailId=?, password=?, repeatPassword=?, phoneNo=?,gender=?,roleid=?,roleName=? where id=?"); ps.setString(1, bean.getUserName()); ps.setString(2, bean.getEmailId()); ps.setString(3, bean.getPassword()); ps.setString(4, bean.getRepeatPassword()); ps.setLong(5, bean.getPhoneNo()); ps.setString(6, bean.getGender()); ps.setLong(7, bean.getRoleid()); ps.setString(8, bean.getRoleName()); ps.setLong(9, bean.getId()); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return pk; }
-
Controllers
Controllers are the servlet classes that are responsible for getting the data as requested and sending the data to the model to perform the database transaction. also, controllers take responses from models and send that responses to view.
UserController:
package com.cab.booking.Controller; import java.io.IOException; 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 com.cab.booking.Bean.BaseBean; import com.cab.booking.Bean.UserBean; import com.cab.booking.Model.UserModel; import com.cab.booking.Utility.DataUtility; import com.cab.booking.Utility.DataValidator; import com.cab.booking.Utility.PropertyReader; import com.cab.booking.Utility.ServletUtility; /** * Servlet implementation class UserCtl */ @WebServlet(name = "UserCtl", urlPatterns = "/user") public class UserCtl extends BaseCtl { private static final long serialVersionUID = 1L; public static final String OP_UPDATE = "Update"; public static final String OP_SAVE = "Save"; public UserCtl() { super(); } @Override protected BaseBean populateBean(HttpServletRequest request) { UserBean bean = new UserBean(); bean.setId(DataUtility.getLong(request.getParameter("id"))); bean.setFirstName(DataUtility.getString(request.getParameter("firstName"))); bean.setLastName(DataUtility.getString(request.getParameter("lastName"))); bean.setEmail(DataUtility.getString(request.getParameter("email"))); bean.setPassword(DataUtility.getString(request.getParameter("password"))); bean.setContactNo(DataUtility.getString(request.getParameter("contactNo"))); bean.setCity(DataUtility.getString(request.getParameter("city"))); bean.setAddress(DataUtility.getString(request.getParameter("address"))); bean.setGender(DataUtility.getString(request.getParameter("gender"))); bean.setRoleName(DataUtility.getString(request.getParameter("roleName"))); bean.setRoleid(DataUtility.getLong(request.getParameter("roleid"))); System.out.println("RoleName :" +bean.getRoleName()); System.out.println("RoleId :" +bean.getRoleid()); if (bean.getRoleid()==2) { bean.setRoleName("User"); }else { bean.setRoleName("Driver"); } bean.setStatus("1"); populateDTO(bean, request); return bean; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserModel model = new UserModel(); long id = DataUtility.getLong(request.getParameter("id")); if (id > 0) { UserBean bean = null; try { bean = model.findByPk(id); System.out.println("RoleName :" +bean.getRoleName()); System.out.println("In Do Get"); } catch (Exception e) { e.printStackTrace(); } ServletUtility.setbean(bean, request); } ServletUtility.forward(getView(), request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserModel model = new UserModel(); String op = DataUtility.getString(request.getParameter("operation")); long id = DataUtility.getLong(request.getParameter("id")); UserBean bean = new UserBean(); bean = (UserBean) populateBean(request); if (OP_UPDATE.equalsIgnoreCase(op)){ System.out.println("in do post2"); long i = model.Update(bean); System.out.println("RoleName :" +bean.getRoleName()); System.out.println("RoleId :" +bean.getRoleid()); ServletUtility.setSuccessMessage("Data Updated Successfully", request); } else { try { long pk = model.add(bean); ServletUtility.setSuccessMessage("Data Add Successfully", request); } catch (Exception e) { e.printStackTrace(); } } ServletUtility.forward(getView(), request, response); } @Override protected String getView() { return TBSView.USER_VIEW; } }
-
Exceptions
Exception packages contain the Exception classes, and those classes will be used in the entire project according to the requirement. let’s take the example of “Record not found”. In case the user is sending a request to find some data and that data or record is not available in that case we have to send the “Record not found” exception.
package com.cab.booking.Exception; public class RecordNotFoundException extends Exception{ public RecordNotFoundException(String msg) { super(msg); } }
-
Model
Model packages contain simple Java classes that will be responsible to handle the database transaction. we can create model classes according to the model or entity. Let’s take an example of a user Entity in the project. To handle the user’s database operations we have to create Usermodel.java classes that contain methods to ADD/EDIT/DELETE/View the user’s information or any kind of database transaction that is related to the User.
package com.cab.booking.Model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.cab.booking.Bean.UserBean; import com.cab.booking.Exception.ApplicationException; import com.cab.booking.Exception.DuplicateRecordException; import com.cab.booking.Utility.JDBCDataSource; public class UserModel { public Integer nextpk() throws Exception { Connection conn = null; int pk = 0; try { conn = JDBCDataSource.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT MAX(ID) FROM t_user"); ResultSet rs = ps.executeQuery(); while (rs.next()) { pk = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return pk + 1; } public UserBean findByLogin(String login) throws Exception { UserBean bean = null; Connection conn = null; try { conn = JDBCDataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_user WHERE login=?"); ps.setString(1, login); ResultSet rs = ps.executeQuery(); while (rs.next()) { bean = new UserBean(); bean.setId(rs.getLong(1)); bean.setCreatedby(rs.getString(2)); bean.setCreatedatetime(rs.getTimestamp(3)); bean.setModifiedby(rs.getString(4)); bean.setModifieddatetime(rs.getTimestamp(5)); bean.setAddress(rs.getString(6)); bean.setCity(rs.getString(7)); bean.setContactNo(rs.getString(8)); bean.setFirstName(rs.getString(9)); bean.setGender(rs.getString(10)); bean.setLastName(rs.getString(11)); bean.setEmail(rs.getString(12)); bean.setPassword(rs.getString(13)); bean.setRoleid(rs.getLong(14)); bean.setRoleName(rs.getString(15)); bean.setStatus(rs.getString(16)); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return bean; } public UserBean findByPk(long pk) throws Exception { UserBean bean = null; Connection conn = null; try { conn = JDBCDataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_user WHERE id=?"); ps.setLong(1, pk); ResultSet rs = ps.executeQuery(); while (rs.next()) { bean = new UserBean(); bean.setId(rs.getLong(1)); bean.setCreatedby(rs.getString(2)); bean.setCreatedatetime(rs.getTimestamp(3)); bean.setModifiedby(rs.getString(4)); bean.setModifieddatetime(rs.getTimestamp(5)); bean.setAddress(rs.getString(6)); bean.setCity(rs.getString(7)); bean.setContactNo(rs.getString(8)); bean.setFirstName(rs.getString(9)); bean.setGender(rs.getString(10)); bean.setLastName(rs.getString(11)); bean.setEmail(rs.getString(12)); bean.setPassword(rs.getString(13)); bean.setRoleid(rs.getLong(14)); bean.setRoleName(rs.getString(15)); bean.setStatus(rs.getString(16)); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return bean; } public UserBean Authenticate(String login, String Password) throws Exception { UserBean bean = null; Connection conn = null; try { conn = JDBCDataSource.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_user WHERE login =? AND password =?"); ps.setString(1, login); ps.setString(2, Password); ResultSet rs = ps.executeQuery(); while (rs.next()) { bean = new UserBean(); bean.setId(rs.getLong(1)); bean.setCreatedby(rs.getString(2)); bean.setCreatedatetime(rs.getTimestamp(3)); bean.setModifiedby(rs.getString(4)); bean.setModifieddatetime(rs.getTimestamp(5)); bean.setAddress(rs.getString(6)); bean.setCity(rs.getString(7)); bean.setContactNo(rs.getString(8)); bean.setFirstName(rs.getString(9)); bean.setGender(rs.getString(10)); bean.setLastName(rs.getString(11)); bean.setEmail(rs.getString(12)); bean.setPassword(rs.getString(13)); bean.setRoleid(rs.getLong(14)); bean.setRoleName(rs.getString(15)); bean.setStatus(rs.getString(16)); } } catch (Exception e) { e.printStackTrace(); } return bean; } public long add(UserBean bean) throws Exception { System.out.println("in add method"); Connection conn = null; int pk = 0; UserModel model = new UserModel(); UserBean existbean = findByLogin(bean.getEmail()); if (existbean != null) { throw new DuplicateRecordException("Login Id already exist"); } try { conn = JDBCDataSource.getConnection(); pk = nextpk(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("INSERT INTO t_user VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setLong(1, pk); ps.setString(2, bean.getCreatedby()); ps.setTimestamp(3, bean.getCreatedatetime()); ps.setString(4, bean.getModifiedby()); ps.setTimestamp(5, bean.getModifieddatetime()); ps.setString(6, bean.getAddress()); ps.setString(7, bean.getCity()); ps.setString(8, bean.getContactNo()); ps.setString(9, bean.getFirstName()); ps.setString(10, bean.getGender()); ps.setString(11, bean.getLastName()); ps.setString(12, bean.getEmail()); ps.setString(13, bean.getPassword()); ps.setLong(14, bean.getRoleid()); ps.setString(15, bean.getRoleName()); ps.setString(16, bean.getStatus()); ps.executeUpdate(); conn.commit(); ps.close(); } catch (Exception e) { e.printStackTrace(); try { conn.rollback(); } catch (Exception e2) { e.printStackTrace(); throw new ApplicationException("Exception : add rollback exception " + e.getMessage()); } } finally { JDBCDataSource.closeconnection(conn); } return pk; } public List list() throws Exception { System.out.println("in model list"); ArrayList list = new ArrayList(); Connection conn = null; conn = JDBCDataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement("SELECT * from t_user"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { UserBean bean = new UserBean(); bean.setId(rs.getLong(1)); bean.setCreatedby(rs.getString(2)); bean.setCreatedatetime(rs.getTimestamp(3)); bean.setModifiedby(rs.getString(4)); bean.setModifieddatetime(rs.getTimestamp(5)); bean.setAddress(rs.getString(6)); bean.setCity(rs.getString(7)); bean.setContactNo(rs.getString(8)); bean.setFirstName(rs.getString(9)); bean.setGender(rs.getString(10)); bean.setLastName(rs.getString(11)); bean.setEmail(rs.getString(12)); bean.setPassword(rs.getString(13)); bean.setRoleid(rs.getLong(14)); bean.setRoleName(rs.getString(15)); bean.setStatus(rs.getString(16)); list.add(bean); } return list; } public static long delete(long id) { int i = 0; try { Connection conn = JDBCDataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE from t_user where id=?"); stmt.setLong(1, id); i = stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return i; } public long Update(UserBean bean) { System.out.println("in model update method"); int pk = 0; try { Connection conn = JDBCDataSource.getConnection(); PreparedStatement ps = conn.prepareStatement( "update t_user set created_by = ?, created_datetime=? ,modified_by=?,modified_datetime=?, address=?,city=?,contact_no=?,first_name=?,gender=?,last_name=?, login=?, password=?,role_id=?,role_name=?,status=? where id=?"); ps.setString(1, bean.getCreatedby()); ps.setTimestamp(2, bean.getCreatedatetime()); ps.setString(3, bean.getModifiedby()); ps.setTimestamp(4, bean.getModifieddatetime()); ps.setString(5, bean.getAddress()); ps.setString(6, bean.getCity()); ps.setString(7, bean.getContactNo()); ps.setString(8, bean.getFirstName()); ps.setString(9, bean.getGender()); ps.setString(10, bean.getLastName()); ps.setString(11, bean.getEmail()); ps.setString(12, bean.getPassword()); ps.setLong(13, bean.getRoleid()); ps.setString(14, bean.getRoleName()); ps.setString(15, bean.getStatus()); ps.setLong(16, bean.getId()); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return pk; } public List search(UserBean bean) throws Exception { StringBuffer sql = new StringBuffer("SELECT * from t_user WHERE 1=1"); if (bean != null) { if (bean.getId() > 0) { sql.append(" AND id = " + bean.getId()); } if (bean.getEmail() != null && bean.getEmail().length() > 0) { sql.append(" AND login like '" + bean.getEmail() + "%'"); } } ArrayList list = new ArrayList(); Connection conn = null; try { conn = JDBCDataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { bean = new UserBean(); bean.setId(rs.getLong(1)); bean.setCreatedby(rs.getString(2)); bean.setCreatedatetime(rs.getTimestamp(3)); bean.setModifiedby(rs.getString(4)); bean.setModifieddatetime(rs.getTimestamp(5)); bean.setAddress(rs.getString(6)); bean.setCity(rs.getString(7)); bean.setContactNo(rs.getString(8)); bean.setFirstName(rs.getString(9)); bean.setGender(rs.getString(10)); bean.setLastName(rs.getString(11)); bean.setEmail(rs.getString(12)); bean.setPassword(rs.getString(13)); bean.setRoleid(rs.getLong(14)); bean.setRoleName(rs.getString(15)); bean.setStatus(rs.getString(16)); list.add(bean); } rs.close(); } catch (Exception e) { } finally { JDBCDataSource.closeconnection(conn); } return list; } }
-
utility
There are multiple utility classes that are used as helper classes and must request to improve the code reusability.
DataUtility: Used to convert the data from one form to another form. It contains all the conversion methods.
DataValidator: Used to validate the data.
ServletUtiltiy: Helper for the servlet operations.
DataSource: Used to manage the database connections
src/main/resources
- system.properties: It contains the external parameter of the application in the form of key and value.
webapp
The web app folder contains all the resources that will be used to design the view part of the front end of the application. As per the file structure, its devices are into 3 parts, CSS, JS, and JSP.
- CSS: The CSS folder contains all the styling or bootstrap files.
- JSP: this folder contains all the JSP files that define the front of the project.