Passing a variable from JSP to Java - java

I am trying to pass a string variable called seq from a JSP to a Java program, and pass it on to the another Java program by passing the string as an argument to its object. I am somehow getting stuck.
Start.jsp:
<%# page import="org.dypbbi.nirmiti.ProtModMain %>
<%# 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>NIRMITI</title>
</head>
<body>
<h1>Please wait...</h1>
<%
String seq=request.getParameter("s");
ProtModMain.getSequence(seq);
%>
</body>
</html>
ProtModMain.java:
package org.dypbbi.nirmiti;
public class ProtModMain {
String sequence="";
public static String getSequence(String str)
{
return str;
}
public static void main(String args[])throws Exception
{
ProtModMain MainObj = new ProtModMain();
sequence = MainObj.getSequence();
new ObjectFactory(sequence);
}
}
Start.jsp will retrieve the string value from the HTML. It passes the string to ProtModMain class via the method getSequence. I now need to use the string value to pass it to other classes that require it, so I intend to pass it a parameter to the ObjectFactory object. But before that, I need to call the getSequence method in the ProtModMain class so that I can pass the value. I am not understanding how to call the getSequence method in the main method of ProtModMain class.

You need to set the parameter to the request using request.setAttribute("<name>",<value>). Then you can get it in the Java file using request.getAttribute("<name>").
Reference - Oracle Docs - HttpServletRequest

You are not calling the main method. In your JSP you are calling only the static getSequence that, by the way, only returns the value.
I think you have a project concept problem: why your web (JSP) app has a main class?
I think you should adapt:
Start.jsp:
<%# page import="org.dypbbi.nirmiti.ProtModMain %>
<%# 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>NIRMITI</title>
</head>
<body>
<h1>Please wait...</h1>
<%
String seq=request.getParameter("s");
ProtModMain protModMain = new ProtModMain();
ObjectFactory myFactory = protModMain.createFactory(seq);
//do whatever you want with your factory ;)
%>
</body>
</html>
ProtModMain.java:
package org.dypbbi.nirmiti;
public class ProtModMain {
public ObjectFactory createFactory(final String sequence) {
return new ObjectFactory(sequence);
}
}
This way you will be calling the methods you intended to.

You can use <form> tags and <input type='hidden'> with an <input type='submit'> button, in the form you will specify the method to send and to where send the data.
Or you can store in POJOs and store in session and recover it with a servlet.
Or use Ajax with an XmlHttpRequest.

Related

WEB-INF doesn't contain the directory classes with .class files

When I run on tomcat server my java web application
eclipse-workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ProvaUseBean2\WEB-INF doesn't contain the directory classes that must contain all the BeanClasses that I use in my index.jsp
my project structure
my index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:useBean id="classBean" scope="request" class="logic.bean.ClassBean"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
my ClassBean:
package logic.bean;
public class ClassBean {
private String myAttr;
public void setMyAttr(String s) {
myAttr = s;
}
public String getMyAttr(String s) {
return myAttr;
}
}
When I run on TomcatServer I receive this error:
org.apache.jasper.JasperException: /index.jsp (line: [3], column: [0]) The value for the useBean class attribute [logic.bean.ClassBean] is invalid.

Data Injection from controller to jsp page

I want to pass a data from controller method to jsp page. In doing so, using HttpServletRequest.setAttribute().
Now, I can pass it to the just next jsp page. But, I want to hold that data for few more pages.
In this case, what should I do?
Flow of Data:
Controller method1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> Controller method2
I tried setting attribute in each page but it returns null value, as follows
<% request.setAttribute("accId", request.getAttribute("accountId")); %>
You have to use session in jsp when sending data from one page to another.
A demo to show this.
For example :
Create a DemoController class.
#Controller
public class DemoController {
#RequestMapping(value = "/getid", method = RequestMethod.POST)
public String getAccountID(Model model) {
model.addAttribute("accountId", "ABC1234"); // example
return "account";
}
}
Suppose, create an account.jsp.
<!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=UTF-8">
</head>
<body>
<%
String accountId = request.getAttribute("accountId");
out.println("account.jsp -> " + accountId);
session.setAttribute("accId", accountId);
%>
<form action="account2.jsp" method="post">
<input type="submit" name="Submit">
</form>
</body>
</html>
Create another page with the name account2.jsp :
<!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=UTF-8">
</head>
<body>
<%
String accId = (String) session.getAttribute("accId");
out.println("account2.jsp -> " + accountId);
// now you want to sent it to the another controller
// set the parameter in the session and retrieve it in the controller.
session.setAttribute("accountId", accId);
%>
</body>
</html>
Create a DemoController2 class :
#Controller
public class DemoController2 {
#RequestMapping(value = "/getid2", method = RequestMethod.POST)
public String getAccountId2(HttpSession session) {
String id = (String) session.getAttribute("accountId"); // example
System.out.println(id);
return "some-page-name";
}
}

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%>
<%
}
%>

Pass specific element to jsp from arraylist in model from servlet

So to be more specific what Im trying to solve. How can I show the first element in my Arraylist:"sortedDomainList" in my jsp?
EDIT : Model and ArrayList working tried in normal java application.
MODEL short version.
public ArrayList<String> sortedDomainList = new ArrayList<String>();
public ArrayList<String> getSortedDomainList() {
return sortedDomainList;
}
public void setSortedDomainList(ArrayList<String> sortedDomainList) {
this.sortedDomainList = sortedDomainList;
}
}
CONTROLLER/SERVLET
package com.comparebet.controller;
import com.comparebet.model.*;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
request.setAttribute("d", sortedDomainList);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
}
}
VIEW/JSP
<%# 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>CompareBet</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Comparebet" method="get" accept-charset="UTF-8"></form>
<h1> ${d.sortedDomainList[0]}</h1>
</body>
</html>
This is my first try on MVC so I feel really lost when it comes down to servlet.
<%# 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>CompareBet</title>
</head>
<body>
<%
ArrayList<String> sortedDomainList= request.getAttribute("d");
for(String domain:sortedDomainList){
%>
<h1> <%= domain %> </h1>
<% } %>
</body>
</html>

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']}

Categories

Resources