Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the value of a variable in java [closed]

Tags:

java

servlets

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>

}

like image 517
lucifer Avatar asked Dec 14 '13 04:12

lucifer


People also ask

How do I save a variable in Java?

Usage. In a debugger breakpoint stack frame, right click on a variable, you will see "Save Value" and "Load Value..." on the menu. "Save Value" will directly save the selected value.

How do you store a value in Java?

String values are surrounded by double quotes. int - stores integers (whole numbers), without decimals, such as 123 or -123. float - stores floating point numbers, with decimals, such as 19.99 or -19.99. char - stores single characters, such as 'a' or 'B'.

How do you save a value to a variable?

You store a value in a variable by putting the variable name on the left side of an assignment statement.


1 Answers

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

like image 68
Avanz Avatar answered Nov 13 '22 09:11

Avanz