I am new to ATG. And I am trying to use RepositoryFormHandler of my own. But I am not able to do the validations on the form.
Here is my .java file:
public class MyLoginBean extends RepositoryFormHandler {
private String logname;
private String logpwd;
private String message;
public String getLogname() {
return logname;
}
public void setLogname(String logname) {
this.logname = logname;
}
public String getLogpwd() {
return logpwd;
}
public void setLogpwd(String logpwd) {
this.logpwd = logpwd;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean handleLogname(DynamoHttpServletRequest pRequest,
DynamoHttpServletResponse pResponse) throws ServletException,
IOException {
boolean tf=true;
if(logname.isEmpty() || logname==null)
{
tf=false;
setMessage("User name can't empty");
}
System.out.println("inside logname");
return tf;
}
public void handleFormException(DropletFormException exception,
DynamoHttpServletRequest request, DynamoHttpServletResponse response) {
// TODO Auto-generated method stub
super.handleFormException(exception, request, response);
}
}
And here is my .jsp file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/dspTaglib" prefix="dsp" %>
<dsp:importbean bean="/atg/dynamo/droplet/ErrorMessageForEach"/>
<dsp:importbean bean="/dynamusic/MyLoginBean"/>
<!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>Custom Login</title>
</head>
<body>
<dsp:form style="color:white">
<table style="background:#3b5998">
<tr>
<td>
<ul>
<dsp:droplet name="ErrorMessageForEach">
<dsp:param bean="MyLoginBean.formExceptions" name="exceptions"/>
<dsp:oparam name="output">
<li>
<dsp:valueof param="message"/>
</li>
</dsp:oparam>
</dsp:droplet>
</ul>
</td>
</tr>
<tr>
<td>
User Name:
</td>
<td>
Password:
</td>
</tr>
<tr>
<td>
<dsp:input type="text" name="logname" bean="MyLoginBean.logname"> </dsp:input>
</td>
<td>
<dsp:input type="password" name="logpwd" bean="MyLoginBean.logpwd"> </dsp:input>
</td>
<td>
<dsp:input type="submit" bean="MyLoginBean.login"> </dsp:input>
</td>
</tr>
</table>
</dsp:form>
</body>
</html>
This is all I've tried so far and still trying something else.
Please suggest the solution for it and also tell me the mistakes, if any, in the code pasted here.
Don't override handleFormException
Instead of using setMessage, use ATG's built-in behavior. All form handlers inherit a Vector of form exceptions from the GenericFormHandler superclass. To add an error, use:
addFormException(new DropletException("Your error message"));
Then, at the end of your method, call:
return checkFormRedirect(getSuccessUrl(), getFailUrl(), pRequest, pResponse);
This checks if any form exceptions have been added, and if so, redirects to the failUrl, otherwise redirects to the successUrl.
By convention, you should name your form handler *FormHandler, for example ProfileFormHandler, BillingInfoFormHandler, PaymentInfoFormHandler etc.
Hope this helps. See http://docs.oracle.com/cd/E22630_01/Platform.1002/apidoc/atg/droplet/GenericFormHandler.html#getFormExceptions()
Related
I want to set Java class Object values into JSP Page.
My Test_Object code
public class Test_Object {
public String email;
public String first_name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
}
My test.jsp page
<%#page import="test.io.Test_Object"%>
<%# 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>TEST</title>
</head>
<body>
<form action="loginServlet" method="post">
<table>
<tr>
<td>First Name :
<td><input type="text" value="" name="txtFirstname"
value='<%=((Test_Object) request.getAttribute("reqObj")).getFirst_name()%>' /></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="txtEmail"
value='<%=request.getParameter("email")%>' /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
My servlet code
String jb = "{\"email\":\"test#xyz.com\",\"fname\":\"test01\"}";
JSONObject jsonObject = new JSONObject(jb);
Test_Object obj = new Test_Object();
obj.email=jsonObject.getString("email");
obj.first_name=jsonObject.getString("fname");
request.setAttribute("reqObj", obj);
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
view.forward(request, response);
But when i redirect to test.jsp page there is no value display in TextBox.
I am using Eclipse Mars 2 with Java.
The problem might be in the way you are dispatching the request. In your Servlet you are dispatching the request to the /otn.jsp page. But you are trying to read the properties of the object you put in the request scope in the test.jsp page.
So you have to do the following:
In the Servlet code:
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
In the test.jsp page change the input elements as follows:
<input type="text" value="${reqObj.first_name}" name="txtFirstname"/>
<input type="text" value="${reqObj.email}" name="txtEmail" />
I am using here Expression Language with the assumption that you are using one of the current web containers such as Tomcat version 7 and later.
Some minor comments:
Why are you creating the JSONObject eventhough you are not doing anything useful with it in your Servlet code?
When you define Java types (classes, interfaces, ...) use camelcase instead of underscore in the names: use TestObject instead of Test_Object and firstName instead of first_name. Here you'll find naming conventions for Java.
Objective: If I type an email id, in the html form it has to send the request to jsp where it does the logic and has to print(in the html form) whether the email is available or not. I have the following code. Please do help me which part I am doing wrong.
CreateAccount.html
<!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">
<script type="text/javascript" src="emailStore.js"></script>
</head>
<body onload="process()">
<form name="login">
<table align="center">
<tr>
<td>Email*</td>
<td><input type="text" name="userinput" id="userinput"/></td>
<td><div id = "underInput"></div></td>
</tr>
<tr>
<td>Password*</td>
<td><input type="password" name="pswrd" /></td>
</tr>
<tr>
<td>Repeat Password*</td>
<td><input type="password" name="pswrd1" /></td>
</tr>
<tr>
<td>First Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Last Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="text" name="userid" /></td>
</tr>
</table>
<div style="text-align: center">
<input type="submit" value="Create Account"/>
</div>
</form>
</body>
</html>
The ajax part in a javascript file. emailStore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequest()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new ActiveXObject();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("can't create that object");
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
email = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "emailStore.jsp?email=" + email, true);
xml.onreadystatechange = handle.ServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span style = "color:blue">' + message + '</span>';
setTimeout('process()',1000);
}
else
{
alert('Something went Wrong');
}
}
}
And the logic part in a jsp file- emailStore.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList"%>
<!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>
<%
String email = request.getParameter("userinput");
ArrayList<String> emails = new ArrayList<String>();
emails.add("something#gmail.com");
if (emails.contains(email)) {
out.println("Email already taken!");
} else {
out.println("Email available");
}
%>
</body>
</html>
I would advise you of the following:
Use library JQuery;
Use Servlet instead of the JSP;
Keep a list in the session;
Do not use a tabular layout. Instead, use div- layers, and cascading style sheets.
Here is a simple example, front- end part is ..
<head>
...
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var input=$('#userinput').val();
$.get('ActionServlet',{userinput:input},function(responseText) {
$('#underInput').text(responseText);
});
});
});
</script>
...
</head>
<body>
...
<form id="form1">
...
Email
<input type="text" id="userinput"/>
<input type="button" id="submit" value="Submit"/>
<br/>
<div id="underInput">
</div>
...
</form>
...
</body>
</html>
..and server side -
...
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ActionServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String answer = "Something went Wrong";
String userinput = request.getParameter("userinput").toString();
HttpSession httpSession = request.getSession(true);
if(httpSession.isNew()) {
httpSession.setAttribute("sessionVar", new ArrayList<String>());
}
List<String> arrayList = (ArrayList<String>)httpSession.getAttribute("sessionVar");
if(userinput != null && !userinput.equals("")) {
if(arrayList.contains(userinput)) {
answer = "Email already taken!";
} else {
arrayList.add(userinput);
answer = "Email available";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(answer);
}
...
i have a jsp page that gets two parameters 1 for adding another for viewing.this jsp page is named as sucessAdmin.jsp. I have another jsp page admin1.jsp which calls sucessadmin.jsp. admin1.jsp has a form view and add.so if i press the view button it calls sucessAdmin.jsp and displays datas. when i press the add button then it displays a form to enter data but its not adding values to the mysql DB. when i call the same page again,it does not add the data.Please tell me where i have mistake
this is the bean
package sucessAdmin;
import java.sql.*;
import java.io.*;
import java.util.*;
public class sucessAdmin {
private String question;
private String answer;
private String questionNo;
private String opt1;
private String opt2;
private String opt3;
private String opt4;
public sucessAdmin()
{
}
public void setQuestion(String question)
{
this.question=question;
}
public String getQuestion()
{
return question;
}
public void setAnswer(String answer)
{
this.answer=answer;
}
public String getAnswer()
{
return answer;
}
public void setQuestionNo(String questionNo)
{
this.questionNo=questionNo;
}
public String getQuestionNo()
{
return questionNo;
}
public void setOpt1(String opt1)
{
this.opt1=opt1;
}
public String getOpt1()
{
return opt1;
}
public void setOpt2(String opt2)
{
this.opt2=opt2;
}
public String getOpt2()
{
return opt2;
}
public void setOpt3(String opt3)
{
this.opt3=opt3;
}
public String getOpt3()
{
return opt3;
}
public void setOpt4(String opt4)
{
this.opt4=opt4;
}
public String getOpt4()
{
return opt4;
}
public Vector getDetails()
{
int x=0;
Vector v= new Vector();
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/Ontest";
Connection con=DriverManager.getConnection(url,"root","spanwave");
ResultSet rs=null;
Statement st=con.createStatement();
rs=st.executeQuery("select * from questions");
String quer="SELECT * FROM questions";
rs=st.executeQuery(quer);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol=0;
NumOfCol=rsmd.getColumnCount();
System.out.println("Query Executed!! No of Colm="+NumOfCol);
while(rs.next())
{
for(int i=1;i<NumOfCol+1;i++)
{
if(i==NumOfCol)
{System.out.print(rs.getString(i));System.out.println();}else
System.out.print(rs.getString(i)+" ");
v.addElement(rs.getString(i));
}
}
}
catch(Exception e)
{
System.out.println(e);
}
return v;
}
public void addDetails(String question,String opt1,String opt2,String opt3,String opt4,String questionNo,String answer)
//public void addDetails()
{
int qnNo=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/Ontest";
Connection con=DriverManager.getConnection(url,"root","spanwave");
ResultSet rs=null;
qnNo=Integer.parseInt(questionNo);
PreparedStatement ptst=con.prepareStatement("insert into questions values(?,?,?,?,?,?,?)");
ptst.setString(1,question );
ptst.setString(2,opt1 );
ptst.setString(3,opt2 );
ptst.setString(4,opt3 );
ptst.setString(5,opt4 );
ptst.setInt(6, qnNo);
ptst.setString(7,answer);
ptst.executeUpdate();
int NumOfCol=0;
System.out.println("Query Executed!! No of Colm="+NumOfCol);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
this is the calling page
<%# 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>
<jsp:useBean id="admin" scope="request" class="admin.adminBean">
<jsp:getProperty property="userId" name ="admin"/>
</jsp:useBean>
<jsp:useBean id="sucessAdmin" scope ="request" class="sucessAdmin.sucessAdmin"></jsp:useBean>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><jsp:getProperty property="userId" name ="admin"/></title>
</head>
<body bgcolor="pink">
<form action="details.jsp" method="get">
view questions<input type="radio" name="details" value="view"><br>
edit questions
<input type="radio" name="details" value="edit"><br>
add questions
<input type="radio" name="details" value="add"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
this is the called page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><jsp:useBean id="sucessAdmin" scope ="request" class="sucessAdmin.sucessAdmin">
</jsp:useBean>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Details</title>
</head>
<body>
<%String input; %>
<%=input=request.getParameter("details") %>
<%if (input.equals("view")) {
%><%Vector v; %>
<%v=(Vector)sucessAdmin.getDetails();
out.println(sucessAdmin.getDetails()); }
%><%
if(input.equals("add"))
{out.println("addds");
%>
<form method="POST" action="details.jsp">
<table>
<tr>
<td>question<input type="text" name="question" value="" /></td>
</tr>
<tr>
<td>opt1<input type="text" name="opt1" value="" /></td>
</tr>
<tr>
<td>opt2<input type="text" name="opt2" value="" /></td>
</tr>
<tr>
<td>opt3<input type="text" name="opt3" value="" /></td>
</tr>
<tr>
<td>opt4<input type="text" name="opt4" value="" /></td>
</tr>
<tr>
<td>questionNumber<input type="text" name="questionNo" value="" /></td>
</tr>
<tr>
<td>answer<input type="text" name="answer" value="" /></td>
</tr>
</table><br><input type="hidden" name="details"/>
<br><input type="submit" name="submit" value="submit"/>
<%sucessAdmin.addDetails("question","opt1","opt2","opt3","opt4","questionNo","answer");%>
</form>
<%out.println("adding");}
%>
</body>
</html>
replace <%sucessAdmin.addDetails("question","opt1","opt2","opt3","opt4","questionNo","answer");%>
with
<%
String question = request.getParameter("question");
String opt1= request.getParameter("opt1");
String opt2 = request.getParameter("opt2");
String opt3 = request.getParameter("opt3");
String opt4 = request.getParameter("opt4");
String questionNo = request.getParameter("questionNo");
String answer = request.getParameter("answer");
if(question!=null && opt1!=null && opt2 != null
opt3!=null && opt4 !=null && questionNo!=null && answer!=null)
{
sucessAdmin.addDetails(question,opt1,opt2,opt3,opt4,questionNo,answer);
}
%>
Try this and let's hope it works..
Its my jsp page from where i'm sending the data to javabean:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<%#taglib uri="/struts-dojo-tags" prefix="sx" %>
<%#page session="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<sx:head parseContent="true" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Set the Leaves </title>
<script language="JavaScript" src="../Advance_Academic_ERP/css/Ck_Effect.js"></script>
<link rel="stylesheet" type="text/css" media="all"
href="../Advance_Academic_ERP/css/jsDatePick_ltr.min.css" />
<script type="text/javascript"
src="../Advance_Academic_ERP/css/jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:("fromDate"),
dateFormat:"%d-%m-%Y"
});
new JsDatePick({
useMode:2,
target:("toDate"),
dateFormat:"%d-%m-%Y"
});
};
</script>
<script type="text/javascript">
function display(val) {
var o = document.getElementById('name1');
var b = document.getElementById('leaveNo1');
(parseInt(val) == '5' || parseInt(val)=='6')? o.style.display = 'block' : o.style.display = 'none';
(parseInt(val) == '5' || parseInt(val)=='6')? b.style.display = 'block' : b.style.display = 'none';
}
</script>
</head>
<body>
<s:form action="LeaveSetterAction" name="leave" validate="true">
<s:select label="Type Of Holiday/Leave*"
headerKey="-1" headerValue="Select Type"
list="#{'1':'National Holidays', '2':'Weekly Holidays', '3':'Local Holidays', '4':'Situational Holidays', '5':'Seek Leaves', '6':'Personal Leaves'}"
name="leaveType" id="leaveType" onchange="display(this.value);"/>
<table id="name1" style="display: none;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
</table>
<table id="leaveNo1" style="display: none;">
<tr>
<td>No Of Alloted Leaves</td>
<td><input type="text" name="leaveNo" id="leaveNo"></td>
</tr>
</table>
<s:textfield name="fromDate" label="From date*" key="fromDate" id="fromDate"></s:textfield>
<s:textfield name="toDate" label="To date*" key="toDate" id="toDate"></s:textfield>
<s:textfield name="difference" label="Duration" key="difference" id="difference" readonly="readonly"></s:textfield>
<s:textarea name="desc" label="Description*" key="desc" onmouseover="setDifference(this);"></s:textarea>
<s:submit align="center"></s:submit> <s:reset align="center"></s:reset>
</s:form>
</body>
</html>
Its mine javabean page where i'm supposed to get the data:
package abc.Model;
public class SetLeave {
String leaveType;
String name;
String leaveNo;
String fromDate;
String toDate;
String difference;
String desc;
public String getLeaveType() {
return leaveType;
}
public void setLeaveType(String leaveType) {
this.leaveType = leaveType;
}
public String getName() {
System.out.println(name);
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLeaveNo() {
System.out.println(leaveNo);
return leaveNo;
}
public void setLeaveNo(String leaveNo) {
this.leaveNo = leaveNo;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getDifference() {
return difference;
}
public void setDifference(String difference) {
this.difference = difference;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
I'm using javascript on some textfields which are getting null values
Please help me out.
Thanks in advance.
<s:textfield name="difference" label="Duration" key="difference" id="difference" disabled="true"></s:textfield>
In this field you have disabled="true", so the value that would be send to the Model/Bean would be null obviously.
<s:textfield name="difference" label="Duration" key="difference" id="difference" disabled="true"></s:textfield>
<s:hidden name="difference"/>
If you want to send value to your bean. If you still get error, then reply.
Ok , Get this done and reply..
<table id="name" style="display: none;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
</table>
<table id="leaveNo" style="display: none;">
<tr>
<td>No Of Alloted Leaves</td>
<td><input type="text" name="leaveNo" id="leaveNo"></td>
</tr>
</table>
You are using same id's for table and textfield in both the above cases change the id of table to name1 and leaveNo1 and try. I guess this is the only problem.
Your solution is there in the below code paste it and enjoy.
<s:textfield name="difference" label="Duration" key="difference" id="difference" readonly="readonly"></s:textfield>
When i submit data from my form it doesnt save to the database... no error occurs...
i can retrieve from the database but not save to it...
heres the code:
test.jsp
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.util.*" %>
<%# page import="my.beans.StudentBean"%>
<jsp:useBean id="studentData" scope="request"
class="my.beans.StudentDataBean"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Words View</title>
<style type="text/css">
table, tr, td, th
{
text-algn: center;
font-size: .9em;
border: 3px groove;
padding: 3px;
background-color: #eee9e9;
}
</style>
</head>
<body>
<h1>Student List</h1>
<table border="1">
<tr>
<th>
<h4>First Name</h4>
</th>
<th>
<h4>Last Name</h4>
</th>
<th>
<h4>Comment</h4>
</th>
<th>
<h4>Email</h4>
</th>
</tr>
<%
ArrayList<StudentBean> studentList = studentData.getStudentList();
Iterator studentListIterator = studentList.iterator();
StudentBean student;
while (studentListIterator.hasNext()){
student = (StudentBean) studentListIterator.next();
%>
<tr>
<td><%= student.getFirstName()%></td>
<td><%= student.getLastName()%></td>
<td><%= student.getComment()%></td>
<td><%= student.getEmail()%></td>
</tr>
<% }
%>
</table>
</body>
</html>
formTest.jsp
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id = "student" scope = "page"
class = "my.beans.StudentBean" />
<jsp:useBean id = "studentD" scope = "page"
class = "my.beans.StudentDataBean" />
<html>
<form method="post" action="test.jsp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Login</title>
</head>
<body>
<jsp:setProperty name = "student" property = "*" />
<% // start scriptlet
if (student.getFirstName() == null
|| student.getLastName() == null
|| student.getEmail() == null
|| student.getComment() == null) {
%>
Enter forename, surname, student ID and email address to <br />
register.<br />
<br />
<table border="1">
<tr>
<td>First Name:</td>
<td>
<input type="text" name="first" />
</td>
</tr>
<tr>
<td>Last Name:</td>
<td>
<input type="text" name="last" />
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input type="text" name="email" />
</td>
</tr>
<tr>
<td>Comment:</td>
<td>
<input type="text" name="comment" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</body>
</form>
<% } else {
studentD.addStudent(student);
%>
<jsp:forward page="test.jsp" />
<%
}
%>
</html>
And then my beans...
StudentBean.java
package my.beans;
public class StudentBean {
/***********\
* Globals *
\***********/
private String firstName;
private String lastName;
private String comment;
private String email;
public StudentBean(){
}
// get/set for First Name
public void setFirstName(String f) {
firstName = f;
}
public String getFirstName(){
return firstName;
}
// get/set for Last Name
public void setLastName(String l) {
lastName = l;
}
public String getLastName(){
return lastName;
}
// get/set for comment
public void setComment(String co) {
comment = co;
}
public String getComment(){
return comment;
}
// get/set for Email
public void setEmail(String em) {
email = em;
}
public String getEmail(){
return email;
}
}
StudentDataBean.java
package my.beans;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import java.util.ArrayList;
import com.sun.rowset.CachedRowSetImpl; // CachedRowSet implementation
public class StudentDataBean {
private CachedRowSet rowSet;
// construct TitlesBean object
public StudentDataBean() throws ClassNotFoundException, SQLException{
// load the MySQL driver
Class.forName("com.mysql.jdbc.Driver");
// specify properties of CachedRowSet
rowSet = new CachedRowSetImpl();
rowSet.setUrl("jdbc:mysql://localhost:3306/test");
rowSet.setUsername("root");
rowSet.setPassword("");
// obtain list of titles
rowSet.setCommand("SELECT firstName, lastName, email, comment FROM guests" );
rowSet.execute();
} // end StudentDataBean constructor
// return an ArrayList of StudnetBeans
public ArrayList<StudentBean> getStudentList() throws SQLException{
ArrayList<StudentBean> studentList = new ArrayList<StudentBean>();
rowSet.beforeFirst(); // move cursor before the first row
// get row data
while (rowSet.next()){
StudentBean student = new StudentBean();
student.setFirstName(rowSet.getString(1));
student.setLastName(rowSet.getString(2));
student.setEmail(rowSet.getString(3));
student.setComment(rowSet.getString(4));
studentList.add( student );
} // end while
return studentList;
} // end method getStudentList
// insert a Student in student database
public void addStudent(StudentBean student) throws SQLException
{
rowSet.moveToInsertRow(); // move cursor to the insert row
// update the three columns of the insert row
rowSet.updateString( 1, student.getFirstName() );
rowSet.updateString( 2, student.getLastName() );
rowSet.updateString( 3, student.getEmail() );
rowSet.updateString( 4, student.getComment() );
rowSet.insertRow(); // insert row to rowSet
rowSet.moveToCurrentRow(); // move cursor to the current row
try{
rowSet.acceptChanges();
}
catch(Exception e){
System.out.println("Exception caught at line 67: " + e);
}
}
}
Problem solved: it was an error with my java conventions not matching.