简体   繁体   中英

Calling part of jsp page from Servlet or Java Class

I need to call small part of JSP page(like only div load) when a method is invoked? I know we can load whole JSP page from Servlet . Is this possible or any other solution for this?

know we can load whole JSP page from Servlet. Is this possible

Yes it is possible, you forward your request to jsp from servlet and it will render that jsp, here is an exact same example

1) Set some session or request variable equal to some value, say boolean myVar = true .

2) Redirect from your jsp page from your servlet.

3) In the jsp page, check for particular condition for the variable myVar . If condition is fulfilled, using scriptlets or JSTL display only the relevant part of you jsp .

You can use AJAX(Asynchronous Javascript and XML) for this purpose

For example, Suggestions, that appear without any refresh for auto-complete in google search, are using Ajax. JSP code will contain the Ajax code and will send the information to the servlet in form of XmlHttpRequest object and then takes the response from servlet as xmlhttp.responseText . The result can be written at JSP page by using DOM.

To initiate this process, you need to use the onkeyup in input tag like this:

<input type="text" onkeyup="methodName(this.value)"

Learn more about Ajax

To use AJAX with Java, try this

Ajax for Java Web Applications

$('#myDiv').load('serverPage.jsp #server_div_id');

OR

$.ajax({
url: 'serverPage.jsp',
success: function(data) {
      data=$(data).find('div#id');
      $('#mydiv').html(data);       
  }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM