Get servlet attribute without loading current jsp page

on my servlet I have this code:

processRequest(...,...){

String page = "";
if(true){
String str = "hello";
request.setAttribute("str",str);
page = "currentPage#";
}
else{
page = "otherPage";
}
RequestDispatcher rd = requestDispatcher("/",page);
}

on my JSP, to get the servlet attribute, I use this:

<input type = "text" value = "<c out>${str}</c out>">

It happens,

when I use currentPage#, the current page does not load, but the tag inputalways matters null,

but if I used currentPage(without #), I get the value "hello" which is loaded by the page, which I do not want, because the page and content are being updated.

Can someone help me get str attributewithout loading the current page or is there any way?

0
source share
2

Ajax. jquery

ex,

JSP:

    <script src="http://code.jquery.com/jquery-1.10.2.js"
        type="text/javascript"></script>
    <script src="js/app-ajax.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
    $('#userName').blur(function() {
        $.ajax({
            url : 'GetUserServlet',
            tpye: "POST",
            data : {
                userName : $('#userName').val()
            },
            success : function(responseText) {
                $('#ajaxGetUserServletResponse').text(responseText);
            }
        });
    });
});
</script>
    </head>
    <body>     
        <form>
            Enter Your Name: <input type="text" id="userName" />
        </form>
        <br>
        <br> 
        <strong>Ajax Response</strong>:
        <div id="ajaxGetUserServletResponse"></div>

String userName = request.getParameter("userName").trim();
        if(userName == null || "".equals(userName)){
            userName = "Guest";
        }

        String greetings = "Hello " + userName;         
        response.setContentType("text/plain");
        response.getWriter().write(greetings);

jsp ajaxGetUserServletResponse, .

...

+1

jQuery, jQuery.ajax(); , :

<input type="text" id="search">

:

String empName = "Test Coder";
PrintWriter out = response.getWriter();
out.println(empName);

onClick :

$("#search").on("click", function() {

  $.ajax({
    type: "POST",
    url: "YOUR SERVLET NAME",
    data: "{empid: " + empid + "}", // what ever the data you need to pass to server to generate yout "String"

    success: function(result) {
      alert(result.empName); // this should be your String parameter returned from the Servlet. 
       
      $("search").val(str);  // setting the String value on your text input
      
      console.log(result);
    },
    error: function(error) {

      console.log("error" + error);
    }
  });

});

, .. , ..! .

+1

All Articles