Java.Servlet.What is a JavaBean?

A JavaBean is just a regular Java class that:

  1. Has a public no-argument constructor (so the server can create it easily).
  2. Has private fields (data) with public getter and setter methods.
  3. Implements Serializable interface (optional, but often recommended for distributed apps).

✅ It’s like a data holder: it stores information and allows you to get/set it cleanly.


🎯 Example of a JavaBean

package com.example;

public class User {
    private String name;
    private int age;

    // Public no-argument constructor
    public User() {}

    // Getter and Setter for name
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // Getter and Setter for age
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

name and age are private fields.

getName(), setName(), getAge(), setAge() are public access methods.

📜 How JavaBeans are used in JSP?

Using action tags, you can create a bean, set properties, and get properties without writing Java code manually.

Example JSP:

<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="Stanley" />
<jsp:setProperty name="user" property="age" value="30" />

<p>Hello, <jsp:getProperty name="user" property="name" />!</p>
<p>You are <jsp:getProperty name="user" property="age" /> years old.</p>

What happens here:

  • useBean creates a new User object and stores it in the session.
  • setProperty sets the name and age.
  • getProperty reads them and outputs into the page.

Result:

Hello, Stanley!
You are 30 years old.

📢 Important points about JavaBeans:

  • They are not enterprise-level EJBs (Enterprise JavaBeans).
    ➔ JavaBeans are simple, lightweight classes for holding data.
  • JSPs use JavaBeans to bind form fields to backend objects easily.
  • JavaBeans help separate business logic (Java code) from presentation (JSP HTML).

🎯 In short:

When I said “beans” earlier, I meant simple Java objects (JavaBeans) that are easy to create, set, and read inside JSP using special action tags.

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

Java.Servlet.What variable scopes exist in JSP?

In JSP, variable scopes define where and how long a variable (object) is available during the lifecycle of a web application.

There are four variable scopes in JSP:

ScopeObject AvailabilityLifetime
pageAvailable only in the current pageUntil the page finishes processing
requestAvailable for the current HTTP requestUntil the request is completed (forwarded or responded)
sessionAvailable for the current user sessionUntil the session times out or is invalidated
applicationAvailable for all users, all sessionsUntil the server shuts down or app is undeployed

🔵 1. page Scope

  • Visible only in the current JSP page.
  • Not shared across requests or other pages.

Example:

<jsp:useBean id="user" class="com.example.User" scope="page" />

user exists only while this JSP page is executing.

After the response is sent, it disappears.

🔵 2. request Scope

  • Shared across the entire request, including forwards and includes.
  • Used to pass data between servlets, filters, and JSPs.

Example:

<jsp:useBean id="user" class="com.example.User" scope="request" />

If you forward the request to another page, it can still access user.

🔵 3. session Scope

  • Persists across multiple requests from the same user/browser session.
  • Good for storing user login data, shopping carts, etc.

Example:

<jsp:useBean id="user" class="com.example.User" scope="session" />

user stays available until the session expires (usually after inactivity).

🔵 4. application Scope

  • Global scope — available to all users and sessions within the web application.
  • Useful for application-wide settings, counters, shared resources.

Example:

<jsp:useBean id="config" class="com.example.Config" scope="application" />

config is visible everywhere in the app until the server restarts or app is undeployed.

📚 Summary Table

ScopeObject tied toAccessed fromLifetime
pageCurrent JSP pageOnly the current pageUntil page response completes
requestHTTP Request objectForwarded/Included pages tooUntil request completes
sessionUser’s Session objectAll pages in sessionUntil session timeout
applicationApplication ContextAll pages and all usersUntil server shutdown

📢 How They Relate to Java Objects

In Java code inside JSPs, you access them using:

  • pageContext → for page scope
  • request → for request scope
  • session → for session scope
  • application → for application scope

Example in JSP:

<%= session.getAttribute("user") %>
<%= request.getAttribute("orderId") %>
<%= application.getAttribute("config") %>

🎯 Final Key Points:

  • Use page for local temporary data.
  • Use request for passing data between pages.
  • Use session for user-specific long-term data.
  • Use application for global shared data.
Posted in Без рубрики | Comments Off on Java.Servlet.What variable scopes exist in JSP?

Java.Servlet.What do you know about JSP actions (Action tag and JSP Action Elements).JSP – servlet – JSP interaction.

JSP Actions (also called JSP Action Tags or JSP Action Elements) are special XML-like tags that perform predefined tasks when a JSP page is processed.

They are part of the JSP specification itself (not user-defined or third-party) and are executed on the server-side during page request handling.

🎯 Purpose of JSP Actions:

  • Encapsulate functionality (like including other resources, forwarding requests, working with JavaBeans) without writing Java code manually.
  • Simplify interaction with backend logic.
  • Promote reuse and cleaner JSP code.
  • Help JSP remain more declarative (tag-based) rather than imperative (Java code blocks).

🔥 Syntax of Action Tags

<jsp:actionName attribute="value" />

They look like XML elements: start with <jsp:, followed by the action name.

They must be properly closed (either self-closing or with explicit end tag).

🔵 Common JSP Action Elements

Action TagPurpose
<jsp:useBean>Locate or instantiate a JavaBean
<jsp:setProperty>Set a property value on a bean
<jsp:getProperty>Get a property value from a bean
<jsp:include>Dynamically include another resource
<jsp:forward>Forward request to another resource
<jsp:param>Add parameters to include or forward
<jsp:plugin>Download and run a Java plugin (like Applet)

🔥 Short Examples for Each:

1. <jsp:useBean>

Create or find a JavaBean instance.

<jsp:useBean id="user" class="com.example.User" scope="session" />
  • If no user exists in session, create it.

2. <jsp:setProperty>

Set property values inside a JavaBean.

<jsp:setProperty name="user" property="name" value="Stanley" />

Sets user.setName("Stanley");

You can also populate properties automatically from request parameters:

<jsp:setProperty name="user" property="*" />

➔ Sets all matching properties.

3. <jsp:getProperty>

Retrieve property values from a bean.

<p>Welcome, <jsp:getProperty name="user" property="name" />!</p>

Output: Welcome, Stanley!

4. <jsp:include>

Include another file at request time (dynamic inclusion).

<jsp:include page="footer.jsp" />
  • Runs footer.jsp and inserts its output here.

You can also pass parameters:

<jsp:include page="header.jsp">
    <jsp:param name="title" value="Home Page" />
</jsp:include>

5. <jsp:forward>

Forward request internally to another resource.

<jsp:forward page="login.jsp" />
  • Stops further processing and sends request to login.jsp.

You can also pass parameters similarly with <jsp:param>.

6. <jsp:plugin>

Embed Java applets or JavaBeans dynamically.

<jsp:plugin type="applet" code="MyApplet.class" width="300" height="300">
    <jsp:params>
        <jsp:param name="color" value="blue" />
    </jsp:params>
</jsp:plugin>

(Not very common anymore — applets are obsolete today.)

📌 Important points about Action Tags:

  • They are server-side only: the browser never sees them.
  • They provide a declarative, tag-based alternative to embedding Java code (<% %>).
  • Some actions, like <jsp:include>, happen at runtime (not at translation time).

🛠️ Why are Action Tags Important?

  • Cleaner and more readable JSPs (instead of mixing lots of Java code).
  • Help integrate JavaBeans with the UI layer easily.
  • Make JSPs easier to maintain and extend.
  • Support separation of concerns: JSPs handle presentation; JavaBeans handle business data.

🎯 Final Recap:

AspectDescription
What are they?Built-in JSP tags for predefined tasks
Look like?XML-style, <jsp:actionName>
Why use them?Cleaner, more modular, server-side dynamic behavior
Posted in Без рубрики | Comments Off on Java.Servlet.What do you know about JSP actions (Action tag and JSP Action Elements).JSP – servlet – JSP interaction.

Java.Servlet.What are the main types of JSP tags?

📜 1. Directive Tags

  • Used to give instructions to the JSP engine at translation time (before the page is turned into a servlet).
  • They control things like page settings, imports, and file inclusion.

Syntax:

<%@ directive attribute="value" %>

Examples:

  • <%@ page language="java" contentType="text/html" %> → Page settings
  • <%@ include file="header.jsp" %> → Static include
  • <%@ taglib uri="..." prefix="..." %> → Use custom tag libraries (JSTL, etc.)

📜 2. Scripting Tags

  • Allow you to embed Java code directly inside the JSP page.
  • (Not recommended for large applications — better to use JSTL or EL.)

Types of scripting tags:

Types of scripting tags:

TypeSyntaxPurpose
Declarations<%! Java code %>Declare variables or methods
Scriptlets<% Java code %>Write Java code blocks
Expressions<%= Java expression %>Output a Java value directly

Example:

<%! int counter = 0; %>          <!-- Declaration -->
<% counter++; %>                 <!-- Scriptlet -->
<p>Counter: <%= counter %></p>   <!-- Expression -->

📜 3. Action Tags

  • Special tags that interact with JavaBeans, forward requests, include content, and reuse components.
  • Handled by the JSP engine.

Syntax:

<jsp:actionName attribute="value" />

Examples:

  • <jsp:useBean> → Create or find a JavaBean
  • <jsp:setProperty> → Set bean property
  • <jsp:getProperty> → Get bean property
  • <jsp:include> → Include another resource at runtime
  • <jsp:forward> → Forward the request to another page

📜 4. Standard Tag Libraries (JSTL)

  • A set of ready-to-use tags for common tasks like:
    • Conditions (<c:if>)
    • Loops (<c:forEach>)
    • Formatting
    • SQL database access
  • Removes the need to write Java code inside JSP pages.
  • Cleaner, easier, safer!

Example using JSTL:

<c:if test="${user != null}">
    <p>Welcome, ${user.name}!</p>
</c:if>

Here ${user.name} is evaluated using EL (Expression Language).

📜 5. Custom Tags

  • You can define your own tags with special behavior.
  • Usually used in large projects to avoid repetitive code.
  • Created using:
    • Java classes implementing SimpleTagSupport or TagSupport
    • Defined in a .tld (Tag Library Descriptor) file or via annotations.

Example of usage:

<mytags:showDate />

where mytags is a custom tag library you define.

🎯 Final Summary:

Tag TypeMain Use
Directive TagsGive instructions to the JSP container
Scripting TagsEmbed Java code inside HTML
Action TagsWork with JavaBeans, include, forward
Standard Tag Libraries (JSTL)Common operations like loops, conditions
Custom TagsDefine reusable custom behavior
Posted in Без рубрики | Comments Off on Java.Servlet.What are the main types of JSP tags?

Java.Servlet.How to comment out code in JSP?

In JSP, there are three types of comments, depending on what exactly you want:


📝 1. HTML Comments

<!-- This is an HTML comment -->

It will appear in the browser’s page source (users can see it if they view source).

Used to explain client-side code (HTML, CSS).

🛡️ 2. JSP Comments

<%-- This is a JSP comment --%>
  • It is completely removed during JSP translation (server-side).
  • Browser will never see this comment — it stays only on the server.
  • Used to hide server-side Java code, instructions, or disable code temporarily.

✅ Best way to comment out Java or dynamic code in JSP.

Example:

<%-- 
    <% String username = request.getParameter("username"); %> 
    <%= username %> 
--%>

Neither the Java code nor the output will be included in the HTML response.

⚙️ 3. Java Comments inside Scriptlets

If you’re inside a Java block (<% %>), you can use normal Java comments:

  • Single-line Java comment:
<%
    // This is a single-line Java comment
    int counter = 0;
%>

Multi-line Java comment:

<%
    /* This is
       a multi-line
       Java comment */
    int counter = 0;
%>

📜 Quick Table:

Comment TypeSyntaxVisible in Browser?Purpose
HTML Comment<!-- comment -->✅ YesClient-side notes
JSP Comment<%-- comment --%>❌ NoServer-side notes
Java Comment// or /* */ inside <% %>❌ NoComment inside Java code block

🎯 Summary

  • Use <!-- ... --> for HTML comments.
  • Use <%-- ... --%> for server-side JSP comments (best for hiding logic from browser).
  • Use // or /* */ when writing inside <% %> scriptlet blocks.
Posted in Без рубрики | Comments Off on Java.Servlet.How to comment out code in JSP?

Java.Servlet.What is the difference between dynamic and static JSP content?

📜 Static vs Dynamic Content in JSP

AspectStatic ContentDynamic Content
DefinitionContent that does not change for each user or request.Content that can change depending on request parameters, user input, or backend logic.
Written asPlain HTML, CSS, JavaScript inside the JSP page.Embedded Java code, expressions, or custom tags inside the JSP page.
ProcessingDirectly copied into the servlet’s output (out.write()).Evaluated at runtime, and result is inserted into the output.
PerformanceVery fast — no calculation needed.Slightly slower — because server has to execute Java code first.
Example<h1>Welcome to our website</h1><h1>Welcome, <%= user.getName() %>!</h1>

🔥 Examples

Static Content Example:

<html>
  <body>
    <h1>Welcome to our website</h1> <!-- Static: same for every visitor -->
  </body>
</html>

This HTML will be the same for everyone.

Server just copies it into the HTTP response.

Dynamic Content Example:

<html>
  <body>
    <h1>Welcome, <%= request.getParameter("username") %>!</h1> <!-- Dynamic -->
  </body>
</html>

If a user accesses hello.jsp?username=Stanley, they will see:

Welcome, Stanley!

If another user accesses hello.jsp?username=Marina, they will see:

Welcome, Marina!

Here, <%= request.getParameter("username") %> is evaluated during request processing.

⚙️ How They Are Handled Internally:

When the server translates a JSP into a servlet:

  • Static content becomes simple out.write("...") Java statements.
  • Dynamic content becomes actual Java code execution inside the _jspService() method.

Example for Static:

out.write("<h1>Welcome to our website</h1>");

Example for Dynamic:

out.write("<h1>Welcome, " + request.getParameter("username") + "!</h1>");

🎯 Final Summary:

  • Static content: Always the same, copied directly into response.
  • Dynamic content: Depends on request or server-side calculations, generated at runtime.

Both coexist in a typical JSP file to create web pages that are partly constant and partly personalized.

Posted in Без рубрики | Comments Off on Java.Servlet.What is the difference between dynamic and static JSP content?

Java.Servlet.How can we prevent direct access to a JSP page from a browser?

Excellent and very practical question!
There are several ways to prevent users from directly accessing a JSP page from a browser.

Here’s a structured explanation:


🔥 1. Place JSPs under WEB-INF/ Folder

  • Files inside WEB-INF cannot be accessed directly via a URL.
  • Only servlets or controllers can forward a request to them internally.

📂 Folder structure:

/webapp
   ├── WEB-INF
   │     ├── jsp
   │          ├── secretPage.jsp
   └── index.jsp

If you put your secretPage.jsp inside /WEB-INF/jsp/, then:

  • URL like http://example.com/WEB-INF/jsp/secretPage.jsp → ❌ Access Denied (HTTP 404)
  • But from a Servlet:
request.getRequestDispatcher("/WEB-INF/jsp/secretPage.jsp").forward(request, response);

→ ✅ Allowed

✅ Best and most common practice in real projects!

🔥 2. Use Servlet Authentication (Filter or Security Constraint)

  • Create a Filter that checks every request.
  • If someone tries to access a protected JSP without proper login/session, redirect them or block the access.

Example Filter:

@WebFilter("/secure/*")
public class AuthenticationFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(false);
        
        if (session == null || session.getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect("/login.jsp");
        } else {
            chain.doFilter(request, response); // User is logged in
        }
    }
}

Only authenticated users can access /secure/* JSPs.

🔥 3. Use <security-constraint> in web.xml

You can define URL patterns that require authentication.

Example:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Protected Pages</web-resource-name>
        <url-pattern>/secure/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>authenticatedUser</role-name>
    </auth-constraint>
</security-constraint>

This way the server will block direct access unless users are authenticated and have the correct role.

🔥 4. Programmatic Check Inside JSP (not recommended)

You could manually add Java code at the top of your JSP:

<%
    if (session.getAttribute("user") == null) {
        response.sendRedirect("login.jsp");
    }
%>

❗ But this is ugly, mixes Java with HTML, and harder to maintain.
Better to handle security in filters or servlets.

📢 In professional projects, the best way is:

➔ Put JSPs inside WEB-INF/
➔ Control access via servlets + filters.

That way, JSPs are treated only as view templates, not as web-accessible resources.

Posted in Без рубрики | Comments Off on Java.Servlet.How can we prevent direct access to a JSP page from a browser?

Java.Servlet.Which JSP life cycle methods can be overridden?

✨ JSP life cycle methods that you can override:

MethodCan Override?Purpose
jspInit()✅ YesFor initialization tasks (e.g., setting up resources)
jspDestroy()✅ YesFor cleanup tasks (e.g., closing connections)

✅ You can override jspInit() and jspDestroy() by defining them in your JSP file using declaration tags <%! ... %>, like this:

Example:

<%! 
public void jspInit() {
    // Initialization code here
}

public void jspDestroy() {
    // Cleanup code here
}
%>

🚫 JSP life cycle method that you cannot override:

MethodCan Override?Purpose
_jspService()❌ NoIt is generated automatically to handle each request
  • _jspService(HttpServletRequest, HttpServletResponse) is generated by the JSP engine based on your JSP content (HTML + Java code).
  • You cannot write or override it yourself — it’s part of the server-generated servlet class.

Instead, you control what happens during request processing by simply writing scriptlets, JSP expressions, or using tags inside the JSP file.


📢 Final Short Answer:

  • ✅ jspInit() → Overridable
  • ✅ jspDestroy() → Overridable
  • ❌ _jspService() → Not overridable
Posted in Без рубрики | Comments Off on Java.Servlet.Which JSP life cycle methods can be overridden?

Java.Servlet.Explain the methods of the JSP life cycle.

Of course!
In the JSP life cycle, several key methods are automatically called by the server at different stages.
These methods come either from the servlet API (because JSPs become servlets) or from special JSP interfaces.

Here are the main methods involved:


🔵 1. jspInit()

  • Called once when the JSP servlet is first loaded into memory.
  • It’s similar to the init() method in regular servlets.
  • You can override jspInit() to perform initialization tasks, like:
    • Creating database connections
    • Initializing resources
    • Loading configuration files
public void jspInit() {
    // Initialization code here
}

🔵 2. _jspService(HttpServletRequest request, HttpServletResponse response)

  • Called for every client request.
  • This method handles the main logic: processing the request and generating the response.
  • You cannot override _jspService() manually — it is generated automatically by the server during JSP translation.
  • Inside _jspService(), the server processes:
    • HTML template
    • Embedded Java code (<% %>)
    • JSP tags
public void _jspService(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Code to generate dynamic content
}

🔵 3. jspDestroy()

  • Called once when the JSP servlet is about to be unloaded (e.g., server shutdown, app redeploy).
  • It’s similar to the destroy() method in regular servlets.
  • You override jspDestroy() to release resources, like:
    • Closing database connections
    • Stopping background threads
public void jspDestroy() {
    // Cleanup code here
}

📜 Full Summary:

MethodWhen It Is CalledPurpose
jspInit()Once when JSP is loadedInitialization (e.g., opening resources)
_jspService()For each client requestHandle request, generate dynamic output
jspDestroy()Once when JSP is unloaded or server stopsCleanup (e.g., closing resources)

📌 Extra Technical Detail

  • JSPs implement the javax.servlet.jsp.JspPage interface, which defines jspInit() and jspDestroy().
  • The JSP engine generates a servlet class extending HttpJspBase, which internally connects to HttpServlet.
  • _jspService() is generated from your JSP file’s HTML + Java code.

🎯 Quick analogy:

Servlet MethodJSP Method Equivalent
init()jspInit()
service()_jspService()
destroy()jspDestroy()
Posted in Без рубрики | Comments Off on Java.Servlet.Explain the methods of the JSP life cycle.

Java.Servlet.Explain the stages (phases) of the JSP life cycle.

Sure!
The JSP life cycle describes the stages a JSP page goes through inside the server, from its creation to serving requests and eventually being destroyed.

There are 5 main phases:


🚀 1. Translation Phase

  • The server translates the JSP file into a Java servlet source file (.java).
  • Example: hello.jsp → hello_jsp.java
  • This happens only once, unless the JSP file is modified.

🛠️ 2. Compilation Phase

  • The generated .java file is compiled into a servlet class (.class).
  • Example: hello_jsp.class
  • If compilation fails, the server returns an error to the client.

🧠 3. Initialization Phase

  • After successful compilation, the servlet container:
    • Loads the servlet class into memory.
    • Creates an instance of the servlet.
    • Calls the servlet’s init() method once.
  • Purpose: Set up any resources (e.g., database connections) needed during execution.

🔄 4. Request Processing (Execution) Phase

  • For each client request:
    • The container calls the servlet’s service() method.
    • This internally calls doGet(), doPost(), etc., based on HTTP method.
  • JSP embedded Java code executes.
  • The servlet generates dynamic content (HTML, XML, JSON) and sends it back to the client.

🛑 5. Destruction Phase

  • When the server shuts down or unloads the servlet (e.g., for memory management or application redeployment):
    • It calls the destroy() method of the servlet instance.
  • Purpose: Release resources, close database connections, cleanup.

📜 Quick Summary Table

PhaseDescription
TranslationJSP → Java Servlet source code
CompilationJava Servlet source → Servlet class file
InitializationServlet instance is created and initialized (init())
ExecutionRequest handled (service(), doGet(), doPost())
DestructionServlet instance destroyed (destroy())

📌 Important Notes:

  • Translation and Compilation happen only once, unless the JSP is updated.
  • Execution happens for every request.
  • Destruction happens once when the servlet is taken out of service.
Posted in Без рубрики | Comments Off on Java.Servlet.Explain the stages (phases) of the JSP life cycle.