简体   繁体   English

从JSP类检索数据(带有Servlet的MVC)

[英]Retrieving data from JSP-Class (MVC with Servlet)

Im currently working on a school project where me and my group are supposed to build a MVC-project where we have the classes Building and Room. 我目前正在一个学校项目中工作,我和我的团队应该在这个项目中构建一个MVC项目,而我们的班级是Building和Room。 The relation is OnetoMany, Building-(OneToMany)-Room. 关系是“一对多”,“建筑物”-(“一对多”)-房间。 The problem occurs when we want to search for a building name and later show all rooms in that building. 当我们要搜索建筑物名称并稍后显示该建筑物中的所有房间时,就会出现问题。 We can extract the relevant data when we run our servlet without our jsp, but when we start the project by running our searchBuilding.jsp we can only type the building name, and when expected to see the connected rooms, we instead get the message "java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.ics.ejb.Room". 在不使用jsp的情况下运行servlet时,我们可以提取相关数据,但是当通过运行searchBuilding.jsp来启动项目时,我们只能输入建筑物名称,而当期望看到连通的房间时,我们会收到消息“ java.lang.ClassCastException:无法将java.util.ArrayList强制转换为org.ics.ejb.Room”。 It might be a bit messy with all the code but i would really appreciate if someone could help me spot the problem since im supposed to show this to my professor tomorrow. 所有代码可能有点混乱,但是如果有人可以帮助我发现问题,我将不胜感激,因为我应该明天将其展示给我的教授。

This is our code: BUILDING: 这是我们的代码:建筑物:

@Entity
    @Table(name = "Building")
    public class Building {
    private String bname;
private List<Room> rooms; // Building can have many Rooms

@Id
@Column(name = "Bname")
public String getBname() {
    return bname;
}

public void setBname(String bname) {
    this.bname = bname;
}

@OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
public List<Room> getRooms() {
    return rooms;
}

public void setRooms(List<Room> rooms) {
    this.rooms = rooms;
}   

} }

ROOM: 房间:

@NamedQueries({
@NamedQuery(name="Room.findByBname",
 query="SELECT r FROM Room r WHERE r.bname LIKE :bname"),
})

@Entity
@Table(name = "Room")
public class Room implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private RoomId id;
private String bname;
private Building building;

public String getBname() {
    return bname;
}

public void setBname(String bname) {
    this.bname = bname;
}

@Id
public RoomId getId() {
    return id;
}

public void setId(RoomId id) {
    this.id = id;
}

@ManyToOne
@JoinColumn(name = "Bname", insertable = false, updatable = false)
public Building getBuilding() {
    return this.building;
}

public void setBuilding(Building building) {
    this.building = building;
}
}

ROOMID: 室号:

@Embeddable
public class RoomId implements Serializable {

private String bname;
private String rcode;

public RoomId() {
}

public RoomId(String bname, String rcode) {
    this.bname = bname;
    this.rcode = rcode;
}

@Column(name = "Bname", nullable = false)
public String getbname() {
    return bname;
}

public void setbname(String bname) {
    this.bname = bname;
}

@Column(name = "Rcode", nullable = false)
public String getrcode() {
    return rcode;
}

public void setrcode(String rcode) {
    this.rcode = rcode;
}

public boolean equals(Object other) {
    if ((this == other)) {
        return true;
    }

    if ((other == null)) {
        return false;
    }

    if (!(other instanceof RoomId)) {
        return false;
    }

    RoomId castOther = (RoomId) other;

    return ((this.getbname() == castOther.getbname()) || (this.getbname() != null
            && castOther.getbname() != null &&

    this.getbname().equals(castOther.getbname())))

            &&

((this.getrcode() == castOther.getrcode()) ||                                        (this.getrcode() != null               && castOther.getrcode() != null &&

            this.getrcode().equals(castOther.getrcode())));
}

public int hashCode() {
    return super.hashCode();
}

} }

BUILDINGEAO: 建筑馆:

@Stateless
public class BuildingEAOImpl implements BuildingEAOImplLocal {
@PersistenceContext(unitName = "LabEJBSql")
private EntityManager em;

public BuildingEAOImpl() {
    // TODO Auto-generated constructor stub
}

public Building findByBname(String bname) {
    return em.find(Building.class, bname);
}
}

FACADE: 正面:

@Stateless
public class Facade implements FacadeRemote, FacadeLocal {
@EJB
BuildingEAOImplLocal BuildingEAO;
@EJB
RoomEAOImplLocal RoomEAO;

public Facade() {
    // TODO Auto-generated constructor stub
}

public List<Room> findRoomsByBname(String bname) { 
     return RoomEAO.findByBname(bname); 
     }
 }

SERVLET: SERVLET:

@WebServlet("/TestClientServlet")
public class TestClientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private FacadeLocal facade;

/**
 * @see HttpServlet#HttpServlet()
 */
public TestClientServlet() {
    super();
    // TODO Auto-generated constructor stub
}

protected void service(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE html><html><head>");
    out.println("<title>Lab1</title>");
    out.println("<meta charset=\"ISO-8859-1\">");
    out.println("</head><body>");



    /*//THIS WORKS PERFECTLY FINE
List<Room> rooms = facade.findRoomsByBname("EC2");
    for (Room r : rooms) {
        out.println("<h4>Hittade: " + r.getId().getbname() + " "
                + r.getId().getrcode() + "</h4>");
        out.println("</body></html>");
    }
}*/

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

    PrintWriter out = response.getWriter();
    out.println("TestClientServlet-doGet");
    out.close();

}

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

    String url = null;
    // Get hidden field
    String operation = request.getParameter("operation");

    if (operation.equals("showbuilding")) {
        String bname = request.getParameter("txtBname");

        List<Room> r = facade.findRoomsByBname(bname);
        request.setAttribute("rooms", r);
        url = "/ShowBuilding.jsp";
    } else if (operation.equals("searchbuilding")) {
        System.out.println("TestClientServlet-searchbuilding");
        url = "/SearchBuilding.jsp";
    } else {
        url = "/SearchBuilding.jsp";
    }
    System.out.println(url);

    RequestDispatcher dispatcher = getServletContext()
            .getRequestDispatcher(url);
    dispatcher.forward(request, response);
}
*/
}

SEARCHBUILDING.JSP: SEARCHBUILDING.JSP:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 
<title>Search Building</title> 
</head> 
<body> 
<form action="/BuildRoomClientProject/TestClientServlet" method="post"> 

<table cellspacing="0" cellpadding="0" border="0" align="left"> 
<tr> 
<td><h2>Search Building:</h2></td> 
</tr> 
<tr> 
<td> 

<input type= "text" name= "txtBname" size ="25" maxlength="25">
<input type="submit" name="submit" value="Search" /> 
</td> 
<td></td> 
</tr> 
</table> 

<input name="operation" value="showbuilding" type="hidden"> 

</form> 
</body> 
</html> 

SHOWBUILDING.JSP: SHOWBUILDING.JSP:

<%@ page contentType="text/html;charset=windows-1252"%> 
<%@ page import = "org.ics.ejb.Building" %> 
<%@ page import = "org.ics.ejb.Room" %> 
<%@ page import = "org.ics.ejb.RoomId" %> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title> 
Show Building 
</title> 
</head> 
<body> 
<%  Room r = (Room)request.getAttribute("rooms"); %>
<% Building b = (Building)request.getAttribute("building"); %>
<% for (int i=0; i<100; i++){
System.out.println(r.getBname() + " " + r.getId().getrcode());
}%> 
<h2> 
Building: 
</h2> 
<p>
<%= r.getId().getrcode()%>
<%= b.getBname()%> 
</p>
<form action="/BuildRoomClientProject/TestClientServlet" method="post"> 
<input type="submit" name="submit" value="Tillbaka"> 
<input name="operation" value="searchbuilding" type="hidden"> 
</form> 
</body> 
</html>

The "rooms" attribute is being set as a ArrayList of rooms in the servlet. 在Servlet中,“房间”属性被设置为房间的ArrayList。 But when you are trying to get it in the jsp, you are expecting a single room. 但是,当您尝试将其放入jsp时,您期望的是一个房间。 Change 更改

<%  Room r = (Room)request.getAttribute("rooms"); %>

to

<%  List<Room> rooms = (List<Room>)request.getAttribute("rooms"); %>

and then iterate through each room. 然后遍历每个房间。

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

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