JSP/JSTL - Unable to display information to the browser - java

Background:
I wrote a previous servlet that created dynamic webpages where it would read and write to a MySQL database. When I would read from it, I stored the result in a ResultSet, then displayed this information. Everything worked and I was told I should re-write it using JSPs and JSTLs. To do this, in my servlet, I created a ResultSet and stored each column's result in a separate ArrayList. In my JSP, I'm trying to iterate through the ArrayLists, however, the webpage is blank. Since I'm using NetBeans, it normally will indicate any errors, but there seem to be none, so I'm guessing there's either a logical error or a run-time error (which doesn't exactly narrow it down). I've tried simply printing the size of an ArrayList but even that isn't displaying! My guess is either the ArrayList is never populated or it's not properly being sent to the JSP.
To note, my database is populated and I am able to write to it. I've looked throughout various websites to see if anything can help but nothing has so far. I also went through my lecture notes and my syntax seems to be correct.
As part of the assignment, we are required to write all servlet code in processRequest(request, response). doPost and doGet both call this method.
My Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
ResultSet res = null;
ArrayList<String> bookIDs, bookTitles, bookAuthors;
DBUtil util = new DBUtil();
try {
res = BookDB.showBooks();
bookIDs = new ArrayList<String>();
bookTitles = new ArrayList<String>();
bookAuthors = new ArrayList<String>();
while(res.next()) {
bookIDs.add(res.getString("bookID"));
bookTitles.add(res.getString("title"));
bookAuthors.add(res.getString("author"));
}
request.setAttribute("IDHolder", bookIDs);
request.setAttribute("titlesHolder", bookTitles);
request.setAttribute("authorHolder", bookAuthors);
RequestDispatcher booksDispatcher = request.getRequestDispatcher("jspShowAll.jsp");
booksDispatcher.forward(request, response);
} catch (SQLException sqle) {
Logger.getLogger(ShowAllBooks.class.getName()).log(Level.SEVERE, null, sqle);
} catch (IOException iox) {
Logger.getLogger(ShowAllBooks.class.getName()).log(Level.SEVERE, null, iox);
} catch (ServletException ex) {
Logger.getLogger(ShowAllBooks.class.getName()).log(Level.SEVERE, null, ex);
}
}
ResultSet Creation (in a separate package):
public static ResultSet showBooks() throws SQLException {
ConnControl myConnPool=new ConnControl();
Statement s=null;
ResultSet res=null;
Connection myConn=myConnPool.connect();
String queryStm= "SELECT * FROM books;";
s=myConn.createStatement();
res = s.executeQuery(queryStm);
return res;
}
This method was copied and pasted from my previous web app, which works perfectly. The table and database are the same.
My JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
</head>
<body>
<c:forEach var="ids" items="${IDHolder}">
<p>${ids}</p>
</c:forEach>
<c:forEach var="titles" items="${titlesHolder}">
<p>${titles}</p>
</c:forEach>
<c:forEach var="authors" items="${authorHolder}">
<p>${authors}</p>
</c:forEach>
</body>
</html>
My Java Bean:
public class Book {
private int id;
private String title;
private String author;
public Book() {
}
public Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
}

After reviewing the logs and calling printStackTrace() for each exception thrown, I found I overlooked the simplest thing. I forgot to include the JSTL library! Now that I did, I ran my JSP again and it displayed properly.

Related

How to pass value from servlet to Dao class and perform operation and return List/ Arraylist to JSP page

Hello i am new at JSP developing and i need some help about JSP MVC programming I want to pass a value from Servlet and in Dao class i want to receive it in List function and perform operation and return th array to JSP page to use ..
Servlet
String company = "ABCD";
ObsBean ComName = new ObsBean();
ComName.setCompanyName(company);
dao.getComNotify(ComName);
Bean Class (ObsBean)
private String CompanyName;
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String CompanyName) {
this.CompanyName = CompanyName;
}
**DAO Class (ObsDao) **
public List getComNotify(ObsBean ComName) {
List<ObsBean> comNotify = new ArrayList<ObsBean>();
String cname = ComName.getCompanyName();//getting from bean class by getter
try {
String sql = "SELECT * from ObsNotify where notto='"+cname+"'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
ObsBean userNotify = new ObsBean();
userNotify.setNotifyName(rs.getString("notname"));
userNotify.setNotifyBy(rs.getString("notby"));
userNotify.setNotifyTo(rs.getString("notto"));
userNotify.setNotifyDate(rs.getString("notdate"));
comNotify.add(userNotify);
}
}
catch (Exception e) {
out.print("Error for User Notification - : "+e);
}
return comNotify;
}
IN JSP Page :
<%
ObsDao dao = new ObsDao();
List<ObsBean> ComNotify = dao.getComNotify();
for (ObsBean UserNotifi : ComNotify) {
.........
.........
}
%>
This is my complete code , but it shows error , why ?
ERRORS :
HTTP Status 500 – Internal Server Error
Type Exception Report
Message javax.servlet.ServletException: java.lang.NoSuchMethodError: com.ApexCorner.ModelDao.ObsDao.getComNotify()Ljava/util/List;
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: com.ApexCorner.ModelDao.ObsDao.getComNotify()Ljava/util/List;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:565)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Based on your code I assume that "notto" in your table is a company name, so if your sql statement is correct i would rewrite your code as follows:
public List getComNotify(ObsBean Comname) {
List<ObsBean> comNotify = new ArrayList<ObsBean>();
String COM = Comname.getcompanyname();
try {
String sql = "SELECT * from ObsNotify where notto='"+COM+"'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
ObsBean userNotify = new ObsBean();
int totalRows = rs.getRow();
userNotify.setNotifyName(rs.getString("notname"));
userNotify.setNotifyBy(rs.getString("notby"));
comNotify.add(userNotify);
}
}
catch (Exception e) {
out.print("Error for User Notification - : "+e);
}
return comNotify;
}
Comname is an object of the ObsBean type, you should retrieve the company name as a string before you can apply it to the sql statement, also note that java is case sensitive.
in JSP do something like
<%
ObsDao dao = new ObsDao();
ObsDao otherdao = new ObsDao();
otherdao.setCompanyName("My company")
List<ObsBean> ComNotify = dao.getComNotify(otherdao);
for (ObsBean UserNotifi : ComNotify) {
.........
.........
}
%>
In your Dao class, there should be getter method for CompanyName. So try following code:
STRING COM = Comname; ,<-- change this line to String COM=Comname.getCompanyName();

Calling bean method on jsp

I'm trying to call a method that connects that is on a Bean on a jsp file. The method will make a request to a RMI Server and return a string. At this point the method is just return a pre-defined string for test.
This is the bean method:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
}catch(Exception e){
e.printStackTrace();
}
return "Hello";
}
And this is the jsp code:
<h1>Projectos Actuais</h1>
<h2><%
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
try{
aux.getListProjects();
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
I'm guiding my self from another code, and the method is called like this. But in my case it's not working, and I can't figure out what is wrong.
Since you've tagged this struts2, assuming the getListProjects() is on the Action, in JSP use:
<s:property value="listProjects" />
If instead it is on a bean, declare the bean in the Action, and expose it through a getter:
private MyBean bean;
public MyBean getBean(){
return bean;
}
and in JSP use the dot notation:
<s:property value="bean.listProjects" />
P.S: always avoid Scriptlets (<% %>), they're evil.
Quoting and fixing your latest change on edit with some comments:
<h1>Projectos Actuais</h1>
<h2><%
try{
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
//Send result into generated HTML page with out.print!
out.print(aux.getListProjects());
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
As per the flow of Struts there should be field in beanclass with same name of getter & setter. For an example if your method name is getListPorjects then in your bean class there should be a private string variable name listprojects.
Also your method will update with following to way to return listprojects.
example:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
listprojects = "hello"
}catch(Exception e){
e.printStackTrace();
}
return listprojects;
}
Calling bean variable should be with ID over the JSP page.
<jsp:useBean id="aux" class="com.path.to.ConnectToRMIBean" scope="request" />
----
yours stuff
-----
<h1>${aux.listProjects}
hope this will help you. good luck
You are just missing the way <% %> and <%= %> are used in JSP. to print in <% %> tags use
<% out.println("Your results"); %>
and for <%= %>
<%=
String.valueOf(1+2);
%>

Printing text to webpage inside a Java method in JSP

I have been struggling to print text inside a Java method on a Java server page. Here are some ways I've attempted to print the text and errors thrown from the Tomcat (Version 7.0.56) compiler:
<%
class Base {
public void main() {
String Text = "ThisIsText";
out.println(Text);
}
}
%>
Error: Cannot refer to the non-final local variable out defined in an enclosing
scope
<%
class Base {
static Text;
public void main() {
String Text = "ThisIsText";
}
out.println(Text);
}
%>
Syntax error, insert "Identifier (" to complete MethodHeaderName
<%
class Base {
static Text;
public String text() {
String Text = "NewText";
return Text;
}
}
%>
<%text();%>
The method text() is undefined for the type Base_jsp
Is there any way to print HTML Text directly from a Java method in a JSP scriptlet?
The out variable is already inside a method - _jspService. So if you are going to use out, declare another method that takes out as parameter using declaration - <%! and then just call this method.
Use a declarative tag instead
<%!
class Base {
JspWriter out;
public Base(JspWriter out) {
this.out = out;
}
public void main() {
String Text = "ThisIsText";
try {
out.println(Text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
%>
<%(new Base(out)).main();%>
when you write something in <%%> the code between these tags is placed in methods so you cant declare function or class inside that tags because we cant have methods or class inside methods.
Similar,Also check

Run multiple function using JSP

i am new to web programming. i am trying to connect database using jsp with odbc. i have already written a java code for this. now i need to run on Tomcat server. so i choose JSP to do this job.But this is showing me void type not allowed here and erors. how to run this code using jsp. what are my mistakes. please help me to solve in this.
now this is my code
<%#page import="java.sql.*"%>
<%#page import="java.util.*" %>
<%#page import="java.util.logging.Level"%>
<%#page import="java.util.logging.Logger"%>
<%!
int i=0,j=0,k=0;
Connection conn=null;
Connection connection=null;
static int count=0;
String Cname[]=null;
String Title[]=null;
Statement stmt1=null;
ResultSet NumOfRows=null;
Statement stmt2=null;
ResultSet SpreadsheetValues=null;
Statement stmt3=null;
ResultSet rs3=null;
int RowCount;
//this static function required to connect excel database
static
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Exception in connecting to DB"+e.getMessage());
}
}
// connect Sql database
void ConnectSqlDB() {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ServerDB","sa","sqladmin");
System.out.println("MSSQL connected " +"<br>");
}catch(Exception e){
e.printStackTrace();
System.out.println("Exception in connecting to DB"+e.getMessage());
}
}
void ConnectExcelDB() throws SQLException{
conn=DriverManager.getConnection("jdbc:odbc:spreadsheetdb","","");
}
void getRowcount() throws SQLException{
stmt1=conn.createStatement();
String Qs1="select count(*) from [Sheet1$]";
NumOfRows=stmt1.executeQuery(Qs1);
while(NumOfRows.next()){
Rowcount=NumOfRows.getInt(1);
}
NumOfRows.close();
}
void getExcelValues() throws SQLException{
stmt2=conn.createStatement();
String Qs2="select * from [Sheet1$]";
SpreadsheetValues=stmt2.executeQuery(Qs2);
Cname=new String[Rowcount];
Title=new String[Rowcount];
while(SpreadsheetValues.next()){
// Assigning Spread sheet values to String array
Cname[j]=SpreadsheetValues.getString("Cname");
Title[j]=SpreadsheetValues.getString("Title");
j++;
}
}
SpreadsheetValues.close();
stmt2.close();
conn.close();
SpreadsheetValues=null;
stmt2=null;
conn=null;
}
%>
<%=ConnectSqlDB()%>
<%=ConnectExcelDB()%>
<%=getRowcount()%>
<%=getExcelValues()%>
When you are using a method in a JSP Expression, then your method should return a value. I see all of your methods have a return type of void i.e. returning nothing. Change your methods to return appropriate value.
NOTE
I understand that you are currently learning JSP etc but keep in mind that writing contorl/application logic in a view technology like JSP is a bad practice. Try reading the MVC pattern.
Do not use <%= %> (Expression) to invoke void methods and you should have to avoid Java code in JSP (read SO thread).
<%
ConnectSqlDB();
ConnectExcelDB();
getRowcount();
getExcelValues();
%>
<p>Total Records : <%=RowCount%>
<p>Array element at 0 index <%=name[0]%>
<%
for(String v:name)
{
out.println("<br/>" + v);
}
%>

JSP helper class for printing content

I have a question on code reuse in JSP. I have a JSP page example.jsp that issues a call to a database and gets the results. I have a java class HelperClass.java that accepts a record and prints out the different fields
response.getWriter().println
Now my JSP page has HTML as well and the problem is the content printed out by the HelperClass appears before the content in the JSP page. E.g.
<body>
This is the first line <br/>
HelperClass.printdata("second line");
</body>
output is
secondline This is the first line
Is this a known issue. What is the best way to design an HelperClass for a JSP page that prints content out to the page. Any pointers would be greatly appreciated.
Just do not use a "HelperClass to print data". This makes no sense. There you have EL for.
${bean.property}
That's all. Use a servlet to control, preprocess and postprocess requests. Use taglibs (e.g. JSTL) and EL to access and display backend data.
Here's a basic kickoff example of a Servlet which preprocesses the request before display in JSP:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Person> persons = personDAO.list(); // Get list of persons from DB.
request.setAttribute("persons", persons); // So it's available as `${persons}` in EL.
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response); // Forward to JSP for display.
}
Here, the Person is just a Javabean class which represents a real world entity.
public class Person {
private Long id;
private String name;
private String email;
private Integer age;
// Add/generate getters and setters here.
}
The PersonDAO#list() method just returns a List of Person objects from the DB:
public List<Person> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Person> persons = new ArrayList<Person>();
try {
connection = database.getConnection();
statement = connection.createStatement("SELECT id, name, email, age FROM person");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Person person = new Person();
person.setId(resultSet.getLong("id"));
person.setName(resultSet.getString("name"));
person.setEmail(resultSet.getString("email"));
person.setAge(resultSet.getInteger("age"));
persons.add(person);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return persons;
}
Map the servlet in web.xml on an url-pattern of /persons. The JSP is hidden in /WEB-INF so that nobody can access it directly without requesting the servlet first (else one would get an empty table).
Now, here's how persons.jsp look like, it uses JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach to iterate over a List and it uses EL to access the backend data and bean properties. The servlet has put the List<Person> as request attribute with name persons so that it's available by ${persons} in EL. Each iteration in c:forEach gives a Person instance back, so that you can display their proeprties with EL.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${persons}" var="person">
<tr>
<td>${person.name}</td>
<td>${person.email}</td>
<td>${person.age}</td>
</tr>
</c:forEach>
</table>
Call it by http://example.com/contextname/persons. That's all. No need for a "HelperClass to print data" ;) To learn more about JSTL, check Java EE tutorial part II chapter 7 and to learn more about EL, check Java EE tutorial part II chapter 5. To learn more about stuff behind PersonDAO, check this article.

Categories

Resources