Important JSP Action Tags with examples

Important JSP Action Tags with examples

JSP Action tags are special tags that provide functionality to interact with JavaBeans, forward requests to other resources, include content from other resources, and more. They enable the dynamic behavior of web pages by encapsulating reusable functionality.

Some important JSP Action tags include:

  • <jsp:include> Dynamically includes the content of another resource (e.g., a JSP file) at request time.
  • <jsp:forward> Forwards the request to another resource (e.g., a JSP file, servlet).
  • <jsp:param>   Adds parameters to include or forward actions.
  • <jsp:useBean>  Instantiates or locates a JavaBean.
  • <jsp:setProperty>  Sets the properties of a JavaBean.
  • <jsp:getProperty>   Gets the properties of a JavaBean.

Important JSP Action Tags with examples

Example
1. <jsp:include>

Includes the content of another resource at request time.

 main.jsp: 
jsp
<html>
<body>
    <h1>Main Content</h1>
    <jsp:include page="header.jsp" />
    <jsp:include page="footer.jsp" />
</body>
</html>


 header.jsp: 
jsp
<h1>This is the header</h1>


 footer.jsp: 
jsp
<h1>This is the footer</h1>

Example
2. <jsp:forward>
Forwards the request to another resource.

 main.jsp: 
jsp
<jsp:forward page="target.jsp" />


 target.jsp: 
jsp
<html>
<body>
    <h1>Target Page</h1>
</body>
</html>

Example
3. <jsp:param>
Adds parameters to include or forward actions.

 main.jsp: 
jsp
<jsp:include page="display.jsp">
    <jsp:param name="username" value="JohnDoe" />
</jsp:include>


 display.jsp: 
jsp
<html>
<body>
    <h1>Welcome, <%= request.getParameter("username") %></h1>
</body>
</html>

Example
. <jsp:useBean>
Instantiates or locates a JavaBean.

 User.java: 
java
package com.example;

public class User {
    private String name;

    public String getName() {
        return name;
    }

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


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

<html>
<body>
    <h1>User Name: <jsp:getProperty name="user" property="name" /></h1>
</body>
</html>

Explanation

1.  <jsp:include>:

   Dynamically includes header.jsp and footer.jsp into main.jsp.

2.  <jsp:forward>:

   Forwards the request from main.jsp to target.jsp.

3.  <jsp:param>:

   Adds a parameter username with the value JohnDoe to the included display.jsp.

4.  <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>:

   Instantiates a User bean, sets its name property to JohnDoe, and then retrieves and displays the name property.

Homepage

Readmore