简体   繁体   中英

set-attribute and Get-attribute servlet to jsp

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>

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>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM