jquery - Using servlets in Struts 2 -
i wonder if using servlets in struts 2.3.4 practice or not?
i need place html in specific place in jsp without page refreshing. found 2 ways achieve this:
1.create servlet , use ajax handle post request/response, i.e. :
<div id="maindiv"> </div> <script> $(document).ready(function() { $('#div2').click(function() { $.post('testservlet', function(responsetext) { $('#maindiv').html(responsetext); }); }); }); </script> 2. call action using jquery plugin , place generated response in target place in jsp(using well-known sx:submit). problem not know how handle post request/response. jquery submit uses get method.
could please tell me solution better? in both cases have access httpservletrespone , printwriter allows writing text/html content result jsp. should use printwriter inside action class or in servlet method?
there no reason use servlet here.user simple ajax (jquery) , let action handle , send response you.
struts2 actions capable enough handle ajax request , free use post/get method per requirements.
here sample how post data action class , response there
javascript
$.ajax({ type : 'post', // can use url : action url, data : $(formid).serialize(), // post success : function(response) { // handle server response $("#mydiv").html(response); }, error : function(e) { // handle error } }); action class
public class myaction extends actionsuport{ // define getter , setter data public string execute() throws exception{ // define logic here return action.success; } } struts.xml
<action name="myaction" class="myactionclass"> <result>jsp success</result> </action> jsp content send jquery code after ajax call , can paste content specified div.
also note sx:submit represents dojo tags no longer supported in struts2 , has been deprecated long back.
using servelet struts2 not bad practice provided have valid use case , there many cases being used, struts2 provide way let servlet handle request in place of actions
Comments
Post a Comment