Pass data from servlet to jsp without forms?

前端 未结 2 1814
情书的邮戳
情书的邮戳 2020-12-21 07:44

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=         


        
相关标签:
2条回答
  • 2020-12-21 08:23

    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.

    0 讨论(0)
  • 2020-12-21 08:41

    The best way to do that is to use a Tag handler. You won't have to deal with the servlet. Your jsp can invoke the tag handler and get the list of hotels and you can loop over the list, like you are doing in your code.

    <c:set var="HotelList">
        <x:HotelSearch query="something" /> 
    </c:set>
    <c:set var="list" value="${fn:split(HotelList, ',')}" />
    <ul>
        <c:forEach var="elem" items="${list}">
            <li>${elem.name}</li>
        </c:forEach>    
    </ul>
    

    In the above code HotelSearch is a tag handler created to return search results string. e.g. hotel1,hotel2,hotel3

    The string is later broken down using split and converted into an array.

    public class HotelSearch extends SimpleTagSupport {
    
        private String query;
    
        @Override
        public void doTag() throws JspException {
            JspWriter out = getJspContext().getOut();
            try {
                //Query the database using a Database Controller.
                out.println(DatabaseController.getSearchResult(query));
            } catch (java.io.IOException ex) {
                throw new JspException("Error in HotelSearch tag", ex);
            }
        }
    
        public void setQuery(String query) {
            this.query = query;
        }
    }
    
    0 讨论(0)
提交回复
热议问题