7

I have a requirement that i need to save the value of a variable. My problem is that i need to send a value from an webpage to servlet where the value of the variable is null first time but when i slect a value from the select box it gooes to the servlet and it is going with the value but my problem is here i need to refesrh the page after selecting the value. so now when i am doing that the value becomes again zero and the operation is not happening can i save the value of the variable after selecting some values from the selection ??

here is my code..

   <body>
    Select Country:
    <select id="country">
        <option>Select Country</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>

    </select>

    <input type="button" value="Reload page" onclick="reloadPage()">
</body>


<script>
    function reloadPage(){

        location.reload();
    }
</script>  



 <script>
        $(document).ready(function() {
            $('#country').change(function(event) {  
                var $country=$("select#country").val();
                $.get('JsonServlet',{countryname:$country},function(responseJson) {   
                    var $select = $('#states');                           
                    $select.find('option').remove();                          
                    $.each(responseJson, function(key, value) {               
                        $('<option>').val(key).text(value).appendTo($select);      
                    });
                });
            });
        });          
    </script>

and this is my servlet

public class JsonServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String value = request.getParameter("countryname");
    System.out.println("comes from ajax" + value);
    JsonGenerator generator = new JsonGenerator();
    Entry entry = null;
    if (value != null) {

        HttpSession session = request.getSession();

session.setAttribute("value", value);
        entry = generator.aMethod2Json(value);
        Gson g = new Gson();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(g.toJson(entry));


    } else {
        entry = generator.aMethod2Json("1");
        Gson g = new Gson();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(g.toJson(entry));


    }



}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

Cœur
  • 37,241
  • 25
  • 195
  • 267
lucifer
  • 2,297
  • 18
  • 58
  • 100

3 Answers3

6

I hope some code example might help you:

A Simple Counter

To demonstrate the servlet life cycle, we'll begin with a simple example. Example 3-1 shows a servlet that counts and displays the number of times it has been accessed. For simplicity's sake, it outputs plain text.

Example 3-1. A simple counter

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleCounter extends HttpServlet {

  int count = 0;

  public void doGet(HttpServletRequest req, HttpServletResponse res) 
                           throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    count++;
    out.println("Since loading, this servlet has been accessed " +
            count + " times.");
  }
}

Otherwise, if you want something more advanced a good option is to use the A Holistic Counter:

Example 3-2. A Holistic Counter

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HolisticCounter extends HttpServlet {

  static int classCount = 0;  // shared by all instances
  int count = 0;              // separate for each servlet
  static Hashtable instances = new Hashtable();  // also shared

  public void doGet(HttpServletRequest req, HttpServletResponse res) 
                           throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    count++;
    out.println("Since loading, this servlet instance has been accessed " +
            count + " times.");

    // Keep track of the instance count by putting a reference to this
    // instance in a Hashtable. Duplicate entries are ignored. 
    // The size() method returns the number of unique instances stored.
    instances.put(this, this);
    out.println("There are currently " + 
            instances.size() + " instances.");

    classCount++;
    out.println("Across all instances, this servlet class has been " +
            "accessed " + classCount + " times.");
  }
}

This HolisticCounter tracks its own access count with the count instance variable, the shared count with the classCount class variable, and the number of instances with the instances hashtable (another shared resource that must be a class variable).

Ref. Java Servlet Programming By Jason

Community
  • 1
  • 1
Avanz
  • 7,466
  • 23
  • 54
1

What about storing your variable to the servlet session object. So it remains active also during changes within the request scope

Furthermore you can check during every request the value of the variable and act in the appropriate way.

Diversity
  • 1,890
  • 13
  • 20
0

You can make a ajax call to servlet after selecting value and before refreshing the page.

Or

Set the value in session by calling the java script function .

<script>
   function setMyVar(){
      <%     session.setAttribute( "username", Value );  %>
   }
</script>

To get the session attribute on servlet side

   session.getAttribute("userName") 
shakthydoss
  • 2,551
  • 6
  • 27
  • 36