My controller wont print out a list on my JSP - java

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"%>

Related

Java Servlet put contents into input field in HTML after Servlet finished running [duplicate]

This question already has answers here:
How can I retain HTML form field values in JSP after submitting form to Servlet?
(2 answers)
Closed 5 years ago.
So basically I have retrieved data from a database, have the values I need stored in an array. But I am having trouble setting the values in an HTML input field. I have three fields Welsh name, English name, and gender. So I need the welsh input field in the form to hold the welsh word and so on. How would I do this?
The HTML code;
<html>
<head>
<title>Academi Gymraeg</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Academi Gymraeg</h1>
<h2>Modify Vocabulary</h2>
<div class="login-form">
<div class="login-elements">
<br>
<form action="instructorServlet" name="searchVocab" method="post">
<input type="hidden" name="type" value="searchVocab" />
Word:
<input type="text" name="word" class="inputBox" required><br><br>
Language:<br>
<select name="language" class="dropDown">
<option value="English" selected>English</option>
<option value="Welsh">Welsh</option>
</select><br><br>
<button type="submit" class="button" name="search" value="search"
>Search</button><br><br>
</form>
<form action="instructorServlet" name="modifyVocab" method="get">
<input type="hidden" name="type" value="modifyVocab" />
Welsh Name:
<input type="text" name="welshName" class="inputBox" required><br><br>
English Name:
<input type="text" name="englishName" class="inputBox" required><br><br>
Gender:<br>
<select name="gender" class="dropDown">
<option value="Masculine" selected>Masculine</option>
<option value="Feminine">Feminine</option>
</select><br><br>
<button type="submit" class="subButton" name="modifyEntry" value="Modify Entry"
>Modify Entry</button>
<button type="reset" class="subButton" name="modifyEntry" value="Modify Entry"
>Reset</button>
</form><br>
<form action="instructorServlet" name="backToMenu" method="post">
<input type="hidden" name="type" value="backToMenu" />
<button type="submit" class="button" name ="backToMenu" value="backToMenu"
>Back To Menu</button>
</form>
</div>
</div>
</body>
The servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String form = request.getParameter("type");
if ("searchVocab".equals(form)) {
String searchFor = request.getParameter("search");
if (searchFor != null) {
String word = request.getParameter("word");
String language = request.getParameter("language");
String values[] = database.searchFor(word, language);
response.getOutputStream().println("<script> window.location = \"modify-vocab.html\";</script>");
response.getOutputStream().println("<script> document.getElementById(\"welshName\").value = " + values[0] + ";\n"
+ " document.getElementById(\"englishName\").value = " + values[1] + ";\n"
+ " document.getElementById(\"gender\").value = " + values[2] + "; </script>");
}
}
The form reloads, however, the values aren't put into the input fields they just load blank.
Your servlet should build the values you need and forward them to the JSP view.
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// ... code to build your values
// Set the values
request.setAttribute("welshName", welshName);
request.setAttribute("englishName", englishName);
request.setAttribute("gender", gender);
// Ask the view to take care of the values
request.getRequestDispatcher("view.jsp").forward(request, response);
}
Your view.
<%
final String welshName = (String) request.getAttribute("welshName");
final String englishName = (String) request.getAttribute("englishName");
final String gender = (String) request.getAttribute("gender");
%>
Welsh Name: <input type="text" name="welshName" class="inputBox" value="<% out.print(welshName); %>"/>
English Name: <input type="text" name="englishName" class="inputBox" value="<% out.print(englishName); %>"/>
Gender:
<select name="gender" class="dropDown">
<option value="Masculine" <% out.print("masculine".equals(gender) ? "selected" : ""); %>>Masculine</option>
<option value="Feminine" <% out.print("feminine".equals(gender) ? "selected" : ""); %>>Feminine</option>
</select>

Why <form:errors> tag not showing the Error Messages inside <form:form> tag of Spring?

<form:errors> tag not showing Error Messages when I put it inside the <form:form> tag of Spring.
It shows Error Messages, If the <form:errors> tag is out of the <form:form> tag. I have printed the errors of the binding result and it shows the errors as below:
[Field error in object 'student1' on field 'lastname': rejected value []; codes [Size.student1.lastname,Size.lastname,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student1.lastname,lastname]; arguments []; default message [lastname],16,6]; default message [Size.student1.**lastname**]]
Note: If I place <form:errors> inside the <form:form> tag it is not working.
Here is the JSP code:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Contact Manager</title>
<style>
.errStyle{
color:red;}
</style>
</head>
<body>
<h2>${headerName}</h2>
<!-- This line shows the error messages of input binding exception. -->
<!--<form:errors path="student1.*" cssClass="errStyle"/> this line shows the error messages-->
<form:form method="post" action="/SampleTutorials/student/addBean.html">
<label>Last Names</label>
<input type="text" name="lastname"/>
<table>
<tr>
<td><label>First Name</label></td>
<td><input type="text" name="firstname"/></td>
</tr>
<tr>
<td><label>Last Names</label></td>
<td><input type="text" name="lastname"/>
<form:errors path="student1.lastname"> </form:errors>
</td>
</tr><!--**** Here it doesnt shows the error message -->
<tr>
<td><label>DOB</label></td>
<td><input type="text" name="dob"/></td>
</tr>
<tr>
<td><label>Email</label></td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td><label>Telephone</label></td>
<td><input type="text" name="telephone"/></td>
</tr>
<tr>
<td><label>Skillset</label></td>
<td>
<select multiple name="skillSet">
<option value="J2EE">J2EE</option>
<option value="J2SE">J2SE</option>
<option value="Spring">Spring</option>
<option value="Hibernate">Hibernate</option>
</select>
</td>
</tr>
<tr>
<td><label>Flat Number : </label></td>
<td><input type="text" name="address.flatNumber"/></td>
</tr>
<tr>
<td><label>Building Name : </label></td>
<td><input type="text" name="address.buildingName"/></td>
</tr>
<tr>
<td><label>City : </label></td>
<td><input type="text" name="address.city"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
The Controller Method:
#RequestMapping(value="/addBean.html", method = RequestMethod.POST)
public ModelAndView addContactFromBean(#ModelAttribute("student1") #Valid ContactBean student1, BindingResult result){
System.out.println("Inside addContactFromBean");
if(result.hasErrors()){ // this binding result checks for error
ModelAndView model = new ModelAndView("addStudent");
System.out.println("Some error occured in input.");
System.out.println(result.getAllErrors());
return model;
}
ModelAndView model = new ModelAndView("viewStudent");
System.out.println("Student Bean : "+student1.toString());
model.addObject("student1", student1);
System.out.println("View Name :->> "+model.getViewName());
return model;
}
The Spring Bean:
package com.springTut;
import java.util.List;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class ContactBean {
**#NotEmpty
private String firstname;**
**#Size( min=6, max=16, message="Size.student1.lastname")**
**private String lastname;**
private String email;
private String dob;
private Long telephone;
private List<String> skillSet;
private AddressBean address;
#Override
public String toString() {
return "ContactBean [firstname=" + firstname + ", lastname=" + lastname + ", email=" + email + ", telephone="
+ telephone + ", skillSet=" + skillSet + ", address=" + address + "--.]";
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public List<String> getSkillSet() {
return skillSet;
}
public void setSkillSet(List<String> skillSet) {
this.skillSet = skillSet;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getTelephone() {
return telephone;
}
public void setTelephone(Long telephone) {
this.telephone = telephone;
}
public AddressBean getAddress() {
return address;
}
public void setAddress(AddressBean address) {
this.address = address;
}
}
Binding and validation errors are registered in the model. The tag retrieves these errors from the model for display purposes. If the tag is nested inside a form:form tag the effective error key or path is the combination of the modelAttribute attribute in the form:form tag and the path you specify. In your case the modelAttribute is not explicit. Change your form as follows
<form:form method="post" action="/SampleTutorials/student/addBean.html" modelAttribute="student1">
<label>Last Names</label>
<input type="text" name="lastname"/>
<table>
<tr>
<td><label>First Name</label></td>
<td><input type="text" name="firstname"/></td>
</tr>
<tr>
<td><label>Last Names</label></td>
<td><input type="text" name="lastname"/>
<form:errors path="lastname"> </form:errors>
</td>
</tr>
<tr>
<td><label>DOB</label></td>
<td><input type="text" name="dob"/></td>
</tr>
<tr>
<td><label>Email</label></td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td><label>Telephone</label></td>
<td><input type="text" name="telephone"/></td>
</tr>
<tr>
<td><label>Skillset</label></td>
<td>
<select multiple name="skillSet">
<option value="J2EE">J2EE</option>
<option value="J2SE">J2SE</option>
<option value="Spring">Spring</option>
<option value="Hibernate">Hibernate</option>
</select>
</td>
</tr>
<tr>
<td><label>Flat Number : </label></td>
<td><input type="text" name="address.flatNumber"/></td>
</tr>
<tr>
<td><label>Building Name : </label></td>
<td><input type="text" name="address.buildingName"/></td>
</tr>
<tr>
<td><label>City : </label></td>
<td><input type="text" name="address.city"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>
Try to use the spring form properly for the model attribute object and the internal attributes i mean.
In your form
<form:form method="post" action="/SampleTutorials/student/addBean.html" attribute="student">
...
<td><form:input type="text" path="lastname"/>
<form:errors path="lastname"> </form:errors>
</td>
...
Let me know if in this case also fails

Re-ordering form results with Java/JSP

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>.

Servlet works only for one jsp form

I started experimenting a little bit with JSPs and Servlets.I have a project that lets you create an account and saves user data in Oracle db.I have created a form that allows the user to make a quick log-in,from the webapps header using email and password fields:
<jsp:include page="/includes/header.jsp" />
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value='sources/css/logIn.css'/>" type="text/css" rel="stylesheet" />
<form action="logIn" method="post">
<table>
<td>
<div id="header_logo">
<a href="<c:url value='/welcome.jsp'/>">
<img src="<c:url value='/sources/images/logo.jpg'/>">
</a>
</div>
</td>
<td>
Dont have an account?
</td>
<td>
JOIN! </td>
<td class="header_label" align="left">
<div id ="header_email">
email Address<br>
<input type="text" name="logEmailAddress" size="15" value="" class="header_input">
</div>
</td>
<td class="header_label" align="left">
<div id="header_password">
password<br>
<input type="password" name="logPassword" size="15" value="" class="header_input">
</div>
</td>
<td>
<div id="header_submit">
<br><input id="sub" type="submit" value="Log In">
</div>
</td>
</table>
</form>
I use post method to call the LogInServlet which looks like this:
package appUsers;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import business.User;
import data.UserDB;
public class LogInServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String logEmailAddress = request.getParameter("logEmailAddress");
String logPassword = request.getParameter("logPassword");
String url = "";
String message ="";
boolean isLogged=false;
//debug message
System.out.println("user input is emailaddress: " + logEmailAddress + " and password: " + logPassword);
if (logEmailAddress.length()==0 || logPassword.length()==0)
{
message = "Please provide your email address and password";
url = "/welcome.jsp";
}
User user = UserDB.selectUser(logEmailAddress);
if (user!=null)
{
isLogged = logPassword.equals(user.getPassword());
System.out.println(isLogged);
if(isLogged)
{
message = "You have succesfully loged in";
url = "/welcome.jsp";
}
else
{
message = "Invalid password";
url = "/welcome.jsp";
}
}
else
{
message = "No such account";
url = "/welcome.jsp";
}
HttpSession session = request.getSession();
session.setAttribute("user", user);
session.setAttribute("isLogged", isLogged);
request.setAttribute("message",message);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
The function that selects the user from the db:
User user = UserDB.selectUser(logEmailAddress);
is implemented like this:
public static User selectUser(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM USERS " + "WHERE EmailAddress = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
User user = null;
if (rs.next())
{
user = new User();
user.setFirstName(rs.getString("FirstName"));
user.setLastName(rs.getString("LastName"));
user.setEmailAddress(rs.getString("EmailAddress"));
user.setUserName(rs.getString("UserName"));
user.setPassword(rs.getString("Password"));
user.setUserType(rs.getString("Type"));
}
return user;
}
catch (SQLException e){
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
All of the above work fine together, user is selected from DB and confirms users account when logging in from header fields.
Yesterday i tried to create a similar form which is displayed in the main view calling the same Servlet using post method:
<jsp:include page="/includes/header.jsp" />
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value='sources/css/logIn.css'/>" type="text/css" rel="stylesheet" />
<div id="log">
<h1>Log in to Triptip</h1>
<form action="logIn" method="post">
<table>
<tr class="spaceBetweenRows">
<td class="user_label" align="left">
email Address<br>
</td>
<td>
<input class="user_input" type="text" name="logEmailAddress" value=" ">
</td>
</tr>
<tr>
<td class="user_label" align="left">
password<br>
</td>
<td>
<input class="user_input" type="password" name="logPassword" value="">
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<br>
<input id="sub" type="submit" value="Log In">
</td>
</tr>
</table>
</form>
</div>
</body>
Although i have confirmed that attributes Email and Password are being passed correctly to the Servlet the User user = UserDB.selectUser(logEmailAddress); returns null although the user exists!
Anybody have an idea of what might be going on? I tried implementing a new servlet but with the same outcome!Any help would be appreciated since i spent a lot of latenight hours trying to figure this thing out!
I'm using Windows 7 64, Netbeans, 7.4 Java 1.7.0-51, Tomcat 7 and Oracle 11.2XE
In your code, you set a default value that includes a space -
<input class="user_input" type="text" name="logEmailAddress" value=" ">
Based on your comment, you didn't notice that and simply added more characters. You don't need a default value so it could be,
<input class="user_input" type="text" name="logEmailAddress" value="">
or just
<input class="user_input" type="text" name="logEmailAddress">
As you have specified
<input class="user_input" type="text" name="logEmailAddress" value=" ">
so whenever you enter some value in the text-field like abc and when you do
String email = request.getParameter("logEmailAddress");
email shall give you initialspace+abc
so change
<input class="user_input" type="text" name="logEmailAddress" value=" ">
to
<input class="user_input" type="text" name="logEmailAddress" value="">

JSP, "User cannot be resolved to a type"

I am working through Murach's Java Servlets and JSPs
I am in chapter 4, when I load http:// button is pressed I get the error. Can anyone see what is causing the problem, I have all the files stored in tomcat/webapps/MailList. I have gone through this code for hours and cannot find any syntax causing the problem, just thinking another set of eyes would probably catch it. Or someone could explain it, any help is greatly appreciated, this is my first day messing with Servlets/JSPs and tomcat.
The join_email_list.html
<!DOCTYPE html>
<html>
<head>
<title>Chapter 4 - Email List application</title>
</head>
<body background="C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg" >
<h1>Join the Murach's mailing list</h1>
<p>To join the Murach's mailing list, enter your name and email address below.<br>
Then, click n the submit to recieve special offers.</p>
<form action="show_email_entry.jsp" method="get">
<table cellspacing="5">
<tr>
<td align="right" >First name</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td align="right">Last name</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td align="right">email address</td>
<td><input type="text" name="emailAddress"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
the show_email_list.jsp
<!DOCTYPE html public"-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Chapter 4 - Email List</title>
</head>
<body>
<%#page import="business.*, data.*" %>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User user = new User(firstName, lastName, emailAddress);
UserIO.addRecord(user, "..webapps/MailingList/UserEmail.txt");
%>
<h1>Thanks for joining</h1>
<table cellspacing="5">
<tr>
<td align="right">First Name: </td>
<td><%= user.getFirstName() %></td>
</tr>
<tr>
<td align="right">Last Name: </td>
<td><%= user.getLastName() %></td>
</tr>
<tr>
<td align="right">Email Address: </td>
<td><%= user.getEmailAddress() %></td>
</tr>
</table>
<form action="join_email_list.html" method="post">
<input type="submit" value="Return">
</form>
</body>
</html>
the User.java class
package business;
public class User {
private String firstName;
private String lastName;
private String emailAddress;
//this class defines a user, what we can get from a user to store
public User(){}
public User(String first, String last, String email){
firstName=first;
lastName=last;
emailAddress=email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
the UserIO.java class
package data;
import business.User;
import java.io.*;
public class UserIO { //the user io class adds the entered info to a txt file a.k.a psuedo db
public synchronized static void addRecord(User user, String fileName)
throws IOException{
PrintWriter out = new PrintWriter( //open the printwriter
new FileWriter(fileName, true)); //write to file
out.println(user.getEmailAddress()+"|"//write these things to file
+user.getFirstName()+"|"
+user.getLastName());
out.close();//close out to free resources
}
}
user is not in not accessible in the scope you are trying to, also
C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg
is not going to work
use
UserIO.addRecord(user, "MailingList/UserEmail.txt");
instead of
UserIO.addRecord(user, "..webapps/MailingList/UserEmail.txt");

Categories

Resources