简体   繁体   English

set-attribute和get-attribute servlet到jsp

[英]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 在这里我提出了一个问题,比如通过set属性在servlet和jsp之间传递值,get属性我已经在servlet中创建了servlet页面和设置值,现在我怎样才能通过get属性迭代jsp中的所有值。新手可能会有一个指南纠正我的代码,向大家学习是有用的

its all working fine but while i click of update and delete link it showing error like this 它的工作正常,但我点击更新和删除链接它显示这样的错误

Controllertest.java: 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 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 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 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. 首先,您应该尝试避免使用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". 你的arraylist打印null的原因是在servlet的doPost方法中你将属性名称设置为“users”,而在jsp中你试图访问“user”。 (Note the singluar plural diff). (注意单数复数差异)。 You should correct that. 你应该纠正这一点。 If its still null check your dao. 如果它仍然为null检查您的dao。 Try printing value while setting attruibute in servlet class. 在servlet类中设置attruibute时尝试打印值。

Also please note the bean name.. Its UseBean. 另请注意bean名称..它的UseBean。 I think it should be UserBean ;) 我认为它应该是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. 使用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 请注意标记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. 完成后,您可以使用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>

I here assume that arraylist contains User objects. 我在这里假设arraylist包含User对象。 You can iterate the arraylist as a regular java code with embedding it within HTML tags. 您可以将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 . 你也可以看到这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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