1

Here I come up with a problem like to pass value between servlet to jsp by set attribute and get attribute i have created servlet page and set value in servlet now how can i iterate all value in jsp by get attribute.am newbie could some one guide correct my code it useful to learn from u all

its all working fine but while i click of update and delete link it showing error like this

Controllertest.java:

   package Controller;
    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;

    import dao.UserDao;
    import dbBean.UseBean;

    public class ControllerTest extends HttpServlet
    {
        private static final long serialVersionUID = 1L;
        private static String INSERT_OR_EDIT = "/user.jsp";
        private static String LIST_USER = "/listUser.jsp";

        private UserDao dao;

        public ControllerTest()
        {
            super();
            dao = new UserDao();

        }

        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException
        {

            String forward = "";
            String action = request.getParameter("action");
            if (action.equalsIgnoreCase("delete"))
            {

                int userId = Integer.parseInt(request.getParameter("userId"));
                dao.deleteUser(userId);
                forward = LIST_USER;
                request.setAttribute("users", dao.getAllUsers());

            }
            else if (action.equalsIgnoreCase("edit"))
            {
                forward = INSERT_OR_EDIT;
                int userId = Integer.parseInt(request.getParameter("userId"));
                UseBean bean = dao.getUserById(userId);
                request.setAttribute("user", bean);

            }
            else if (action.equalsIgnoreCase("listUser"))
            {
                forward = LIST_USER;
                request.setAttribute("users", dao.getAllUsers());
            }
            else
            {
                forward = INSERT_OR_EDIT;
            }
            RequestDispatcher view = request.getRequestDispatcher(forward);
            view.forward(request, response);

        }

        protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
        {


                UseBean bean = new UseBean();
                bean.setName(request.getParameter("Name"));
                bean.setPassword(request.getParameter("password"));
                bean.setPhoneo(request.getParameter("Phoneo"));
                bean.setEmailID(request.getParameter("Emailid"));
                String userid = request.getParameter("ID");
                if (userid == null || userid.isEmpty())
                {
                    dao.addUser(bean);
                } 
                else
                {
                    bean.setID(Integer.parseInt(userid));
                    dao.updateUser(bean);
                }
                RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
                request.setAttribute("users", dao.getAllUsers());
                view.forward(request, response);

        }
    }

user.jsp

<form method="POST" action='ControllerTest' name="frmAddUser">

  <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
        <% for(int i = 0; i < users.size(); i+=1) 
        { 
            UseBean user = (UseBean)users.get(i);
        %>

        id:<input type="text" name="ID" value="<%=user.getID() %>"><br/>
        Name:<input type="text" name="Name" value="<%= user.getName() %>"><br/>
        Password:<input type="text" name="password" value="<%= user.getPassword() %>"><br/>
        phoneno:<input type="text" name="Phoneo" value="<%= user.getPhoneo() %>"><br/>
        Emailid:<input type="text" name="Emailid" value="<%= user.getEmailID() %>">  <br/> 

        <%} %>
         <input type="submit" value="Submit" />
    </form>

listuser.jsp

 <%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@page import="java.util.*,Controller.*,dbBean.*,Dbconnect.*"%>
<!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=EUC-KR">
<title>Show All Users</title>
</head>
<body>
    <table border=1>
    <thead>
        <tr>
        <th>Id</th>
        <th>Name</th>
        <th>password</th>
        <th>phoneno</th>
        <th>emailid</th>
        <th colspan=2>Action</th>
        </tr>
    </thead>
    <tbody>
        <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
        <% for(int i = 0; i < users.size(); i+=1) 
        { 
            UseBean user = (UseBean)users.get(i);
        %>
            <tr>
            <td><%= user.getID() %></td>
            <td><%= user.getName() %></td>
            <td><%= user.getPassword() %></td>
            <td><%= user.getEmailID() %></td>
            <td><%= user.getPhoneo() %></td>
            <td><a href="ControllerTest?action=edit&userId=<%= user.getID() %>" >Update</a></td>
            <td><a href="ControllerTest?action=delete&userId=<%= user.getID() %>">Delete</a></td>
            </tr>
        <% } %>
    </tbody>
    </table>
    <p>
    <a href="ControllerTest?action=insert">Add User</a>
    </p>
</body>
</html>
user3607180
  • 185
  • 2
  • 5
  • 14
  • updated all code but still did't work ???it showing error like java.lang.InstantiationException: bean updateuser not found within scope – user3607180 May 06 '14 at 09:44
  • i can view data now but while update,insert and delete data it showing error like above??? – user3607180 May 06 '14 at 10:26

2 Answers2

3

Updated based on comment.

User.jsp

<form method="POST" action='ControllerTest' name="frmAddUser">

  <jsp:useBean id="user" class="dbBean.UseBean" scope="request" />

    id:<input type="text" name="ID" value="<%=user.getID() %>"><br/>
    Name:<input type="text" name="Name" value="<%= user.getName() %>"><br/>
    Password:<input type="text" name="password" value="<%= user.getPassword() %>"><br/>
    phoneno:<input type="text" name="Phoneo" value="<%= user.getPhoneo() %>"><br/>
    Emailid:<input type="text" name="Emailid" value="<%= user.getEmailID() %>">  <br/> 

  <input type="submit" value="Submit" />
</form>

First of all you should try avoiding the use of scriptlet. Since this is just for learning purpose you could follow this code.

The reason why your arraylist prints null is in servlet's doPost method you are setting the attribute name as "users" and in jsp you are trying to access "user". (Note the singluar plural diff). You should correct that. If its still null check your dao. Try printing value while setting attruibute in servlet class.

Also please note the bean name.. Its UseBean. I think it should be UserBean ;)

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@page import="java.util.*,Controller.*,dbBean.*,Dbconnect.*"%>
<!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=EUC-KR">
<title>Show All Users</title>
</head>
<body>
    <table border=1>
    <thead>
        <tr>
        <th>Id</th>
        <th>Name</th>
        <th>password</th>
        <th>phoneno</th>
        <th>emailid</th>
        <th colspan=2>Action</th>
        </tr>
    </thead>
    <tbody>
        <jsp:useBean id="users" type="java.util.ArrayList" scope="request" />
        <% for(int i = 0; i < users.size(); i+=1) { 
            UseBean user = (UseBean)users.get(i);
        %>
            <tr>
            <td><%= user.getID() %></td>
            <td><%= user.getName() %></td>
            <td><%= user.getPassword() %></td>
            <td><%= user.getEmailID() %></td>
            <td><%= user.getPhoneo() %></td>
            <td><a href="ControllerTest?action=edit&userId=<%= user.getID() %>" >Update</a></td>
            <td><a href="ControllerTest?action=delete&userId=<%= user.getID() %>">Delete</a></td>
            </tr>
        <% } %>
    </tbody>
    </table>
    <p>
    <a href="ControllerTest?action=insert">Add User</a>
    </p>
</body>
</html>

Jstl Solution

Use jstl. That is the best option here. You can get plenty of documentations online. For you case it should be something like below. Note the including of the tag lib

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Once you have this you can iterate over a list using the foreach as shown below.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@page import="java.util.*,Controller.*,dbBean.*,Dbconnect.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=EUC-KR">
<title>Show All Users</title>
</head>
<body>
    <table border=1>
    <thead>
        <tr>
        <th>Id</th>
        <th>Name</th>
        <th>password</th>
        <th>phoneno</th>
        <th>emailid</th>
        <th colspan=2>Action</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${user}" var="element"> 
            <tr>
            <td>${element.id}</td>
            <td>${element.name}</td>
            <td>${element.password}</td>
            <td>${element.phoneno}</td>
            <td>${element.emailid}</td>
            <td><a href="ControllerTest?action=edit&userId=">Update</a></td>
            <td><a href="ControllerTest?action=delete&userId=">Delete</a></td>
            </tr>
        </c:forEach>
    </tbody>
    </table>
    <p>
    <a href="ControllerTest?action=insert">Add User</a>
    </p>
</body>
</html>
Syam S
  • 8,421
  • 1
  • 26
  • 36
  • thanks for u r suggestion but am learner first i try to understand a set and get attribute so only am approaching in this manner – user3607180 May 06 '14 at 08:46
  • am getting this error javax.servlet.ServletException: java.lang.InstantiationException: bean users not found within scope – user3607180 May 06 '14 at 09:26
  • Instantiation exception is because your users attribute is null. js:useBean cannot handle null. Did you check the value returning from dao.findAllUsers() ? – Syam S May 06 '14 at 11:44
  • now i can view data ,delete but cant be update and insert data kindly look at this thread help on this http://stackoverflow.com/questions/23493164/java-lang-numberformatexception-null-i – user3607180 May 06 '14 at 11:46
  • Is that the NumberFormatException? That is because the value is null. Can you share your update/insert form? – Syam S May 06 '14 at 11:48
  • Sorry your user.jsp is now missing in this question. This listuser.jsp does not update or insert any data. How do you retrieve this value in servlet? are you just taking the id and loading from database? – Syam S May 06 '14 at 12:02
  • I don't see any issues with this. In fact I tried it and its working fine. From the trace the issue is when system try to do Integer.parseInt(request.getParameter("userId")); because the userId is null. If this is invoked from listuder.jsp it should work fine. you can see the userId paramenter in the url. Check whether an id is being passed or not. If you are calling ControllerTest/edit from some other pages ensure you pass userID – Syam S May 06 '14 at 12:37
  • me too i could't find error while click of update link i cant see a any input type element only it showing a submit button then i click a submit button it inserting all value as "Null" when i saw in View Data wt could be the problem there??? – user3607180 May 06 '14 at 12:41
  • Oh was that your problem?? Thats because in user.jsp you are trying to access a list of users while you set only one user bean.. Again "users" - "user" problem. I've updated the user.jsp in my answer. Try that. – Syam S May 06 '14 at 13:28
0

I here assume that arraylist contains User objects. You can iterate the arraylist as a regular java code with embedding it within HTML tags.

<tbody>
        <%
        List<User> al1 = (List) request.getAttribute("user");
        System.out.println(al1); // prints null
        for(User user : al1) {
        %>
            <tr>
                <td><%= user.getName() %></td>
                <td><%= user.getAge() %></td>
                <td><%= user.getRole() %></td>
                <td><%= user.getDescription() %></td>
                <td><a href="ControllerTest?action=edit&userId=">Update</a></td>
                <td><a href="ControllerTest?action=delete&userId=">Delete</a></td>
            </tr>
         <% } %>
</tbody>

You could also see this answer.

Community
  • 1
  • 1
Parasu
  • 192
  • 2
  • 13