passing an array from java to javascript using bean - java

I am trying to pass a String[] from a java class to a jsp file, i manage to pass a simple String, but i am stuck on this one for few days now. Can someone help me, i wold like the answer to be more detailed since i am new at this.
Java class:
public class UserArray extends Applet {
public String javaArray [] =
{ "array 1", "array 2" , "array 3" };
public String [] getJavaArray() {
return javaArray;
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<jsp:useBean id ="array" class="eu.xyx.ztr.applet.UserArray"/>
</head>
<body>
<h4>
<jsp:getProperty name ="array" property="javaArray"/>
</h4>
</body>
So far i have maage to obtain the address of String[]. I just want to obtain the values of javaArray and if it is posible to obtain them in a form like this:
<script>
function addrow(tableID){
var numeuser=document.numeuser;
var nume=["adrian","cristi","levi",numeuser];
var prenume=["ric","dre","asd"];
var email=["rew#td","qq#eqwq","ee#ew"];

Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList myArray = new ArrayList();
myArray.add("array 1");
myArray.add("array 2");
myArray.add("array 3");
request.setAttribute("myArray", myArray);
//then call jsp :
RequestDispatcher rd = request.getRequestDispatcher("mypage.jsp");
rd.forward(request, response);
}
jsp
<body>
<c:forEach var="myarr" items="${myArray}">
<c:out value="${myarr}" />
</c:forEach>
</body>

You should use javascript library like google JSON or jackson JSON for the same
have a look at these links
http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/

Related

How to display List results in JSP Page?

I Have a class that find Google search results. And i have a JSP page that i want to show the results in. But i can't do it.
Heres my UrlOku class :
public static void GetUrl() {
final String keyword = "emre varol";
final String url = "https://www.google.com/search?q="+keyword;
try {
final Document document = Jsoup.connect(url).get();
List<String> myList = new ArrayList<String>();
for(Element row: document.select("div[class=g]")) {
final String title = row.select("div[class=TbwUpd NJjxre]").text();
myList.add(title);
}
}
And heres my JSP page :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="urlpaket.Urloku" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="menu.jsp"></jsp:include>
<%
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
WELCOME ${username}
<%
Urloku oku = new Urloku();
oku.GetUrl();
%>
<c:forEach items="${myList}" var="item">
<tr>
<td><c:out value="${item.title}" /></td>
</tr>
</br>
</c:forEach>
And there is nothing in the welcome.jsp file.
Any help would be appreciated!
How is myList variable available in you JSP? This needs to be set in pageContext before accessing it using ${myList}.
You can change the signature to public static List GetUrl()
and do something like this
Urloku oku = new Urloku();
List<String> myList = oku.GetUrl();
pageContext.setAttribute("myList ",myList );
Now it should be available.

Display the calculation of servlet before forwarding it to jsp [duplicate]

HTML code appears when I try to execute the jsp page. This appears in the browser.
I tried to change the contentType and language in the tag. But it did not work.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<HTML>
<HEAD> <TITLE> The Welcome JSP </TITLE> </HEAD>
<BODY>
<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
</BODY>
</HTML>
This is my servlet code.
public class Add extends HttpServlet {
public void service(HttpServletRequest rq, HttpServletResponse rs)throws IOException, ServletException
{
int i=Integer.parseInt(rq.getParameter("t1"));
int j=Integer.parseInt(rq.getParameter("t2"));
int k=i+j;
PrintWriter out=rs.getWriter();
out.println("The sum is:"+k);
RequestDispatcher rd=rq.getRequestDispatcher("/Welcome.jsp");
rd.include(rq,rs);
}
}
I want the code to get rendered and view the output.

How to pass the array list from servlet to JSP?

In the servlet:
List<myItem> yourObjectToReturn = search.parserContent();
request.setAttribute("yourObjectToReturn",yourObjectToReturn);
the array yourObjectToReturn consists 3 variable(id, txtfile, sentence) which you can see from
the myItem class
public class myItem{
String sentence;
int id;
String txtfile;
// public myItem(){
// }
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getTxtfile(){
return txtfile;
}
public void setTxtfile(String txtfile){
this.txtfile = txtfile;
}
public String getSentence(){
return sentence;
}
public void setSentence(String sentence){
this.sentence = sentence;
}
}
how to display the id, txtfile, sentence in the JSP separately? How to pass the arraylist from servlet to JSP .
the JSP : how to edit my JSP. I got error of my JSP:
type safety: unchecked cast from objectto arraylist
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%# page import="java.util.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% List<myItem> myList = (ArrayList<myItem>) request.getAttribute("yourObjectToReturn"); %>
The search Result SENTENCE IS: <%=myList %> --%>
</body>
</html>
Don't use scriptlets in your jsp page.
Include the JSTL standard taglib via:
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
Then in your JSP use the iteration tag:
<c:forEach items="${requestScope.yourObjectToReturn}" var="current">
<c:if test="${current.sentence== 'secret' }">
<h1>seeeeeeeeeecret revealed</h1>
</c:if>
</c:forEach>
Where:
${requestScope.yourObjectToReturn} is your collection object.
And (during each iteration):
${current} is your actual element.
For further reference look http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html
And to avoid weird errors: don't forget to import myItem class (Should really be MyItem, thou...)
EDIT: Before digging deep into JSTL, I suggest you to take a reading of this other question. Particularly focus on the selected answer, it provides great insights.
To retrieve the Id and Txtfile from the List you need to iterate with using for example a for loop like:
...
for (int i=0; i < myList.size(); i++) {
%>
<%=myList.get(i).getId()%>
<%=myList.get(i).getTxtfile())%>
<%}%>
You can use for loop and html together as follows:
<%
#SupressWarnings("unchecked")
List<mtItem> myList
for (MyItem myitem : myList)
{
%>
The search result is <%=myitem%>
<%
}
%>

Trying to pass a list from servlet to jsp but prints null

I am trying to pass an ArrayList of objects from a servlet to a jsp file but when I try printing it, it prints nothing. I used the exact lines from a similar post for the jsp...can someone help me because I have never used a jsp before.
The idea is to to traverse through an xml file using dom parser and then print its elements to an html table of a specific form. My java code successfully collects all the elements and stores them in a list which I want to pass in the jsp to format in the table asked...
SERVLET CODE (with missing pieces cause it's huge) :
import all the needed libraries
public class MyServlet extends HttpServlet {
private static xml_obj obj = null;
public static ArrayList<xml_obj> objList = new ArrayList<xml_obj>();
public static void main(String[] args){
try {
Start(); //starting the methods for the xml traversal and creates the list
//System.out.println("AA"+objList.get(1).getName());
}
catch(Exception e) {
e.getMessage();
}
}
public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
ArrayList list = getList();
//System.out.println(objList.get(1).getName());
request.setAttribute ("Xml_objList", objList );
RequestDispatcher view = request.getRequestDispatcher("DomNav.jsp");
view.forward (request,response);
}
static void Start(){
/*..........code missing.............*/
myDOMTreeProc dtp = new myDOMTreeProc();
dtp.processLvl(ListOfCh, 0); //processLvl -> method in myDOMTreeProc
}
public static ArrayList<xml_obj> getList() {
return objList;
}
}
class myDOMTreeProc {
/*........DOM XML TRAVERSE.......*/
}
class attribute {
private String Name;
private String Value;
/*.............setters/getters.......*/
}
class xml_obj {
public int Lvl;
private String Name;
private String Value;
private String Parent;
private ArrayList<attribute> attributes=null;
/*.............setters/getters.......*/
}
JSP CODE:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Expression Language Example</title>
</head>
<body>
<h1>TEST JSP</h1>
<% ArrayList list = (ArrayList) request.getAttribute("Xml_objList"); %>
<c:forEach var="item" items="${Xml_objList}">
${item.Lvl}
</c:forEach>
</body>
</html>
The list is correct I tested it. I think the problem is when I pass it in the jsp.
Follow Java Naming convention and everything will work fine. Just replace int Lvl with int lvl;
JSP:
<c:forEach var="item" items="${Xml_objList}">
${item.lvl}
</c:forEach>
Instead of ${item.lvl} you can try with ${item.getLvl()} or ${item['lvl']}

jsp can't redirect page using response

I can't redirect to the page with the response.sendRedirect(url);
I can redirect to a link in a common jsp page, but I failed to send it in a function I defined in a jsp page. So in my case, which redirecting within a function, how to solve that?
FYI, the error is "response cannot be resolved".
Below is part of my source code:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%# page import="javax.mail.*"%>
<%# page import="javax.mail.internet.*"%>
<%# page import="javax.activation.*"%>
<%# page import="java.util.*,java.io.*"%>
<%# page language="java" %>
<%# page import="com.mysql.jdbc.Driver" %>
<%# page import="java.sql.*" %>
<%!
public void sendSMS(String nickName, String setAname, String currAname,
String toPhone){
String acctInfo="xxx";
String acctPwd="xxx";
String contents="Message from Miss U:( \n Please be reminded that your friend:"+nickName+" is OUT of your setting area: "+setAname+". The current area is "+currAname+".";
String smsURL="http://api.accessyou.com/sms/sendsms-utf8.php?msg="+contents+"&phone="+toPhone+"&pwd="+acctPwd+"&accountno="+acctInfo;
response.sendRedirect(smsURL);
}
%>
When you call your helper function you have to pass in the response object. Reason being that JSPs gets translated to Java Code, which is then compiled so it can run on JVM. Things between <%!...%> will get translated into helper methods that has different context than the code in <%...%>.
Your jsp will get translated into something like this:
public class MyJsp {
public void doPost(HttpServletRrequest request, HttpServletResponse response) {
/* tons of code compiled off JSP */
sendSMS(...)
}
private void sendSMS(String nickName, String setAnmae...) {
String acctInfo="xxx";
response.sendRedirect(...); // error, there is no response object in the local context
}
}
Something like this would work
%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%# page import="javax.mail.*"%>
<%# page import="javax.mail.internet.*"%>
<%# page import="javax.activation.*"%>
<%# page import="java.util.*,java.io.*"%>
<%# page language="java" %>
<%# page import="com.mysql.jdbc.Driver" %>
<%# page import="java.sql.*" %>
<%
sendSMS(arg1, arg2, arg3, ar4, response)
%>
<%!
public void sendSMS(String nickName,
String setAname,
String currAname,
String toPhone,
ServletResponse response){
String acctInfo="xxx";
String acctPwd="xxx";
String contents="Message from Miss U:( \n Please be reminded that your friend:"+nickName+" is OUT of your setting area: "+setAname+". The current area is "+currAname+".";
String smsURL="http://api.accessyou.com/sms/sendsms-utf8.php?msg="+contents+"&phone="+toPhone+"&pwd="+acctPwd+"&accountno="+acctInfo;
response.sendRedirect(smsURL);
}
%>
Notice how in sendSMS you don't have direct access to the request and response object.
You can Do it as below
<%# page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Page Redirection</title>
</head>
<body>
<center>
<h1>Page Redirection</h1>
</center>
<%
// New location to be redirected
String site = new String("http://www.xyz.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
</html>
Sample Code:
<%! public void sendSMS(HttpServletResponse response){
try{
response.sendRedirect("th.jsp");}
catch(Exception e){
e.printStackTrace();
}
} %>
<%sendSMS(response); %>

Categories

Resources