Java.Servlets.How do I call another servlet from one servlet?

In Java servlets, if you want to call another servlet from within your current servlet, you have a few options depending on what exactly you mean by “call”:

1. Forward the request (internal call, no redirect visible to the client)

You can forward the current request to another servlet inside the same server using a RequestDispatcher.

RequestDispatcher dispatcher = request.getRequestDispatcher("/otherServlet");
dispatcher.forward(request, response);

The control is passed to otherServlet.

URL in browser stays the same (client doesn’t know).

Request and response objects are shared.

2. Include output from another servlet (embed response)

You can include another servlet’s output into your current response:

RequestDispatcher dispatcher = request.getRequestDispatcher("/otherServlet");
dispatcher.include(request, response);

The output of otherServlet is embedded in the response.

Useful if you want to combine responses (e.g., page fragments).

3. Send Redirect (external, client-visible redirect)

You can redirect the client to another servlet:

response.sendRedirect(request.getContextPath() + "/otherServlet");

Browser will make a new request to /otherServlet.

URL in browser changes.

Request and response are not shared anymore (new request).

Summary Table:

WayMethodControlBrowser URL Changes?Request/Response Shared?
ForwardRequestDispatcher.forward()Server-sideNoYes
IncludeRequestDispatcher.include()Server-sideNoYes
Redirectresponse.sendRedirect()Client-sideYesNo

Example:
Suppose you are in FirstServlet and want to call SecondServlet internally.

public class FirstServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // Some logic
        System.out.println("Before calling SecondServlet");

        RequestDispatcher dispatcher = request.getRequestDispatcher("/SecondServlet");
        dispatcher.forward(request, response);

        // Code here won't execute after forward!
        System.out.println("After calling SecondServlet"); // Will not run
    }
}
Posted in Без рубрики | Comments Off on Java.Servlets.How do I call another servlet from one servlet?

Java.Servlet.What is Request Dispatcher?

The RequestDispatcher is a Servlet API tool that lets you forward or include one web resource (like a servlet, JSP, or static file) from another servlet.

📦 What is RequestDispatcher?

It’s an interface in the javax.servlet package that allows one servlet to:

ActionDescription
ForwardTransfer the request to another resource on the server, without the client knowing.
IncludeInclude the output of another resource in the current response.
RequestDispatcher dispatcher = request.getRequestDispatcher("target.jsp");

Or via the ServletContext:

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/target.jsp");

🔁 Two Main Operations

1. Forward

Transfers control to another resource on the server, and terminates the current servlet.

request.getRequestDispatcher("/result.jsp").forward(request, response);
  • URL does not change in the browser
  • Request and response objects are shared
  • Control does not return to the original servlet

➡️ Use case: Pass control after processing form data, like login or registration

2. Include

Includes the output of another resource into the current response.

request.getRequestDispatcher("/footer.jsp").include(request, response);
  • Merges output
  • Used for layouts, header/footer, etc.
  • Original servlet keeps control

➡️ Use case: Composing pages with common headers/footers

🧪 Example: Forwarding to a JSP

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    String name = req.getParameter("name");
    req.setAttribute("user", name);  // pass data

    RequestDispatcher dispatcher = req.getRequestDispatcher("/welcome.jsp");
    dispatcher.forward(req, res); // internally transfer
}

In welcome.jsp:

<h1>Welcome, ${user}</h1>

🧠 RequestDispatcher vs Redirect

FeatureRequestDispatcher.forward()HttpServletResponse.sendRedirect()
TypeServer-sideClient-side
Browser URL changes?❌ No✅ Yes
Can share request data?✅ Yes (setAttribute)❌ No (requires session or params)
Control returns?❌ No (after forward)❌ No (new request entirely)
Use caseInternal workflowRedirecting user elsewhere (e.g., login)

✅ Summary

ConceptDescription
What is it?Interface to forward or include resources
Where to get it?request.getRequestDispatcher() or from context
Key methodsforward(), include()
Use casesLayouts, controller-to-view transitions
Posted in Без рубрики | Comments Off on Java.Servlet.What is Request Dispatcher?

Java.Servlets.What Is ServletRequest?

The ServletRequest interface is your main gateway to reading incoming data from a client (browser, mobile app, etc.) in a Java web application.

It lets you extract everything about the request — like parameters, headers, body, input streams, and metadata.

📦 What Is ServletRequest?

ServletRequest is an interface provided by the Servlet API:

javax.servlet.ServletRequest

It is used by the servlet container to pass client request data to your servlet.

✅ Responsibilities of ServletRequest

You Can Use It To…Example
Get query/form parametersgetParameter("username")
Read request body (e.g., POST data)getInputStream() or getReader()
Get client IP, hostnamegetRemoteAddr(), getRemoteHost()
Access request attributesgetAttribute(), setAttribute()
Get content length and encodinggetContentLength(), getCharacterEncoding()
Work with input streamsBinary or character reading of body
Detect protocol/port/server infogetProtocol(), getServerPort()

🔧 Common Methods in ServletRequest

MethodDescription
getParameter(String name)Get a form/query parameter value
getParameterMap()Get all parameters as a map
getInputStream()Read raw binary data from body
getReader()Read character stream (e.g., JSON payload)
getAttribute(String name)Get an attribute (used to pass data between filters)
setAttribute(String, Object)Set attribute (used in filters/forwarding)
getRemoteAddr()Get client IP address
getContentType()Get MIME type of incoming data
getContentLength()Get body length in bytes

🧪 Example: Read Form Parameters

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    String username = req.getParameter("username");
    String password = req.getParameter("password");

    res.getWriter().write("Username: " + username);
}

📤 ServletRequest vs HttpServletRequest

FeatureServletRequestHttpServletRequest
Protocol-agnostic✅ Yes❌ No (HTTP-specific only)
HTTP methods (GET/POST/etc.)❌ Not available✅ Yes
Header access❌ Not available✅ getHeader(), getCookies()
Session support❌ Not available✅ getSession()
Usage in HTTP apps✅ But usually cast to HttpServletRequest✅ Native support

So, while ServletRequest is useful, in HTTP apps you almost always work with its subclass HttpServletRequest, which gives you headers, sessions, cookies, methods, etc.

✅ Summary

FeatureDescription
What is it?Interface for reading incoming client data
Who provides it?Servlet container
When used?Passed into doGet(), doPost(), or filters
Works with…Parameters, attributes, body, encoding, etc.
Use HttpServletRequest for…HTTP-specific features like headers and sessions
Posted in Без рубрики | Comments Off on Java.Servlets.What Is ServletRequest?

Java.Servlet.What is the ServletResponse interface for?

The ServletResponse interface is used to build and send the response from a servlet back to the client (usually a browser or an HTTP client).

📦 What Is ServletResponse?

It’s a core part of the Servlet API:

javax.servlet.ServletResponse

It represents the output stream that the servlet uses to send:

  • HTML
  • JSON
  • Binary data (e.g. images, files)
  • Status codes
  • Headers

➡️ The servlet container creates a ServletResponse object for each request and passes it to your servlet’s service() / doGet() / doPost() method.

🧪 Basic Example: Writing HTML to Response

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<h1>Hello, Stanley!</h1>");
}

🧠 Key Responsibilities of ServletResponse

TaskMethod/Usage
Set content typesetContentType("text/html")
Set character encodingsetCharacterEncoding("UTF-8")
Get output stream for binarygetOutputStream()
Get writer for textgetWriter()
Set response buffer sizesetBufferSize(int size)
Control response bufferingflushBuffer(), resetBuffer()

⚡ Difference Between getWriter() and getOutputStream()

| Use getWriter() for… | Text (HTML, JSON, plain text) | | Use getOutputStream() for… | Binary data (images, PDFs, zip files) |

❗ You can use only one of these per response — not both.

✅ Typical Workflow in a Servlet

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    // Set status and headers
    res.setStatus(HttpServletResponse.SC_OK);
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");

    // Write JSON response
    PrintWriter out = res.getWriter();
    out.print("{\"message\": \"Data received\"}");
    out.flush();
}

✅ Summary

FeaturePurpose
What is it?Interface to build the response to send to the client
Who provides it?Servlet container
Common use?Write HTML, JSON, or binary data
Key methodsgetWriter(), setContentType(), getOutputStream()
Posted in Без рубрики | Comments Off on Java.Servlet.What is the ServletResponse interface for?

Java.Servlet.If i have 2 servlets, will i have 2 instances of ServletConfig ?

If you have two servlets, the servlet container will create two separate ServletConfig instances — one for each servlet.


🧠 Why?

Because ServletConfig is meant to hold configuration specific to one servlet, such as:

  • Init parameters defined in <servlet> tag or @WebServlet
  • The servlet’s name
  • A reference to the shared ServletContext

Each servlet can have its own initialization settings — so it needs its own ServletConfig object.

🔧 Example

web.xml

<servlet>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>com.app.LoginServlet</servlet-class>
  <init-param>
    <param-name>loginDb</param-name>
    <param-value>jdbc:mysql://login-db</param-value>
  </init-param>
</servlet>

<servlet>
  <servlet-name>AdminServlet</servlet-name>
  <servlet-class>com.app.AdminServlet</servlet-class>
  <init-param>
    <param-name>adminDb</param-name>
    <param-value>jdbc:mysql://admin-db</param-value>
  </init-param>
</servlet>

Servlets

public class LoginServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String db = config.getInitParameter("loginDb");
        System.out.println("LoginServlet using DB: " + db);
    }
}
public class AdminServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String db = config.getInitParameter("adminDb");
        System.out.println("AdminServlet using DB: " + db);
    }
}

✅ Each servlet gets its own ServletConfig instance, containing only its own init parameters.

🔁 What About ServletContext?

  • Only one ServletContext per web application
  • Shared among all servlets, filters, and listeners

✅ Summary

ConceptScopeOne per…
ServletConfigPer servlet✅ Yes
ServletContextPer web app❌ No (only one)
Posted in Без рубрики | Comments Off on Java.Servlet.If i have 2 servlets, will i have 2 instances of ServletConfig ?

Java.Servlet.What is the difference between ServletContext and ServletConfig?

Both ServletContext and ServletConfig are part of the Servlet API, but they serve different scopes and purposes. Let’s break them down side by side 👇

🧠 Core Difference

FeatureServletConfigServletContext
ScopeOne servlet onlyEntire web application
PurposePasses init parameters to a specific servletShares global configuration and resources
Data sharing❌ Not shared across servlets✅ Shared across all servlets and filters
Defined in<servlet> tag in web.xml or @WebServlet<context-param> tag in web.xml or via listener
Accessed viagetServletConfig()getServletContext()
LifecycleCreated per servletCreated once per application
Typical use caseRead servlet-specific config like db URLShare app-wide info like version, cache, shared objects

📄 Example: web.xml with Both

<context-param>
  <param-name>appVersion</param-name>
  <param-value>1.0.0</param-value>
</context-param>

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.myapp.MyServlet</servlet-class>
  <init-param>
    <param-name>dbUrl</param-name>
    <param-value>jdbc:mysql://localhost/mydb</param-value>
  </init-param>
</servlet>

🔧 Accessing Values in Servlet

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // From ServletConfig (specific to this servlet)
    String dbUrl = config.getInitParameter("dbUrl");

    // From ServletContext (shared by all servlets)
    String version = config.getServletContext().getInitParameter("appVersion");
}

Or in modern style (if you override init() without arguments):

String dbUrl = getServletConfig().getInitParameter("dbUrl");
String version = getServletContext().getInitParameter("appVersion");

🧪 ServletConfig vs ServletContext: Analogy

AnalogyServletConfigServletContext
👤 Per-employee dataTheir desk nameplateCompany-wide notice board
📦 Per-component configYour specific component’s configApp-level shared resources and settings

✅ Summary

Key PointServletConfigServletContext
For what?One specific servletEntire application
Shared?❌ No✅ Yes
Common usageRead servlet init parametersRead global parameters or share data
Who creates it?Container (one per servlet)Container (one per app)
Posted in Без рубрики | Comments Off on Java.Servlet.What is the difference between ServletContext and ServletConfig?

Java.Servlets.What is ServletContext?

If ServletConfig is like a servlet’s private config, then ServletContext is like a global shared workspace for the entire web application.

🌍 What Is ServletContext?

ServletContext is an object provided by the servlet container that:

✅ Represents the web application’s runtime environment and
✅ Provides a way for all servlets to share information and resources

📦 Key Use Cases of ServletContext:

Use CaseExample
Sharing data between servletsStore an object globally with setAttribute()
Reading global configGet app-level parameters from web.xml
Accessing resourcesLoad files with getResource() or getRealPath()
LoggingWrite to server logs via log()
Getting environment detailsServer info, context path, MIME types, etc.

🧪 Example: Sharing Data Between Servlets

Servlet A — set attribute:

@Override
public void init() {
    getServletContext().setAttribute("appStartTime", System.currentTimeMillis());
}

Servlet B — get attribute:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    Long startTime = (Long) getServletContext().getAttribute("appStartTime");
    res.getWriter().write("App started at: " + startTime);
}

✅ Works across all servlets in the same app.

📄 web.xml – Global Init Parameters

<context-param>
    <param-name>globalSetting</param-name>
    <param-value>enabled</param-value>
</context-param>

Servlet:

String value = getServletContext().getInitParameter("globalSetting");

🔧 Useful Methods in ServletContext

MethodPurpose
getInitParameter(String)Get app-wide init param from web.xml
getAttribute(String)Get a shared app-wide attribute
setAttribute(String, Object)Set a shared app-wide attribute
removeAttribute(String)Remove an attribute
getRealPath(String)Get physical path on the server
getResource(String)Get resource as URL
getMimeType(String)Get MIME type based on file extension
getContextPath()Get the web app’s context root (like /myapp)
log(String)Write to server log

🧠 ServletContext vs ServletConfig

FeatureServletConfigServletContext
ScopePer servletEntire web app
Data SharingNot sharedShared between all servlets
Defined in<servlet><context-param>
PurposeServlet-specific configApp-level config & resource sharing
AccessgetServletConfig()getServletContext()

🧩 Real Use Case Example

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    ctx.setAttribute("appStartTime", Instant.now());
}

This is from a ServletContextListener — perfect for setting shared values at startup.

✅ Summary

ConceptDescription
What is it?A global config and data-sharing object for the entire app
Provided byServlet container
Shared?Yes — among all servlets, filters, listeners
Typical UsesConfig, file access, logging, data sharing
Access viagetServletContext() in servlet or ServletContextListener
Posted in Без рубрики | Comments Off on Java.Servlets.What is ServletContext?

Java.Servlet.What is ServletConfig?

ServletConfig is a special interface in the Servlet API that allows the servlet container to pass configuration information to a servlet at initialization time.

You can think of it as the servlet’s own private config object, defined in web.xml (or annotation-based equivalent).

📦 What is ServletConfig?

  • Part of javax.servlet
  • Passed to the servlet by the container when calling init(ServletConfig config)
  • Contains:
    • Init parameters (name-value pairs defined in web.xml)
    • Servlet name
    • Reference to the ServletContext

🧪 Example Use Case

📄 In web.xml:

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.myapp.MyServlet</servlet-class>
  <init-param>
    <param-name>dbUrl</param-name>
    <param-value>jdbc:mysql://localhost:3306/mydb</param-value>
  </init-param>
</servlet>

🧑‍💻 In Servlet:

public class MyServlet extends HttpServlet {
    private String dbUrl;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config); // Important to call this!
        dbUrl = config.getInitParameter("dbUrl");
        System.out.println("Database URL: " + dbUrl);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.getWriter().write("Using DB URL: " + dbUrl);
    }
}

You can also get it via getServletConfig() inside init() or doGet() if you’ve overridden the no-arg init() instead.

✅ Key Methods in ServletConfig

MethodDescription
getInitParameter(String name)Get a single init param
getInitParameterNames()Get all param names
getServletName()Get the name of the servlet
getServletContext()Get reference to global ServletContext

🔁 ServletConfig vs ServletContext

FeatureServletConfigServletContext
ScopePer servletEntire web application
PurposeConfig for a single servletShared app-wide data & context
Defined in<servlet> tag<context-param> tag
Access from servletgetServletConfig()getServletContext()

✅ Summary

FeatureDescription
What is it?Config object passed to servlet during initialization
Where defined?In web.xml or annotations (@WebServlet, etc.)
PurposeProvide servlet-specific init parameters
Access how?init(ServletConfig config) or getServletConfig()
Difference from contextOnly for this servlet; not shared like ServletContext
Posted in Без рубрики | Comments Off on Java.Servlet.What is ServletConfig?

Java.Servlet.How to handle exceptions thrown by another servlet in an application?

Handling exceptions thrown by other servlets is crucial for building robust, user-friendly web applications.

There are multiple ways to handle exceptions in a Java servlet-based application, and it all depends on how centralized and graceful you want the handling to be.

✅ 1. Handle Exceptions with web.xml – Centralized Error Pages

The classic and cleanest way is to configure exception handling in web.xml.

📄 Example:

<error-page>
    <exception-type>java.lang.NullPointerException</exception-type>
    <location>/error.jsp</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/notfound.jsp</location>
</error-page>

🔧 What This Does:

  • If any servlet in your app throws a NullPointerException, the container forwards the user to /error.jsp.
  • If a 404 error (resource not found) occurs, user is redirected to /notfound.jsp.

You can use these placeholders in JSP pages:

<%= exception %>  <!-- To show the actual exception -->

✅ 2. Handle Exceptions in the Servlet Itself

You can always use try-catch in individual servlets:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {
        // risky code
    } catch (Exception e) {
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        res.getWriter().write("Oops! Something went wrong.");
    }
}

✔️ Good for specific or critical operations
✖️ But clutters the servlet and doesn’t centralize error handling

✅ 3. Use a Filter for Global Exception Handling

If you want to catch exceptions from any servlet globally, create a Filter:

@WebFilter("/*")
public class ExceptionHandlerFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Throwable e) {
            HttpServletResponse res = (HttpServletResponse) response;
            res.setStatus(500);
            res.getWriter().write("Global Error Handler: " + e.getMessage());
        }
    }
}

✔️ Great for catching unexpected exceptions across the whole app
✔️ Centralized error logging
✖️ Not ideal for handling specific exception types differently

✅ 4. Custom Error Servlet

You can map exceptions to a dedicated servlet instead of a JSP:

<error-page>
    <exception-type>java.lang.ArithmeticException</exception-type>
    <location>/ErrorHandler</location>
</error-page>

🧠 In your ErrorHandler servlet:

public class ErrorHandler extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        res.getWriter().write("Exception: " + throwable);
    }
}

🧠 Summary Table

MethodScopeUse When…
web.xml <error-page>Application-wideYou want clean and declarative error pages
try-catch in servletServlet-specificYou want tight control over a risky block
Global Filter with try-catchEntire appYou want global error logging or fallback
Error handling servletApp-wide, customizableYou want structured error recovery
Posted in Без рубрики | Comments Off on Java.Servlet.How to handle exceptions thrown by another servlet in an application?

Java.Servlet.What is 1 in loadOnStartup = 1 ?

The 1 in loadOnStartup = 1 (or <load-on-startup>1</load-on-startup>) is an integer priority that tells the servlet container:

👉 “Load this servlet when the application starts — and do it in this order relative to other servlets.”

🔢 What Does the Number Mean?

✅ Non-negative Integer (0, 1, 2, etc.)

  • Tells the container to load the servlet eagerly, at application startup.
  • Lower numbers load first.
  • Multiple servlets? Order of loading is based on ascending numbers.
ValueEffect
0Load immediately (high priority)
1Load after 0
5Load later

So if you have:

<load-on-startup>1</load-on-startup>  // InitServlet
<load-on-startup>2</load-on-startup>  // MetricsServlet

Then InitServlet is initialized before MetricsServlet.

❌ Negative or Absent Value

  • Servlet is loaded lazily — only when it receives its first request.
  • This is the default behavior if load-on-startup is not specified.

🚀 Use Cases for loadOnStartup

ScenarioWhy Set Priority?
DB connection pool initializationEnsure DB is ready before user requests
Logging system bootstrappingStart logs early
Caching dataPreload and warm up cache
Background schedulersStart worker threads early

✅ Example with Annotation

@WebServlet(urlPatterns = "/init", loadOnStartup = 1)
public class InitServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("🚀 InitServlet started at app startup!");
    }
}

Posted in Без рубрики | Comments Off on Java.Servlet.What is 1 in loadOnStartup = 1 ?