Monday, 29 January 2018

ajax - How to pass a value of a variable from a java class to the jsp page



I have 2 files named Admin.java and index.jsp.



In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.



The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.



The code of Admin.java is:



public Admin() 
{
super();
}

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

if (action.equals("login"))
{
String userName="";
String password="";

userName = request.getParameter("username");
password = request.getParameter("password");

response.setCharacterEncoding("UTF-8");

SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);

String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);

request.setAttribute("rest", res);

return;
}


The code of index.jsp is



function login(user, pass) 
{

$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){

}


within the



function(response)
{
......
}


I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.


Answer



From your code,



request.setAttribute("rest", res);


You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by



response.getWriter().write(res);


This way it'll end up in the response body and be available as variable response in your JS function.



See also:




No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...