Instead of writing HTML inside Java (as in Servlets), you can write HTML first and just insert Java logic where needed. This makes your code:
Easier to write
Easier to read
Easier to maintain
✅ 2. Separates Business Logic from Presentation
JSP handles presentation (UI/HTML)
Java classes or servlets handle business logic This separation follows the MVC pattern (Model–View–Controller), making your code more modular and testable.
✅ 3. Reusable Components
You can use:
JavaBeans for reusable data components
JSP tag libraries (like JSTL) to reduce Java code in JSP
Includes (<jsp:include>) to reuse common page parts like headers and footers
✅ 4. Built-in Session and Request Handling
JSP provides built-in access to:
request, response
session, application
out (for writing to the response) You don’t need to manually write boilerplate code to access these.
✅ 5. Automatic Servlet Generation
Behind the scenes, each JSP is compiled into a servlet. This gives you the power and performance of Java servlets, but with much less manual coding.
✅ 6. Integration with Enterprise Tools
JSPs integrate well with:
JDBC for database access
Java EE technologies (e.g., Servlets, EJBs)
Spring MVC and other frameworks
Summary:
We need JSP because it bridges the gap between HTML page design and Java server-side logic. It allows for rapid, dynamic content generation with less code and better organization than using servlets alone.
Posted inБез рубрики|Comments Off on Java.Servlet.Why do we need JSP?
Servlet 3.0 (finalized in December 2009, part of Java EE 6) brought major improvements to simplify development and support modern web applications.
✅ Main Features introduced in Servlet 3.0:
Feature
Description
1. Annotation-based Configuration
No more messy web.xml! You can declare servlets, filters, listeners with annotations like @WebServlet, @WebFilter, @WebListener.
2. Pluggability
Web apps can bring their own servlets/filters/listeners in their own JARs — the container auto-scans for annotations.
3. Asynchronous Processing (Async Servlet)
Servlets can handle long-running tasks without blocking threads → super important for scalability (ex: chat apps, long polling).
4. Programmatic Configuration
You can add servlets, filters, listeners dynamically at runtime (inside ServletContextListener).
5. File Upload Support (Multipart)
Built-in support for handling file uploads (@MultipartConfig, request.getPart()), no need for third-party libraries like Apache Commons FileUpload anymore.
You had to declare everything inside a huge web.xml file.
After Servlet 3.0:
You can just annotate your classes:
import jakarta.servlet.annotation.WebServlet;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
// no need to touch web.xml
}
Similarly for Filters:
@WebFilter("/*")
public class MyFilter implements Filter { }
Listeners:
@WebListener
public class AppContextListener implements ServletContextListener { }
2. Pluggability
You can drop JARs inside WEB-INF/lib/, and if those JARs have servlets, filters, or listeners annotated → container automatically discovers and loads them.
Very useful for modular apps or frameworks!
3. Asynchronous Processing
New in Servlet 3.0: Async Servlet API!
Traditionally, servlet processing was strictly synchronous: one request → one thread.
Now you can startAsync() to free the thread and do background work.
Example:
@WebServlet(urlPatterns = "/async", asyncSupported = true)
public class AsyncServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
AsyncContext asyncContext = req.startAsync();
asyncContext.start(() -> {
try {
// Do some long running work
Thread.sleep(3000);
asyncContext.getResponse().getWriter().write("Async work done!");
asyncContext.complete();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
Benefit: server thread is not blocked during slow work → better scalability.
4. Programmatic Configuration
In ServletContextListener, you can now register servlets, filters, listeners programmatically without annotations or web.xml.
Example:
public class AppInitializer implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
ServletRegistration.Dynamic myServlet = ctx.addServlet("myServlet", new MyServlet());
myServlet.addMapping("/dynamic");
}
}
Use case: dynamic modules, plugins, or runtime decisions.
5. File Upload Support
No more external libraries needed!
You can declare:
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
// process the file
}
}
Built-in, simple, clean!
6. Security Enhancements
Programmatic login:
request.login(username, password);
Programmatic logout:
request.logout();
No need to always depend on form-based login configuration.
Also improved session tracking, declarative security options.
✅ Short answer: The connection pool (like HikariDataSource, Tomcat DataSource, etc.) should be destroyed when the web application is shutting down.
That means:
When Tomcat (or another servlet container) undeploys your app,
Or stops,
Or reloads the application.
Otherwise:
Database connections stay open → resource leak on database side.
Eventually database runs out of connections → errors like “Too many connections”.
✅ How to destroy it properly?
You must close the connection pool inside a ServletContextListener in the contextDestroyed() method.
Here’s the right lifecycle:
Event
What to do
App startup (contextInitialized)
Create connection pool and store it in ServletContext
App shutdown (contextDestroyed)
Close the connection pool safely
✅ Example again (proper destruction):
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import com.zaxxer.hikari.HikariDataSource;
@WebListener
public class AppContextListener implements ServletContextListener {
private HikariDataSource dataSource;
@Override
public void contextInitialized(ServletContextEvent sce) {
dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("user");
dataSource.setPassword("pass");
// Save it in the ServletContext so servlets can use it
sce.getServletContext().setAttribute("DataSource", dataSource);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Properly close the pool when the application shuts down
HikariDataSource ds = (HikariDataSource) sce.getServletContext().getAttribute("DataSource");
if (ds != null) {
ds.close(); // 🔥 Important: release all DB connections
}
}
}
✅ What happens when you call ds.close()?
All idle connections are closed.
Active connections are closed after use.
No new connections are accepted.
The pool is safely shutdown.
In short: the application cleans up after itself like a good citizen.
✅ If you forget to close:
Memory leak inside Tomcat or your server.
Database keeps connections busy unnecessarily.
Can cause deployment errors if you redeploy the app many times.
✅ Real-world checklist:
Thing
Should happen
During contextInitialized
Create + configure DataSource
Save it to
ServletContext attributes
During contextDestroyed
Fetch DataSource and call .close()
After closing
No memory leaks, no DB leaks
🌟 Visual Lifecycle:
App Startup
↓
ServletContextListener.contextInitialized()
↓
Create Connection Pool (DataSource)
↓
Servlets use connections from pool
↓
App Shutdown
↓
ServletContextListener.contextDestroyed()
↓
Close Connection Pool properly
✨ Final Reminder:
Connection objects are borrowed and returned automatically (with try-with-resources).
But the pool itself must be manually closed once when the app ends.
Posted inБез рубрики|Comments Off on Java.Servlet.If i created connection pool, when it should be destroyed ?
Open in servlet, close after use (try-with-resources)
Logging
SLF4J + Logback or similar
Initialization
Use ServletContextListener
Error handling
Catch and log exceptions properly
Resource closing
Always close Connection, ResultSet, PreparedStatement
🌟 Visual Diagram:
[App Startup]
↓
[ContextListener] → creates ConnectionPool (DataSource)
↓
[Servlets] → get DataSource → get Connection → work → close Connection
↓
[Logging] → all events, errors, debug info
Posted inБез рубрики|Comments Off on Java.Servlet.How can we organize a database connection, provide logging in a servlet?
Check for Mixed Content: all your links, images, CSS, JS must also load over HTTPS!
✅ Summary:
Step
Action
Get certificate
From CA or Let’s Encrypt
Configure server
Use HTTPS/TLS settings
Redirect all HTTP traffic
Force HTTPS
Test and validate
Ensure everything is secure
✅ Visual timeline:
Browser sends request → Server responds with certificate → Browser verifies → TLS handshake → Encrypted communication begins 🔒
✅ Extra Tip: If you’re building a modern app, also enable HTTP Strict Transport Security (HSTS), which tells browsers: “Always connect to me over HTTPS, forever!”
(You set it via HTTP header like Strict-Transport-Security.)
🔥 Final mini-cheat:
Concept
How
Encrypt transport
Use HTTPS (TLS)
Identity trust
Certificate from CA
Server-side config
Setup keystore, configure connector
Extra security
Use HSTS header
Posted inБез рубрики|Comments Off on Java.Servlet.How can we provide transport layer security for our web application?
Use Java EE security (declarative, via web.xml) — <security-constraint>.
Use Spring Security if you use Spring Boot / Spring MVC.
But for a simple servlet app, Filter is the cleanest and most flexible solution.
Method
When to use
Filter
Best for servlet apps, flexible control
web.xml<security-constraint>
OK but less flexible, older style
Spring Security
For Spring Boot / complex apps
Posted inБез рубрики|Comments Off on Java.Servlet.What is an effective way to ensure that all servlets are accessible only to a user with a valid session?