2012-03-16 81 views
0

我是新來的服務器端編程,我在寫一個簡單的servlet/jsp程序。 servlet部分應該從URL中獲取參數並將其保存到地圖中,並且jsp部分應該讀取地圖並在HTML表格中顯示其內容。使用動態映射從Servlet調用JSP

下面是該servlet:

@WebServlet("/RestaurantServlet86105511") 
public class RestaurantServlet86105511 extends HttpServlet { 
private static HashMap<String, String> map = new HashMap<>(); 
private String name; 
private String price; 

@Override 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    name = request.getParameter("name"); 
    price = request.getParameter("price"); 
    map.remove(name); 
    map.put(name, price); 
    RequestDispatcher rd = request 
      .getRequestDispatcher("/WEB-INF/RestaurantJSP86105511.jsp"); 
    rd.forward(request, response); 
} 
public static HashMap<String, String> getMap() { 
    return map; 
} 
} 

我不知道我做錯了什麼,但每次rd.forward被調用後,地圖上的內容也將被刪除,而JSP將只打印最近我在URL中輸入的參數。 有沒有其他方式從servlet調用jsp?或者我只是做錯了方式?

+0

由於每次調用'doGet()',都會在映射中添加'name',替換與此名稱''關聯的以前的值。在你的情況下'remove()'是還原劑。 – Zaki 2012-03-16 16:22:23

+0

在Servlet中使用實例(或靜態)變量是個不好的做法,因爲它們本質上不是線程安全的。學習MVC來構建您的應用程序。 – Zaki 2012-03-16 16:28:09

回答

0

你應該做的是把你的地圖到請求的一個屬性:

request.setAttribute("yourMap", map); 

然後在JSP可以使用JSTL和EL來訪問值。

Price: ${yourMap.price} 
Name: ${yourMap.name}