簡體   English   中英

將out.println轉換為c:out

[英]Convert out.println to c:out

什么是此JSPJSTL c:out版本:

<% 

 PersonController personController = new PersonController();
 personController.populate();
 out.println(personController.getAllPeople().get(0).getName()); 

%>

在此后面運行的代碼:

PersonController

List<Person> allPeople = new ArrayList<Person>();

public void populate() {
  Person person = new Person();
  person.setName("Jeff");
  allPeople.add(person);
}

public List<Person> getAllPeople() {
    return allPeople;
}

public void setAllPeople(List<Person> allPeople) {
    this.allPeople = allPeople;
}

Person

private String name;

public String getName() {
   return name;
}

public void setName(String name) {
    this.name = name;
}

你需要這個 -

<c:out value="${personController.allPeople[0].name}"/> 

使用以下有效的表達式:

<c:out value="${personController.allPeople[0].name }"/>

如果以下表達式不起作用,則您的代碼中還有其他問題。 我懷疑personController的實例永遠不會使用setAttribute()或通過JSP標記綁定到請求。 在代碼中的某個點,必須將personController的實例放置在請求或會話中,以便JSP EL可以引用它。


使用Servlet

我構建了一個GitHub Gist ,它可能提供一些見解。 注意,在我的servlet中,我創建了personController的實例並將其添加到request 然后,我轉到包含可解析表達式並顯示值的表達式的JSP。

PersonController pc = new PersonController();
pc.getAllPeople().add(new Person("Joe"));
pc.getAllPeople().add(new Person("John"));
request.setAttribute("personController", pc);

String nextJSP = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);

使用JSP標簽

關聯personController實例的另一種方法是使用<jsp:useBean/>標記。

UseBean示例JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<jsp:useBean id="personController" class="org.test.PersonController" />

<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <c:out value="${personController.allPeople[0].name }"/>
</body>
</html>

這將消除討厭的片段,但是將要求您修改PersonController類,以便默認構造函數將調用populate()方法。

org.test.PersonController.java

public class PersonController {

    List<Person> allPeople = new ArrayList<Person>();

    public PersonController() {
        this.populate();
    }

    public void populate() {
        Person person = new Person("Jeff");
        person.setName("Jeff");
        allPeople.add(person);
    }
    /* Omitted Accessors */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM