Java set-attribute 和 Get-attribute servlet 到 jsp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23489228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:21:47  来源:igfitidea点击:

set-attribute and Get-attribute servlet to jsp

javajspservlets

提问by user3607180

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

在这里,我提出了一个问题,例如通过设置属性和获取属性将 servlet 之间的值传递给 jsp 我已经创建了 servlet 页面并在 servlet 中设置了值,现在我如何通过获取属性迭代 jsp 中的所有值。更正我的代码,向大家学习很有用

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

一切正常,但当我点击更新和删除链接时,它显示这样的错误

Controllertest.java:

控制器测试.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

用户.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

列表用户.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>

采纳答案by Syam S

Updated based on comment.

根据评论更新。

User.jsp

用户.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.

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

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.

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

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

还请注意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 Solution

Jstl解决方案

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

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

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

一旦你有了这个,你就可以使用 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>

回答by Parasu

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

我在这里假设 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>

You could also see this answer.

你也可以看到这个答案