简体   繁体   中英

not able to use jsp variable in java

We want to access a variable from jsp inside a java class in same file. Can someone pls suggest how to use it ?

Below is the code. In this we are using data variable in jsp tags & we want to access the value of data inside DummyDB class of java.

JSP File:

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="java.util.StringTokenizer"%>
<%@ page import="java.sql.*" %>
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.net.*" %>

<%

HttpSession Session = request.getSession(true);

String data = Session.getAttribute("data").toString();

%>

<%!

public class DummyDB {
    private int totalCountries;

   RequestDispatcher rd = request.getRequestDispatcher("include.jsp");
rd.include(request, response); 

    private List<String> countries;
    public DummyDB() {
        countries = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(data, ",");

        while(st.hasMoreTokens()) {
            countries.add(st.nextToken().trim());
        }
        totalCountries = countries.size();
    }

    public List<String> getData(String query) {
        String country = null;
        query = query.toLowerCase();
        List<String> matched = new ArrayList<String>();
        for(int i=0; i<totalCountries; i++) {

            country = countries.get(i).toLowerCase();
            if(country.startsWith(query)) {
                matched.add(countries.get(i));
            }
        }
        return matched;
    }
        }
%>

I don't see where you are creating an instance of DummyDB class, but if you create such an instance in your jsp code, you can pass the data String to it in the constructor, or add a setData method that would accept that String.

For example :

<%

HttpSession Session = request.getSession(true);

String data = Session.getAttribute("data").toString();
DummyDB db = new DummyDB (data);

%>
<%!
public class DummyDB {
...
    public DummyDB(String data) {
        countries = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(data, ",");
        ...

Change this:

StringTokenizer st = new StringTokenizer(data, ",");

to:

StringTokenizer st = new StringTokenizer(request.getSession().getAttribute("data"), ",");

If that works you can remove this line entirely:

String data = Session.getAttribute("data").toString();

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