set-attribute和get-attribute servlet到jsp

时间:2014-05-06 08:07:14

标签: java jsp servlets

这里我提出了一个问题,比如通过set属性在servlet和jsp之间传递值,get属性我已经创建了servlet页面并在servlet中设置了值我现在如何通过get属性迭代jsp中的所有值.am newbie can一些指南纠正我的代码,这对你们所有人学习很有用

一切正常,但是当我点击更新并删除链接时,它显示错误,如此

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>

2 个答案:

答案 0 :(得分:3)

根据评论更新。

<强> 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>

首先,您应该尝试避免使用scriptlet。由于这仅用于学习目的,因此您可以遵循此代码。

你的arraylist打印null的原因是在servlet的doPost方法中你将属性名称设置为“users”,而在jsp中你试图访问“user”。 (注意单数复数差异)。你应该纠正这一点。如果它仍然为null检查您的dao。在servlet类中设置attruibute时尝试打印值。

另请注意bean名称..其UseBean。我认为它应该是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解决方案

使用jstl。这是最好的选择。您可以在线获取大量文档。对于你的情况,它应该是如下所示。 请注意标记lib

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

完成此操作后,您可以使用foreach迭代列表,如下所示。

<%@ 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>

答案 1 :(得分:0)

我在这里假设arraylist包含User个对象。 您可以将arraylist作为常规Java代码进行迭代,并将其嵌入HTML标记中。

<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>

您还可以看到此answer