I am new to jsp and I have created jsp page to search something. I have written servlet as well. But I don't know hot to make the interaction between those.
My web.xml looks like
<servlet>
<servlet-name>HotelSearch</servlet-name>
<servlet-class>it.testproject.HotelSearch</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HotelSearch</servlet-name>
<url-pattern>/HotelSearch</url-pattern>
</servlet-mapping>
My servlet name is HotelSearch.java and Search page is Default.jsp and I want to redirect to SearchResults.jsp after the servlet call.
Can anyone expalain me how to do this.Thanks in advance.
step 1: load default.jsp i guess you have a form to submit the search query like
<form method="post" action="HotelSearch">
//action is your url pattern and method is your choice get or post
// your text box
</form>
step 2: Now perform your business logic for search in your servlet then put your result data in request
req.setAttribute("key",value); //value is object
dispatch your request with data to `SearchResults.jsp`
req.getRequestDispatcher("SearchResults.jsp").forward(req,resp);
step 3: display data in SearchResults.jsp
using req.getAttribute("key")
Tip
Best way is to configure jsp file in web.xml
<servlet>
<servlet-name>myjsp</servlet-name>
<jsp-file>jsp/SearchResults.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>myjsp</servlet-name>
<url-pattern>/jsp_url</url-pattern>
</servlet-mapping>
Now you can use
req.getRequestDispatcher("jsp_url").forward(req,resp);
So you would want to:
Use form to send data to servlet from first jsp:
<form action="servlet_url"> <input type="submit" ... > </form>
Redirect from servlet to second jsp:
(HttpServletResponse)response.sendRedirect("jsp_url");
Make sure your tag has the action set correctly:
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<FORM action="${ctx}/HotelSearch">
<input type="text" name="queryString">
</FORM>
response.sendRedirect(request.getContextPath() + "/SearchResults.jsp");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.