JavaBean not working in JSP - java

My aim is to import my class file in my index.jsp and reading over the internet I learned I'm supposed to use JavaBeans.
So here is my class file placed in WEB-INF/classes/jBean/Bucket.class -
package jBean;
import java.sql.* ;
import java.math.* ;
public class Bucket implements java.io.Serializable{
public static void main(String[] args){
Bucket obj = new Bucket();
obj.DBConn();
}
public static void DBConn(){
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentfeedback","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt("Roll_No")+" "+rs.getString("Name")+" "+rs.getString("Pass"));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
And here is my index.jsp where I want to import the class file -
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<jsp:useBean id="jBean" class="jBean.Bucket" scope="session" />
</body>
</html>
Doing this I get this error message on executing index.jsp file
java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
So, my query is how shall I import the class file, Bucket.java?
And is there any other way to import the file to index.jsp other than using javBeans?
Please help me with this as I can't find what I'm looking for. Maybe cause I might not be asking the right thing.
All I want to do is import the class file Bucket.java to the index.jsp
May God help the helping soul.

Did you observed your project folder structure.
The classes referenced by the jsp must be in the classpath.
And the classpath includes WEB-INF/classes.
The location of the jsp is of no importance.
question regarding jsp page import and <jsp:useBean id

Related

${} is not working on my JSP page. How can i get my ${} html tag to work again? [duplicate]

This question already has answers here:
How to install JSTL? The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved [duplicate]
(5 answers)
Closed 2 years ago.
So ${} did work. But the JSTL jar files that I'm using made to where the ${} doesn't work anymore. These are my JSTL jar files. jstl-1.2 (1).jar, jstl-impl-1.2.jar, jstl-standard.jar. I am following Navin tutorial on Servlet & JSP Tutorial | Full Course on youtube. He skipped JSTL jar files. I'm a junior developer trying to understand why my ${} isn't working anymore.
Question: Why did my ${} tag not work anymore?
Please be gentle. :D
<%# 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" %>
<!DOCTYPE html >
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${students}" var="s" >
${s} <br>
</c:forEach>
</body>
</html>
package com.Demo;
public class Student {
int rollno;
String name;
#Override
public String toString() {
return "Student [rollno=" + rollno + ", name=" + name + "]";
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int rollno, String name) {
super();
this.rollno = rollno;
this.name = name;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<display-name>JSTLexample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
package com.Demo;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//String name = "Navin";
List <Student> studs = Arrays.asList(new Student(1, "brandon"), new Student(2, "Micheal"), new Student (3, "Charles"));
request.setAttribute("students", studs);
RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
}
That "${}" is EL expression language syntax. You require to configure your "web application" web.xml or variant to use the JSTL (Java Standard Tag Library) .jar file in either the servers /commons/lib folder with server.xml (obviously not) or /WEB-INF/lib of your application.
Then call in the names of each tag prefix you wish to use declared at the top of your JSP page.
Tomcat has a few ways of achieving it.
Also your doctype should be
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Yout .tld tag library descriptor should be in the WEB-INF folder.
define the taglib location in your web.xml file
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location>
</taglib>
</jsp-config>
Also, your bean class should be declared in the web.xml and the page declarations to call it in the page at the top too.
Not a bad point to recheck the above if things go wrong.
The servlet you have made is a GET request servlet , they pass parameters on the URL by
?name=**valuOFthisPart&anid=**somethinHere&terminus=
if you use ${Param.student} added as student past the "?" on the url that may be usable to the EL something like this
**?students=name=**valuOFthisPart&next1=somethinHere&next2=somethinHere&terminus=
A POST servlet cannot carry parameters on the URL and is what you are trying to do by the code so is what the request.setAttribute is setting doing is for a POST request (POST requests do carry tokens).
Too, the setAttribute on request object is available by the interface of its class of which it can be done at class level by a wrapper sub class too as next
javax.servlet.ServletRequestWrapper requestWrpp = new javax.servlet.ServletRequestWrapper(request);
requestWrpp.setAttribute("students", studs);
HOWEVER, while more modern versions of web container recognise complex types such as List and Map (but probably not Student class) you may be able to use the code there by what i vaguely think i remember the clause of use of complex objects in JSP processing is and that being it is understood to be convertible to string.
Student is unrecognizable to the web app parser rules, however if you wrote Student to extend ( Map int,String ) then the runtime and compiler may be able to use that set up inside as a ( Map K,V )
Actually, this cannot work because you try to do this in the servlet before JSP processing by the response [ ! unless the Student class is only a servlet support class in the classes folder. (not bean syntax class)
see next paragraph ].
You are trying to use a class the way a bean operates , and a bean must be declared both in the web.xml and the page and the servlet notified too with a Student object reference from either classes or /classes/beans folder !!!
If it is a bean it should be in a bean folder (if it is not a bean and only a support processing class should be in classes with the servlet packaged or not) and called by the response in the JSP parser , but properly loaded, correctly updated current instance of it in the web app user session should be used (something JSF does more easily).
You can obtain current session and beans for servlet instance use by acquiring the web app context and initial instance thread to find the bean you want, its current instance and current state (requires to be a session bean unless the values are constant or it only outputs by set get processing instantly) to get its' current values. Bean classes must be declared throughout the app configuration not dissimilar to servlets but are different with rigid rules of declaration for runtime and syntax.
Final note
// the first argument should be a string NOT an int
req.setAttribute("String Object",(java.lang.Object)anObject);
//NOTE: That object must be convertible to a String from a recognizable java language core class !!!
Just a quick note about post requests, actually it can carry a query string but is considered a bizzarre action inside a Java framework.

Where is my ConnectionPool class?

Now I am working with one of old site that was written using JSP. I see that everywhere in the code used
import ConnectionPool.ConnectionPool;
And I see that CLASSPATH set as:
classpath=%classpath%;C:\j2sdkee1.3\lib\j2ee.jar;C:\Working\Application\MyApp\Bean;
Could you please help understand me where I can search ConnectionPool.class?
May be in C:\Working\Application\MyApp\Bean or in my application directory?
Example of using ConnectionPool in JSP:
<code>
<%# page import="ConnectionPool.ConnectionPool;" %>
<%
application.removeAttribute("MYAPP_POOL");
ConnectionPool pool = new ConnectionPool();
pool.setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
pool.setURL("jdbc:odbc:myapp");
pool.setUsername("Username");
pool.setPassword("Password");
pool.setSize(20);
pool.initializePool();
application.setAttribute("MYAPP_POOL",pool);
%>
</code>

calling Webservices from jsp

I have created the wsdl successfully .Its url is "http://:/aebis/HelpdeskWebserviceImpl?wsdl".
Now I want to use this url to call the function in jsp.I am using Jboss as server.
Please suggest if any one can help.
Thanks in advance.
Here is a 5-minute example using eclipse
I am gonna use this WSDL to demonstrate
http://www.webservicex.net/ConvertAcceleration.asmx?WSDL
Create a dynamic java project for your JSPs
Create your JSP and some backend java class
your 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">
</head>
<body>
<%= new myweb.MyClass().getResult() %>
</body>
</html>
and
package myweb;
public class MyClass {
public String getResult(){
return null;
}
public static void main(String[] args) {
MyClass c = new MyClass();
System.out.println(c.getResult());
}
}
Now create the WS client. Click on/select the project
right click and create a new Web Service Client from the given WSDL
Change MyClass to call the web service (you can test first using the class main too)
package myweb;
import java.rmi.RemoteException;
import NET.webserviceX.www.AccelerationUnitSoap;
import NET.webserviceX.www.AccelerationUnitSoapProxy;
import NET.webserviceX.www.Accelerations;
public class MyClass {
public String getResult() throws RemoteException {
AccelerationUnitSoap a = new AccelerationUnitSoapProxy();
Accelerations x = Accelerations.decimeterPersquaresecond;
Accelerations y = Accelerations.centimeterPersquaresecond;
Object z = a.changeAccelerationUnit(1, x, y);
return z.toString();
}
public static void main(String[] args) throws RemoteException {
MyClass c = new MyClass();
System.out.println(c.getResult());
}
}
Add the web app to your server (if there's one. If there isn't, create a new server)
Clear the server (forcing it to refresh the app) and start it
And here it is.
The wsimport tool is part of the JDK and generates "portable artifacts" from a wsdl. That gives you classes to use easily for communicating with the web service without the need of doing the boilerplate code yourself.
But I feel that you may need some more background beforehand, to get a better understanding how to use JAX-RS web services or implement a state-of-the-art web application with JSF, so my advice is to consult the Java EE 7 tutorial for those two (chapter 28 and 7).

Spring Web Services Class Not Found Exception

I'm going through this Spring tutorial online form springsource.org.
http://static.springsource.org/docs/Spring-MVC-step-by-step/part2.html
In Chapter 2, at the end, it has you add a bean to prefix and suffix /WEB-INF/jsp/ and .jsp to responses.
The code so far should basically load index.jsp when you go to localhost:8080/springapp/ which will redirect to localhost:8080/springapp/hello.htm which creates an instance of the HelloController which should in theory send you over to /WEB-INF/jsp/hello.jsp. When I added the prefix/suffix bean and changed all my references to just "hello" instead of the fully pathed jsp file, I started getting the following error:
message Handler processing failed; nested exception is
java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/fmt/LocalizationContext
I've tried going back through the samples several times and checking for typo's and I still can't find the problem. Any tips or pointers?
index.jsp (in the root of the webapp:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
<c:redirect url="/hello.htm" />
HelloController.java (minus the imports and package:
public class HelloController implements Controller {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String now = (new Date()).toString();
logger.info("Returning hello view with " + now);
return new ModelAndView("hello", "now", now);
}
}
My hello.jsp file:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello :: Spring Application</title>
</head>
<body>
<h1>Hello - Spring Application</h1>
<p>Greetings, it is now <c:out value="${now}" /></p>
</body>
</html>
It seems like you are missing the JSTL jar here. Try downloading it and place it in your classpath to see if it works: Where can I download JSTL jar
It seems certain required jar(s) are missing from classpath.
Make sure you have servlet-api-2.x.jar jsp-api-2.x.jar and jstl-1.x.jar on classpath
Please make sure the jstl.jar file is located in your WEB-INF/lib folder.
As a matter of fact, here is what is stated in the tutorial that you linked. I guess you missed this step:
We will be using the JSP Standard Tag Library (JSTL), so let's start
by copying the JSTL files we need to our 'WEB-INF/lib' directory. Copy
jstl.jar from the 'spring-framework-2.5/lib/j2ee' directory and
standard.jar from the 'spring-framework-2.5/lib/jakarta-taglibs'
directory to the 'springapp/war/WEB-INF/lib' directory.

How to test EJB on local

New to EJB, please help:
To verify my EJB on local, I tried create a test.jsp that calls the EJB like this:
<%# page import="com.web.ejb.service.ContentInfo" %>
<% ContentInfo ci = ContentInfo.getContentById("123"); %>
When run the jsp, got error "Only a type can be imported. com.web.ejb.service.ContentInfo resolves to a package".
Then I replaced the import with
<jsp:useBean id="ContentInfo" class="com.web.ejb.service.ContentInfo" />
but got "ContentInfo cannot be resolved to a type."
Thanks for your help.
From the error message, seems like com.web.ejb.service.ContentInfo is not your class name. Maybe you made a typo ?
If you want to test an EJB more thoroughly, you can use OpenEJB to replicate the functionalities of an EJB server, in case of units tests for example.
First check whether the class name is correct and it is available in the above mentioned package. After that try this:
<%# page import="<package>.<YourBusinessInterface>, javax.naming.*"%>
<%!
try {
InitialContext ic = new InitialContext();
<YourBusinessInterface> obj = (<YourBusinessInterface>)
ic.lookup(<YourBusinessInterface>.class.getName());
} catch (Exception ex) {
// exception code here
}
%>
<html>
<body>
<% obj.callBusinessMethod(); %>
</body>
</html>
This link http://docs.oracle.com/javaee/5/tutorial/doc/bnbnp.html might help you. :)

Categories