I'm inexperienced with Java and JSP. I created a form and it works the way it is supposed to, but I want to have some fun with it and have it reorder the results after the form is submitted. I'll include some images to show what I mean. I'm having a hard time searching for what I want and don't really know where to start. Any help will be appreciated.
Here is the form page:
Here is the results:
Here is what I want the results to look like (notice 'last' goes from 2 to 3, 'middle' from 3 to 5, 'item' from 4 to 2, and 'address' from 5 to 4):
Java File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowParameters extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
String title = "Reading All Request Parameters";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =
request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("STOP1\n");
doGet(request, response);
}
}
JSP file
<%# 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>Lab 3</title>
<style type="text/css">
.address {
height: 50px;
}
</style>
</head>
<body>
<body BGCOLOR="#FF0000">
<h1 align="center">Basic FORM</h1>
<form action="ShowParameters" method="post">
First Name: <input type="text" name="first"> <br>
Last Name: <input type="text" name="last" value="$"> <hr/>
Middle Name: <input type="text" name="middle"> <br>
Item: <input type="text" name="item"> <br>
Address: <input type="text" name="address" class="address"> <br>
Credit Card: <br>
<input type="radio" name="cardType" value="Visa">Visa <br>
<input type="radio" name="cardType" value="MasterCard">MasterCard <br>
Credit Card Number: <input type="text" name="cardNum"> <br><br>
<center><input type="submit" value="Submit Order"></center>
</form>
</body>
</html>
instead of creating html in servlet create a class to hold form input information like:
public class Person {
private String firstName;
private String midlleName;
private String lastName;
private String item;
private String address;
private String cardType;
private String cardNumber;
//getters and setters
}
in servlet create instance of Person class and set values then simply add person instance to request and forward to jsp.
Person person = new Person();
person.setFirstName(request.getParameter("first"));
//set other person values here
request.setAttribute("person", person);
request.getRequestDispatcher("filename.jsp").forward(request, response);
in jsp display like:
<table border="2">
<tr bgcolor="#FFAD00">
<th>Parameter Name</th>
<th>Parameter Value(s)</th>
</tr>
<tr>
<td>first</td><td>${person.firstName}</td>
</tr>
<tr>
<td>item</td><td>${person.item}</td>
</tr>
<tr>
<td>last</td><td>${person.midlleName}</td>
</tr>
<tr>
<td>address</td><td>${person.address}</td>
</tr>
<tr>
<td>middle</td><td>${person.lastName}</td>
</tr>
<tr>
<td>cardType</td><td>${person.cardType}</td>
</tr>
<tr>
<td>cardNum</td><td>${person.cardNumber}</td>
</tr>
</table>
Benefits:
easy to change the order as you like in html.(simply move the <tr/> elements)
No need of loop.
Follows Object-oriented programming (OOP) style of programming.
Rather than getting an enumeration of the parameters by request.getParameterNames you could have a string array of all the parameter names you expect with them in the order you want, and you could loop through that array like so:
String[] paramNames = { "item", "last", "first" };
for(int i=0; i<paramNames.length; i++)
{
out.print("<tr>");
out.print("<td>" + paramNames[i] + "</td>");
out.print("<td>");
String[] paramValues = request.getParameterValues(paramNames[i]);
...
...
out.print("</td>");
out.print("</tr>");
}
Please take note that one of the things you are not doing in your code is properly closing the cells with </td> and the rows with </tr>. You should really also close the LIs with </li>.
Related
I have an assignment for a one web page to show a table based on a selected date range (week, month or quarter) and a selected date. The data is from a read-only JSON file. A <select> control is filled with start dates using jQuery (not my preference but it works). Selecting a start date should cause a set of records to be chosen to be displayed in the <table> using JSTL <c:out>. I observe the correct data being requested by <c:forEach> from EventInfo#getDate() but no HTML code is written. I also failed to get JSTL to write <option> for the <select> control or even a <label>.
I am not sure what else to check to get this to work, such as pom.xml, file locations.
The java servlet and class files are in src/edjusterJsp/.
HomePage.jsp and actions.js are in WebContent/.
The data files is in WebContent/WEB-INF/.
Development is done in Eclipse/Luna on Windows Vista using Chrome to view.
HomePage.jsp
<%# 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 http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Joe Brown's Assignment for e|djuster</title>
<style>
.picklab
{
width: 10em;
}
.pickcontrol
{
width: 8em;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="actions.js"></script>
</head>
<body>
<h1>Joe Brown's Data Viewer</h1>
<c:set var="greeting" value="Hello World" />
<c:out value="${greeting}" />
<form action="JoeabServlet" method="post">
<label class="picklab">Period</label>
<select id="periodtype" class="pickcontrol pickler" required>
<option>select</option>
<option value="ptweek">Week</option>
<option value="ptmonth">Month</option>
<option value="ptquarter">Quarter</option>
</select><br>
<label class="picklab">Start Date</label>
<select id="periodrange" class="pickcontrol pickled">
<option>Please select parent</option>
</select><br>
<input type="submit" value="Update Summary" />
<table id="summaryz">
<thead>
<tr>
<th>Date</th>
<th>Type</th>
<th>Summary</th>
<th>Metric</th>
</tr>
</thead>
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
<c:forEach items="${eventinfos}" var="evinfo">
<tr>
<td><c:out value="${evinfo.getEventDate()}" /></td>
<td><c:out value="${evinfo.getEventType()}" /></td>
<td><c:out value="${evinfo.getEventSummary()}" /></td>
<td><c:out value="${evinfo.getEventSize()}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
</body>
</html>
JoeabServlet.java (portion)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String fillid = request.getParameter("fillid"); // ID of child DD to fill options for.
String periodsize = request.getParameter("periodsize");
String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for.
System.out.println("doGet() fillid: " + fillid + " periodsize: " + periodsize + " val: " + val);
String jsonText = "invalid";
if (0 == fillid.compareTo("periodrange"))
{
// Generate date options for a period type
List<String> dates = getPeriodRanges(val);
StringWriter sw = new StringWriter();
JSONValue.writeJSONString(dates, sw);
jsonText = sw.toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonText);
}
else if (0 == fillid.compareTo("summaryz"))
{
// Generate summary data for the table
System.out.println("doGet() matched summaryz");
List<EventInfo> evInfos = getEventInfos(periodsize, val);
request.setAttribute("eventinfos", evInfos);
request.getRequestDispatcher("/HomePage.jsp").forward(request, response);
}
}
actions.js (portion)
function fillSummaries(tableToFillID, ddTypeId, callingElement)
{
var tableau = $("#" + tableToFillID);
var dd = $('#' + ddTypeId);
console.debug("selected: " + $(callingElement).children(':selected'));
console.debug("selected text: " + $(callingElement).children(':selected').text());
sdate = $(callingElement).children(':selected').text();
console.debug("sdate : " + sdate);
$.getJSON('http://localhost:8080/edjusterJsp/JoeabServlet?fillid=' + tableToFillID + '&periodsize=' + dd.val() + '&val=' + sdate);
}
EventInfo.java (portion)
public class EventInfo
{
protected String event_date;
protected String event_type;
protected String event_summary;
protected String event_size;
public String getEventDate()
{
System.out.println("get event_date" + event_date);
return event_date;
}
}
I'm trying to get it to print out my Linked List from the user input. This code adds the object to the linked list as I can see it being printed to the console but they are not being printed to the page. Thanks.
Controller:
#Controller
#RequestMapping("/addr")
public class AddressController {
public Collection<Address> addresses = (Collection<Address>) Collections.synchronizedCollection(new LinkedList<Address>());
/* #RequestMapping("/new")
public String getAddressForm() {
System.out.println("Test");
return "addressProject/addressBook";
}
*/
#RequestMapping("/new")
public ModelAndView submitForm(String name, String email, String group, String phoneNumber, String address){
Address addr = new Address(name, email, group, phoneNumber, address);
addresses.add(addr);
ModelAndView modelandview = new ModelAndView("addressProject/addressBook");
modelandview.addObject("addresses", addr);
System.out.println("Address: name=" + addr.getName() + ", email=" + addr.getEmail() + ", group=" + addr.getGroup() + ", phoneNumber=" + addr.getPhoneNumber() + ", address=" + addr.getAddress());
return modelandview;
}
}
JSP:
<body>
<div class="container">
<form>
Name: <input type="text" name="name"><br>
<br/>
Email: <input type="text" name="email"><br>
<br/>
Group: <input type="text" name="group"><br>
<br/>
Phone Number: <input type="text" name="phoneNumber"><br>
<br/>
Address: <input type="text" name="address"><br>
<br/>
<input type="submit" />
</form>
</div>
<h2>Addresses v5</h2>
<c:forEach items="${addresses}" var="address">
<tr>
<td>${address}</td>
</tr>
You add the address to the model and not the list:
modelandview.addObject("addresses", addr);
should be:
modelandview.addObject("addresses", addresses);
jsp.
<table>
<c:forEach items="${addresses}" var="address">
<tr>
<td>${address}</td>
</tr>
</c:forEach>
<table>
And ensure you have declared the taglib directive at the top of your JSP file:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Hi, my problem is increasing the table row automatically. Actually, when I click GET button the product type and product name values are getting from database. Here, after getting those values, I will give another id based on that id again for values will come. But it was not setting in another row. Here is my java code and jsp:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
while(rs.next())
{
i++;
request.getSession().setAttribute("edit","success");
request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
request.getSession().setAttribute("strength", rs.getString("Strength_v"));
request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
request.getSession().setAttribute("uom", rs.getString("UOM_v"));
request.getSession().setAttribute("formE", rs.getString("FormE_v"));
request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
}
if(i==0)
{
request.getSession().setAttribute("edit", "fail");
}
}
catch(Exception e)
jsp code
<tr>
<td>
<input class="textfield-form-date-req" type="text" id="pro_type">
</td>
<%
if(editStatus =="success")
{
%>
<script type="text/javascript">
document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
</script>
<%
}
<td>
<input class="textfield-form-date-req" type="text" id="pro_id">
</td>
<%
if(editStatus =="success")
{
%>
<scripttype="text/javascript">
document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
</script>
<%
}
%>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
I have created a sample for you with ajax. It gets the data from the server side and append it , in the existing table.
The jar files I have used is ,
jackson-all-1.9.0.jar - to convert the java object to json format
servlet-api-2.4.jar - for servlet
My TableAppend.jsp will be,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//alert("DOM is ready");
});
function sendData() {
$.ajax({
type : 'POST',
url : "TableAppend",
data : "name=" + $('#name').val() + "&age=" + $('#age').val()
+ "&sid=" + new Date(),
dataType : 'html',
success : function(result) {
//alert("Result ::::>>> "+result);
if(result != null && $.trim(result) != "" && result != undefined){
var json = JSON.parse(result);
//alert(json.name);
//alert(json.age);
appendToTable(json.name, json.age);
}
},
error : function(e) {
alert('Error in Processing');
}
});
}
function appendToTable(name, age) {
var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
$('#mytable').append(tr);
}
</script>
</head>
<body>
Name :
<input type="text" id="name" name="name" /> Age :
<input type="text" id="age" name="age" />
<input type="button" value="Append to table" onclick="sendData()">
<br></br>
<br></br>
<br></br>
<table id="mytable" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>HumanBeing</td>
<td>25</td>
</tr>
<tr>
<td>Saideep</td>
<td>26</td>
</tr>
</tbody>
</table>
</body>
</html>
My TableAppend.java servlet will be,
public class TableAppend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TableAppend() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("UTF");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String json ="";
System.out.println("-----------------");
if(name != null && age != null){
TableAppendPojo obj = new TableAppendPojo();
obj.setName(name);
obj.setAge(age);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(obj);
System.out.println("json : "+json);
}
out.println(json);
}
}
Then java class will be,
public class TableAppendPojo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Note : Please apply the above logic in your code . In your case , you don't need to give the data from the UI. You retrieves the data from the database in the servlet.So please convert the retrieved data from the database to the json format and append it to the table.
Hope this helps.
In my application I have a username with a textbox, a checkbutton and a password. After entering the username into the textbox, if I click on check button it should search in the MySQL database for the username, if it is available it should display the message if not an other message should be displayed.
How do I do that with JSP?
i tried the follwing code:
<form method="post" name="frm_addUser" action="./adduserserver.jsp"><br><br>
<table width="500px;" border="0" cellpadding="5" cellspacing="1" bgcolor="#f8f8ff" bordercolor="#333366" align="center">
<tr>
<td bordercolor="Gainsboro"><font size="4">User ID</font></td>
<td bordercolor="Gainsboro"><input name="userid" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4"> </font></td>
<!--<td><input value="Check availability" onclick="" class="btn_checkavail" type="button"></td></tr>-->
</td>
<td>
<input type="submit" value="check" name="check"
onclick="" /></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Pass Word </font></td>
<td bordercolor="Gainsboro"><input name="password" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Confirm Password </font></td>
<td bordercolor="Gainsboro"><input name="confirmpassword" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<%
try{
String username=request.getParameter("username");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","sumith");
st=con.createStatement();
sqlQuery="select distinct username from usernameexist where username='"+username+"'";
rs=st.executeQuery(sqlQuery);
int count=0;
while(rs.next())
{
count++;
}
if(count>0)
{
out.println("<html>");
out.println("<head>");
out.println("<title>MeterDetailsPage</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center' color='red'>");
out.println("<tr color='red'>");
out.println("<td ><font size=4 color=red >username Already Exist</font></td>");
out.println("</tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
else
{
if(username!=null )
{
if(!username.equals(""))
{
//st.executeUpdate("insert into usernameexist(username) values('"+username+"')");
out.println("<html>");
out.println("<head>");
out.println("<title>username</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center'>");
out.println("<tr>");
out.println("<td ><font size=4 color=green><b>available </b></font></td>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
}
st.close();
con.close();
}
catch(Exception e){}
%>
</table>
</form>
</body>
</html>
Try This it will work,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Index Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
Enter Your Name: <input type="text" id="name" /><br>
Enter our user name :<input type="text" id="userName"><br>
Enter your Password :<input type="password" id="password"><br>
<input type="button" value="Submit" onclick="ajaxCall();">
<br>
<strong> Response</strong>:
<div id="ajaxGetUserServletResponse"></div><br>
</body>
</html>
Ajax file
function ajaxCall(){
var name = jQuery("#name").val();
var userName = jQuery("#userName").val();
var password= jQuery("#password").val();
alert(name);
alert(userName);
alert(password);
jQuery.ajax({
url : "GetUserServlet",
method: "GET",
type : "JSON",
data : "name="+name+"&userName="+userName+"&password="+password,// query parameters 1st
success : function(response){
$('#ajaxGetUserServletResponse').text(response);
}
});
}
Servlet
import java.io.IOException;
import java.util.ArrayList;
import javax.management.relation.RelationSupportMBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
userBean ub = new userBean();
String name = request.getParameter("name").trim();
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
System.out.println("name catched "+name);
System.out.println("username catched"+userName);
System.out.println("Password catched"+password);
ArrayList<userBean> list = new ArrayList<userBean>();
ub=new userBean();
ub.setName(name);
ub.setUserName(userName);
ub.setPassword(password);
list.add(ub);
response.setContentType("text/plain");
response.getWriter().print(list);
}
}
Pojo Class
public class userBean
{
private String name;
private String userName;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My scenario was little bit different you can alter the code in index.jsp and add the call on button "Check Availability" and bring the response from servlet.
check your table name in query
select distinct username from usernameexist where username='"+username+"'";
make sure your table is usernameexist
and
String username=request.getParameter("username");
here parameter is userid not username
so use
String username=request.getParameter("userid");
Your should do below :
Make sure that your jsp is passing all fields including checked field to servlet. You can do form post which has all attributes.
Your servlet should read all parameters and if check-box is checked then you put appropriate logic in servlet (like querying your MySQL db)
Return proper response from your servlet so that jsp can show appropriate message. You can keep messages in your jsp/js and based on flag you can show appropriate message to user.
you can use as follows.. attach jquery file in source code
<script src="jquery-1.9.1.js">
IN Form
<input type="text" name="userName" id="userName" onBlur="checkId(this.value)">
<span id="status"></span>
<script type="text/javascript">
function checkId(member_id)
{
$.ajax({
type: "POST",
url: "processAjax.jsp", /* The request will be processed in this file.. */
beforeSend: function() {
$("#divIdStatus").html("geting name...");
},
data: "member_id=" + member_id ,
success: function(msg) {
$("#divIdStatus").html(msg);
}
});
}
IN processAjax.js
String member_id = (request.getParameter("member_id")).trim();
if (member_id.equals("")) {
out.print("! This is Required");
} else {
ResultSet result = // check in database if any record with this user name;
if (result.next()) {
out.print("! Not Available");
} else {
out.print("OK..");
}
}
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.