jsp and getting attributes data - java

I am trying to display the note attribute that I saved into my request.setAttribute("entries", entries), but I can't access this data in my jsp and I can't figure it out. I've tried {note} , but that doesn't work.
This is my controller class:
while( rs.next() )
{
int id = rs.getInt("id");
String name = rs.getString("name");
String note = rs.getString("note");
String title = rs.getString("title");
Notes entry = new Notes(id, name, note, title);
entries.add(entry);
}
request.setAttribute("entries", entries);
request.getRequestDispatcher( "/WEB-INF/homework2/MyNotes.jsp" ).forward(
request, response );
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
}
}
This is my jsp view:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>MyNotes</title>
</head>
<body>
<p align="right">Hello, ${sessionScope.CurrentUser}! Logout</p>
<span>JOT My Notes | New</span>
<br>
<br>
<br>
<p>${note} </p>
<p>${applicationScope.entries.note},</p>
</body>
</html>

You already have your List in your request so:
Get the list with EL language
Iterate it to get all objects inside.
Then you can, (for example) put info a table:
<c:forEach items="${requestScope.entries}" var="entry">
<tr>
<td>ID: <c:out value="${entry.id}"/></td>
<td>Name: <c:out value="${entry.name}"/></td>
<td>Note: <c:out value="${entry.note}"/></td>
<td>Title: <c:out value="${entry.title}"/></td>
</tr>
</c:forEach>

Related

s:property not shown value Struts2

I have the following:
select name="nroPartido" style="color:#F5FFFA; background-color: #CC9900; font-weight: bold;">
<%
//se crean las listas
java.util.ArrayList<Partido> lista = Pronosticos.getInstance().getMiLista();
int nro = 0;
for (Partido p : lista) {
out.println("<option value=\"" + nro + "\">" + p.getLocal() +"-" +p.getVisitante() + "</option>");
nro++;
}
%>
</select>
So when I click the button the value of nro will be the value of the var nroPartido that is in the pronosticoAction class:
package acciones;
import com.opensymphony.xwork2.ActionSupport;
public class pronosticoAction extends ActionSupport {
private int nroPartido;
public String execute() {
System.out.println(nroPartido);
return SUCCESS;
}
public int getNroPartido() {
return nroPartido;
}
public void setNroPartido(int nroPartido) {
this.nroPartido = nroPartido;
}
}
Then what i want to do is print that number in a JSP page. So i do the following:
<%# 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>Detalles partido</title>
</head>
<body>
<h1>Chosen number</h1>
<h4>
You select number: <s:property value="nroPartido" />
</h4>
</body>
</html>
The problem is that it only shows this:
If someone could help me will be very useful
Thanks!
The following line is wrong, both syntactically and conceptually:
<s:property value="nroPartido"></<s:property>
there is an extra < , and the <s:property/> tag should self-closed, like a void element in XHTML:
<s:property value="nroPartido" />
That said, you should consider building your Select without using scritplets at all, by either iterating the options with <s:iterator>, or by using <s:select/> that is often the right way. You can find an example on how to do it in this answer.
EDIT
You also forgot to include the taglib directive for Struts2 tags:
<%# taglib prefix="s" uri="/struts-tags" %>
To use the Struts 2 tags on the view page, you must include a tag library directive. Typically, the taglib directive is <%# taglib prefix="s" uri="/struts-tags" %>. So the prefix for all the Struts 2 tags will be "s".
If you want to actually read the Struts 2 tag TLD file, you'll find it in the META-INF folder of the Struts 2 core jar.

Modifying existing object in one JSP file in another

I want to add another user in registration JSP file to my HashMap which is created in my homepage, but it seems the another HashMap is being created when I'm trying to register user.
How to access the HashMap from homepage JSP file in another?
This is my base class:
package com.jakub.spring;
import java.util.HashMap;
public class registeredUsers {
public HashMap<String, String> userSource;
public registeredUsers() {
userSource=new HashMap<String, String>();
}
public void register(String name, String password) {
userSource.put(name, password);
}
public String userExists(String user) {
String passwordFromSource = userSource.get(user);
if(passwordFromSource != null) {
return passwordFromSource;
}else
return "";
}
}
This is my homepage:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#CCCFFF">
<form method="post" action="validate.jsp">
<p align="left">Podaj login:</p>
<input type="text" name="name" />
<p align="left">Podaj haslo:</p>
<input type="text" name="password" />
<input type="submit" value="Zaloguj" />
</form>
Rejestracja
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
out.println("Dostepni uzytkownicy w systemie: \n");
out.print(registeredUsers.userSource.keySet());
%>
</body>
</html>
This is my registration page:
<%# page language="java" contentType="text/html; charset=ISO-8859-2"
pageEncoding="ISO-8859-2"%>
<!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-2">
<title>Konto utworzone</title>
</head>
<body>
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
registeredUsers.register(request.getParameter("name"),request.getParameter("password"));
out.print("Konto zostało utworzone");
out.print(registeredUsers.userSource.keySet());
%>
Powrót do strony glownej
</body>
</html>
Use ConcurrentHashMap instead of HashMap because it's in Application scope and that can be accessed simultaneously by multiple threads at a time and it results in ConcurrentModificationException.
Please have a look at Thread Safe JSP-Servlet Q&A

java web application mysql connection error

I am new in Java. My Java Environment is 1. Windows 8. 2. Mysql - 5.5.27. 3. Eclipse IDE for Java EE Devoper v-2. 5. Apache Tomcat v-7. 6. mysql-connector-java-5.1.28 bin rar 7. JDK 1.7. Now i want to connect with mysql from jsp file. I already add the mysql-connector to the library resource. But i can not connect. My code and error i given in the following.
Code: home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page language="java" import="java.sql.Connection"%>
<%# page language="java" import="java.sql.PreparedStatement"%>
<%# page language="java" import="java.sql.ResultSet"%>
<%# page language="java" import="java.sql.SQLException"%>
<%# page language="java" import="java.sql.DriverManager"%>
<%# page language="java" 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>Bengal Contact List | Home </title>
</head>
<body>
<%
Connection con = null;
try {
//Class.forName("com.mysql.jdbc.Driver");
String driver="com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/java_contact";
String user = "root";
String password = "";
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe);
}
catch(SQLException ex){
System.out.println(ex);
}
// Connection con;
// con=DBConnect.GetDBConnect();
String sql="SELECT * FROM contactsinfo";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
%>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Designation</td>
</tr>
<%
while(rs.next()){
%>
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Designation")%></td>
<%
}
%>
</table>
<h1>Now i am in Home Page.I want to show table information of Contact List.</h1>
</body>
</html>
Error:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:534)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
org.apache.jsp.home_jsp._jspService(home_jsp.java:96)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.
please find out where is the problem.
try to give null checks for rs.getInt("ID"), rs.getString("Name"), rs.getString("Designation"). NullPointerException is throwing there in the page.
Use the same for con object too.
first check your result is empty or not
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
else{
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Designation")%></td>
}
Firstly avoid using of scriptlets "<% %>" in JSP.
Secondly always do null check in your code, especially if you are using db result. You are heving null pointer exception in your JSP and it appear here;
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Designation")%></td>
Please try sthg like that;
-put this top on the file;
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and then
<c:if test="MAKE_YOUR_NULL_CHECK_HERE">
//Write your <td> here.
</c:if>
you must add port number of the Database(3306) port number, username and password and I have attached working code.. check and update the comment.....
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page language="java" import="java.sql.Connection"%>
<%# page language="java" import="java.sql.PreparedStatement"%>
<%# page language="java" import="java.sql.ResultSet"%>
<%# page language="java" import="java.sql.SQLException"%>
<%# page language="java" import="java.sql.DriverManager"%>
<%# page language="java" 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>Bengal Contact List | Home </title>
</head>
<body>
<%
Connection con = null;
try {
//Class.forName("com.mysql.jdbc.Driver");
String driver="com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/schemaname";
String user = "username";
String password = "password";
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe);
}
catch(SQLException ex){
System.out.println(ex);
}
// Connection con;
// con=DBConnect.GetDBConnect();
String sql="SELECT * FROM contactsinfo";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
%>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Designation</td>
</tr>
<%
while(rs.next()){
%>
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<%
}
%>
</table>
<h1>Now i am in Home Page.I want to show table information of Contact List.</h1>
</body>
</html>

reading and writing Persion Language(FARSI) Data

I using a JSP page to write into a file
Input Box in JSP will send some DATA
DATA
FARSI (Persian): INPUT_MSG = کد من کار نمی کند برای زبان فارسی.
<notification><myprojectid>256333859</myprojectid><mobile>123456789</mobile><uniqueid>ABCDEF565667DD</uniqueid><noation/><title>Push-Notification</title><message>INPUT_MSG</message><timestamp>20132611112245</timestamp></notification>
But in the file it has been stored in like given value
éï ÃÂ
àéçñ ÃÂÃÂ
à éÃÂï èñçà òèçàÃÂçñóÃ.
JSP PAGE Encoding For : SendMessage.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<form method="post" action="genMsgFile.jsp" name="testForm">
<span>Farsi Message : </span>
<input type="text" name="faMSg" />
<input type="submit" value="Push Message" />
</form>
</body>
</html>
JSP PAGE Encoding For : writeInfile.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.io.*"%>
<%#page import="java.util.*"%>
<%#page import="java.lang.*"%>
<html>
<body>
<%!
public void createFile(String msgLocation, String filepath, String msgTosend){
String fp = msgLocation + filepath;
// System.out.println("$$ PATH $$$ "+ fp);
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(fp));
pw.println(msgTosend);
pw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
%>
<%
String farMsg = request.getParameter("faMSg");
createFile(msgPATH,farsiFile,farMsg);
%>
</body>
</html>
What changes i should make in writeInfile.jsp so it will stored in readable format ???

PrintWriter output to jsp page inside body tag

This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.
This is my function
public Print(HttpServletRequest request,HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
};
This is where I call it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<%# page import="com.otrocol.app.*" %>
<%
Print(request, response);
%>
</body>
</html>
This is what I think the result is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
</body>
</html>
"haha"
This is what I want the response to be:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
"haha"
</body>
</html>
This is the error I get:
The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function.
Otherwise you are taking a second writer, and with buffering everything goes haywire.
Also as output already did happen do not set the content type in the function.
At the top of the JSP is a nice location, also for the imports.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
When having one writer the function would print at the correct spot in the body.
Nice intuition about the cause. BTW begin a function name with a small letter.
It's not a direct answer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSP from Java code.
Code example:
register.jsp
<%# taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<p>
<c:out value="${custom:printHaha()}" />
</p>
</body>
</html>
custom-tags.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>custom-taglib</shortname>
<uri>CustomTags</uri>
<function>
<name>printHaha</name>
<function-class>com.yourpackage.Tags</function-class>
<function-signature>
java.lang.String print()
</function-signature>
</function>
(...)
Tags.class
public class Tags {
public static String print() {
return "haha";
}
}
More info on Tags: official docs
I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp
now to print something on asp you can do this any number of ways
print by expression tag
use out (which is an object the server creates)
out.print("Blah...");
and more
to understand what happens to a jsp look into /work/catalina/blah.../
There are two pages. The first one is the Main Page. This one performs some
pseudo calcs.
Based on those calcs, either Success.jsp or Failure.jsp is returned.
This code will do what you wanted to have achieved.....
Even though as the others pointed out, there are more advanced techniques as of
late, still in order to dance, first you have to know the moves....
Primarily look at this
cObj.Print(request, response); in the 2nd jsp page.
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
</body>
</html>
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<!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>Failure!</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%cObj.Print(request, response);%>
</body>
</html>
Java Bean
package rustler.Beans;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Beany implements Serializable
{
public Beany()
{
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setJunk(String sStr)
{
//System.out.println("What a punk!");
custName = sStr;//"What a punk!";
}
public void Print(HttpServletRequest request,HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
public String prntJunk()
{
//System.out.println("What a punk!");
return custName;//"What a punk!";
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}

Categories