Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

java - Pass data from servlet to jsp without forms?

So what I'm basically trying to do here is get a list of hotels in JSP , from the servlet , without any forms.

This is my JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<ul>
    <c:forEach var="elem" items="${list}">
    <li>${elem.name}</li>
    </c:forEach>    
</ul>
</body>
</html>

Servlet function:

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


    try {
        java.util.List<Hotel> list = model.getAllHotels();
        request.setAttribute("list", list);
        RequestDispatcher rDispatcher = request.getRequestDispatcher("/index.jsp");
        rDispatcher.forward(request, response);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Now I know how to do this via form with get / post , since the servlet has specific functions for that. But how can I send this data without forms ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You simply need a link to your servlet:

<a href="<c:url value='/yourServlet' />">Click here to list the hotels</a>

You can also invoke the servlet by typing its address in the address bar of your browser:

http://localhost:8080/yourWebApp/yourServlet

The code of your servlet is fine, and the code of the JSP as well.

The servlet is mapped to some URL (/yourServlet in my example) thanks to a <servlet-mapping> element in the web.xml, or thanks to a @WebServlet annotation on the servlet class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...