This steps use Netbeans version 31.
to create tomcat apache project in netbeans follow these steps:
- open your netbeans
- File -> New Project -> java with Maven -> Web Application
- fill "Project Name" e.g. My Servlet
- in New Web Application -> Server click Add
- select Apache Tomcat or TomEE
- select your jakarta tomcat directory
- fill username and password from tomcat-users.xml file which is has rule rolename="manager-gui"
- Finish will return to New Web Application, then Finish
to create a new servlet
- From your project -> Source Packages -> <package_name>. MyServlet, right click and create New -> Servlet
- Class Name: HelloWorld, then next
- Servlet Name: My Servlet
- URL Pattern: /HelloWorkd
- This will create default response
- run from your netbeans, and your HelloWorld will appear in browser with url http://localhost:8080/MyServlet/HelloWorld
now, we add mariadb into our project, edit Project Files -> pom.xml
<dependencies>
....
<!-- MariaDB JDBC driver -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.5.10</version>
</dependency>
</dependencies>now edit HelloWorld.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HelloWorld </title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet HelloWorld at " + request.getContextPath() + " 0261015</h1>");
// connect to db
out.println("<p>connecting to mariadb</p>");
try {
Class.forName("org.mariadb.jdbc.Driver");
out.println("<p>MariaDB JDBC driver FOUND</p>");
try (java.sql.Connection conn =
java.sql.DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/<db_name>",
"<db_user>",
"<db_password>")) {
out.println("<p>MariaDB CONNECTION SUCCESSFUL</p>");
out.println("<p>Database: "
+ conn.getCatalog() + "</p>");
} catch (SQLException ex) {
out.println("<p>Error"+ex.getMessage()+"</p>");
}
} catch (ClassNotFoundException e) {
out.println("<p>MariaDB JDBC driver NOT FOUND</p>");
}
out.println("</body>");
out.println("</html>");
}
}run your servlet.
if no error found, you may start writing your application.
hint: use any ai to find error in your code, copy paste code and error. but Do Not rely on it, use your instinct to fix your code, ai may made mistake.