user3440622
user3440622

Reputation: 11

Bean Jsp String array connection

I have a String type of array in my java bean and i want to get it in my Java Server Page. But when i am using get property on my page it's giving me null. Can anybody suggest a solution for this?

Upvotes: 0

Views: 678

Answers (1)

Aamir Latif
Aamir Latif

Reputation: 56

I think you are trying to access bean property without setting its value through setter method. And a better method to access bean and its property is jsp expression language as shown in below example.

JSP Code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Names are : ${namesBean.names[0]} ${namesBean.names[1]}
</body>
</html>

If I access this jsp page directly from http://localhost:8080/sof/main.jsp url at this time namesBean is not initialized and out out will be

Names are :

And if I forward request to this jsp page through a servlet using http://12.0.0.1:8080/sof/SampleServlet where It is initialized namesBean then its value will be displayed on page.

Bean Code:

package sample;

public class SampleBean {

    public String[] names;

    public String[] getNames() {
        return names;
    }

    public void setNames(String[] names) {
        this.names = names;
    }
}

Servlet Code:

package sample;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SampleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SampleBean sampleBean = new SampleBean();
        sampleBean.setNames(new String[]{"Aamir", "Latif"});
        request.setAttribute("namesBean", sampleBean);
        RequestDispatcher rd = request.getRequestDispatcher("main.jsp");
        rd.forward(request, response);
    }
}

Servlet Mapping:

  <servlet>
    <description></description>
    <display-name>SampleServlet</display-name>
    <servlet-name>SampleServlet</servlet-name>
    <servlet-class>sample.SampleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SampleServlet</servlet-name>
    <url-pattern>/SampleServlet</url-pattern>
  </servlet-mapping>

Then output will be

Names are : Aamir Latif

One more better approach is to use JSTL

Upvotes: 1

Related Questions