Expression language can't access getter methods - java

I have the following class users.java:
package org.XY;
public class user {
private String mail;
private String name;
private String org;
private String pw;
private String admin;
public user (String mail,String name,String org, String pw, String admin){
this.mail=mail;
this.name=name;
this.org=org;
this.pw = pw;
this.admin = admin;
}
public String getMail() {
return this.mail;
}
public String getName() {
return this.name;
}
public String getOrg() {
return this.org;
}
public String getPw() {
return this.pw;
}
public String getAdmin() {
return this.admin;
}
public String getUser() {
String u = this.mail + " | " + this.name + " | " + this.org + " | " + this.pw + " | Is admin:" + this.admin;
return u;
}
}
And the following jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import="org.XY" %>
<%# page import="java.util.List" %>
<%#page isELIgnored="false"%>
<html>
<head>
<title>myservlet</title>
</head>
<body>
<%--<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.getMail()}" /></td>
<td><c:out value="${user.getName()}" /></td>
<td><c:out value="${user.getOrg()}" /></td>
<td><c:out value="${user.getPw()}" /></td>
<td><c:out value="${user.getAdmin()}" /></td>
</tr>
</c:forEach>--%>
<%
List<user> users = (List<user>) request.getAttribute("users");
for (user user : users) {
%>
${user.mail}
<%
}
%>
<%
for (user user : users) {
out.println("<li>" + user.getPw());
}
%>
...
I want to create a table which contains all the data from the users.
As you can see, I tried using the ${user.mail} method with el.
Both give me an javax.el.PropertyNotFoundException: No public static field named [mail] was found on class [org.isse.sopro.user] error and an java.lang.NoSuchFieldException: mail error.
I already tried renaming the getter methods but it did not solv the issue.
Could someone tell me what I am diong wrong?
Regards
Andi
UPDATE:
Obviously it wasn't about the program itself, it was about maven. After a complete reload from Intellij, maven reloaded the project and everything worked fine.

You can not use ${user.mail} because of did not implements Serializable
You need change user class implements Serializable
public class user implements Serializable{
}
And you can use ${user.mail} instead of ${user.getMail()}
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.mail}" /></td>
</tr>
</c:forEach>

Try this
<%--<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.mail}" /></td>
<td><c:out value="${user.name}" /></td>
<td><c:out value="${user.org}" /></td>
<td><c:out value="${user.pw}" /></td>
<td><c:out value="${user.admin}" /></td>
</tr>
</c:forEach>--%>

Related

How to loop over a list of object in JSTL

enter image description hereI have the following list which is coming from a class via toString method .
I am passing the list in modelAndView object to jsp page.
Now I want to loop over the list and make a table in jsp Page.
Please guide.
List<LocationStats> allStates = [LocationStats{state='Fujian', country='Afghanistan', latestTotalCases=51526}, LocationStats{state='Guangdong', country='Albania', latestTotalCases=59438}] ;
////////////////////////// LocationStats.JAVA ///////////////////////////////////////
public class LocationStats {
private String state;
private String country;
private int latestTotalCases;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getLatestTotalCases() {
return latestTotalCases;
}
public void setLatestTotalCases(int latestTotalCases) {
this.latestTotalCases = latestTotalCases;
}
#Override
public String toString() {
return "LocationStats{" +
"state='" + state + '\'' +
", country='" + country + '\'' +
", latestTotalCases=" + latestTotalCases +
'}';
}
}
///////////////////////////// HomeController.java ////////////////////////
#RequestMapping("/")
public ModelAndView home() {
ModelAndView mv = new ModelAndView();
mv.addObject("location", coronaVirusDataService.getAllStates());
mv.setViewName("home.jsp");
return (mv);
}
/////////////////// home.jsp //////////////////////
<table>
<tr>
<th>state</th>
<th>country</th>
<th>latestTotalCases</th>
</tr>
<tr th:each="elements : ${location}">
<td th:text="${elements.state}"></td>
<td th:text="${elements.country}"></td>
<td th:text="${elements.latestTotalCases}">0</td>
</tr>
</table>
You should add taglib at the beginning of jsp file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Than you can write it in this way:
<table>
<tr>
<th>state</th>
<th>country</th>
<th>latestTotalCases</th>
</tr>
<c:forEach items="${location}" var="elements">
<tr>
<td>${elements.state}</td>
<td>${elements.country}</td>
<td>${elements.latestTotalCases}</td>
</tr>
</c:forEach>
</table>
You can also check if this 'location' is not empty, for example by printing it out:
<%=location%>
<table>
<tr>
<th>state</th>
<th>country</th>
<th>latestTotalCases</th>
</tr>
<c:forEach items="${location}" var="element">
<tr>
<td>${element.state}</td>
<td>${element.country}</td>
<td>${element.latestTotalCases}</td>
</tr>
</c:forEach>
</table>

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

jsp in another jsp struts 2

1st problem : i have a jsp in which there are two tabs ,for the second tab i have included the struts include tag. When i open the second tab and performs the action the second tab form values are not passing to the action.
2nd problem : in the select tag i have populate the list but it is coming as prepopulated means all the options are coming as selected="selected"
main jsp in which tabs are made
<!-- admin first tab starts here -->
<form action="saveRolesAndPermissions" method="post">
<table align="center">
<tr>
<td ><s:text name="FTID" ></s:text></td>
<td ><s:textfield id="FTID" name="ft_id">
</s:textfield></td>
<td><input type="button" value="validate" onclick="userPresent()"></td>
</tr>
</table>
<table>
<tr>
<td>First Name</td>
<td><input id="first_name" type="text" readonly onkeydown="return false"></td>
<td>Last Name</td>
<td><input id="last_name"
type="text" readonly onkeydown="return false"></td>
<td>Email-Id</td>
<td><input id="mail_id" type="text"
readonly onkeydown="return false"></td>
</tr>
</table>
<table align="center">
<tr>
<td><s:text name="ROLES"></s:text></td>
<td></td>
<td></td>
</tr>
<tr>
<td><s:text name="Available Roles"></s:text></td>
<td></td>
<td><s:text name="Assigned Roles"></s:text></td>
</tr>
<tr>
<td><s:select id="roles" name="availableRole"
multiple="true" list="availableRole"></s:select></td>
<td><input type="button" value="&gt" onclick="move_list_items('roles','assignedroles');"/><input
type="button" value="&lt" onclick="move_list_items('assignedroles','roles');"/></td>
<td><s:select id="assignedroles" name="assignedRole" multiple="true"
list="{}" >
</s:select></td>
</tr>
</table>
<br /> <br /> <br />
<table>
<tr>
<td><s:text name="Permissions"></s:text></td>
<td></td>
<td> </td>
</tr>
<tr>
<td><s:text
name="Available Permissions"></s:text></td>
<td></td>
<td><s:text name="Assigned Permissions"></s:text></td>
</tr>
<tr>
<td><s:select id="permissions" multiple="true"
name="availablePermission" list="availablePermission" headerValue=""></s:select></td>
<td><input
type="button" value="&gt" onclick="move_list_items('permissions','assignedpermissions');"/><br /> <input type="button"
value="&lt" onclick="move_list_items('assignedpermissions','permissions');" /></td>
<td><s:select id="assignedpermissions" multiple="true" name="assignedPermission"
list="{}" ></s:select></td>
</tr>
</table>
<br /> <br />
<table align="center" style="width: 25%;">
<tr>
<td><s:if test="hasActionMessages()">
<div class="welcome" style="list-style:none">
<s:actionmessage />
</div>
</s:if></td>
</tr>
</table>
<table>
<tr>
<td><s:submit
value="save"onclick="saveRole();return false;"></s:submit></td>
<td> <input type="button" name="close"
value="close" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</form>
<!-- second tab for modify roles -->
<div id="content02" class="content" >
<s:include value="../asp/aspAdminModify.jsp"></s:include>
</div>
<!-- /second tab ends here -->
included jsp
<form action="grantedRolesAndPermissions" method="post">
<table>
<tr>
<td><s:text name="FTID" ></s:text></td>
<td><s:textfield id="modify_FTID" name="modifyftid">
</s:textfield></td>
<td><s:submit
value="search" onclick="search();return false;"></s:submit>
</td>
</tr>
</table>
Bean for the first tab
private String ft_id;
private ArrayList<String> availableRole;
private ArrayList<String> availablePermission;
private ArrayList<String> assignedRole;
private ArrayList<String> assignedPermission;
//getters and setters
Action for the first tab
public class ASPadmin extends ActionSupport implements ServletRequestAware, ModelDriven<ASPAdminBean>{
/**
*
*/
private static final long serialVersionUID = 1L;
private AdminASPService aspService = new AdminASPService();
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
public CMTUser cmtuser;
private ASPAdminBean aspAdminBean = new ASPAdminBean();
//getters and setters
public String populateRolesAndPermissions() throws Exception
{
/*aspAdminBean=new ASPAdminBean();*/
aspAdminBean.setAvailableRole(aspService.getRolesList());
aspAdminBean.setAvailablePermission(aspService.getPermissionsList());
return SUCCESS;
}
public String saveRolesAndPermissions() throws Exception
{
User user = CMTUser.getUser(request);
String login = user.getUserId();
String[] temp = login.split("\\.");
String abcfinal = temp[0].substring(0, 1).toUpperCase()
+ temp[0].substring(1);
String deffinal = temp[1].substring(0, 1).toUpperCase()
+ temp[1].substring(1);
String name = abcfinal + " " + deffinal;
System.out.println("name ==============>" + name);
String id = aspService.saveRolesPermissions(aspAdminBean,name);
System.out.println("id=======>"+id);
if("Y".equals(id)){
addActionMessage("Record Inserted Successfully");
populateRolesAndPermissions();
return SUCCESS;
}
else{
return ERROR;
}
}
#Override
public String execute() throws Exception {
String url = request.getRequestURL().toString();
String[] actionArray = url.split("/");
String event = null;
String forward = SUCCESS;
for (int i = 0; i < actionArray.length; i++) {
event = actionArray[i];
}
System.err.println(event);
try {
if (event.equals("aspAdmin.action")) {
populateRolesAndPermissions();
}
}catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
#Override
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
#Override
public ASPAdminBean getModel() {
// TODO Auto-generated method stub
return aspAdminBean;
}
}
bean for second tab
public class ASPAdminModifyBean {
private String modifyftid;
private String aspmodifyassignedRole;
private String aspmodifyassignedPermission;
private String createddate;
private String createdby;
private String updateddate;
private String updatedby;
private String username;
private ArrayList<String> modifyavailableRole;
private ArrayList<String> modifyavailablePermission;
private ArrayList<String> modifyassignedRole;
private ArrayList<String> modifyassignedPermission;
//getters and setters
action for the second tab
public class ASPadminModify extends ActionSupport implements ServletRequestAware, ModelDriven<ASPAdminModifyBean> {
private AdminASPService aspService = new AdminASPService();
private GetRolePermissionListInt[] roleVO;
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
private ASPAdminModifyBean modify = new ASPAdminModifyBean();
GetRolePermissionListInt role;
//getters and setters for the above
public String grantRolesPermissions(){
System.out.println("enter the grant roles and permissions");
String tab2="modify";
boolean id;
HttpServletRequest request=getRequest();
HttpSession session=request.getSession();
session.setAttribute("tabs",tab2 );
role=aspService.getGrantedRolesAndPermissions(modify);
System.out.println("assigned roles===================>"+role.getAssignedRoles());
modify.setAspmodifyassignedRole(role.getAssignedRoles());
modify.setAspmodifyassignedPermission(role.getAssignedPermissions());
modify.setCreatedby(role.getCreatedBy());
modify.setCreateddate(role.getCreatedDate());
modify.setUpdatedby(role.getUpdatedBy());
modify.setUpdateddate(role.getUpdatedDate());
modify.setUsername(role.getUserName());
modify.setModifyftid(role.getFtid());
System.out.println("assigned permissions==============>"+role.getAssignedPermissions());
System.out.println("updated by=================>"+role.getUpdatedBy());
System.out.println("update date=================>"+role.getUpdatedDate());
System.out.println("created by===================>"+role.getCreatedBy());
System.out.println("created date=====================>"+role.getCreatedDate());
System.out.println("ftid=============================>"+role.getFtid());
System.out.println("user name===========================>"+role.getUserName());
System.out.println("ftid=============>"+role.getFtid());
if(role!=null){
return SUCCESS;
}else{
return ERROR;
}
}
#Override
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
}
#Override
public ASPAdminModifyBean getModel() {
// TODO Auto-generated method stub
return modify;
}
}
Well, the code is grown again :)
Start by :
changing your ArrayList declarations to List (in both beans, and regenerate getters and setters);
changing the way you get the Request, the Response and the Session, by using Struts2 Aware s interfaces (and their setters, with code inside)
Then if it still doesn't work, describe a little better what do you mean by "values are not passing to Action", and consider posting your interceptor stack config.
Hope that helps...

Function must be used with aprefix -jsp

I have similar problem asked here The function " " must be used with a prefix when a default namespace is not specified . But my context is different.
I have Spring web app which contains a jsp that gets arraylist of Objects created (using helping class) from controller and these object values are rendered in a table. My Controller, Jsp page, and Helping class are as follows
Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home( Model model) {
logger.info("Welcome home! the client locale is ");
ArrayList<TrendSign> ts=new ArrayList<TrendSign>();
for(int i=0;i<5;i++)
{
TrendSignDAO actor = new TrendSignDAO();
actor.setPhrase("phrase"+i);
actor.setHitCount(i);
actor.setWordCount(i);
actor.setCharCount(i);
ts.add(actor);
}
model.addAttribute("ts", ts );
return "home";
}
}
JSP Page is as follows:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>Phrase</th>
<th>hit count</th>
<th>wordcount</th>
<th>char count</th>
</tr>
</thead>
<tbody>
<c:forEach var="row" items="${ts}">
<tr class="odd gradeX">
<td><c:out value="${row.getPhrase()}"/></td>
<td><c:out value="${row.getHitCount()}"/></td>
<td><c:out value="${row.getWordCount()}"/></td>
<td><c:out value="${row.getCharCount()}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
Helping class
public class TrendSign {
private String phrase;
private int hitCount;
private int wordCount;
private int charCount;
public void setPhrase(String phrase)
{
this.phrase = phrase;
}
public String getPhrase()
{
return (this.phrase);
}
public void setHitCount(int hitCount)
{
this.hitCount = hitCount;
}
public int getHitCount()
{
return (this.hitCount);
}
public void setWordCount(int wordCount )
{
this.wordCount = wordCount;
}
public int getWordCount()
{
return (this.wordCount);
}
public void setCharCount(int charCount )
{
this.charCount = charCount;
}
public int getCharCount()
{
return (this.charCount);
}
public TrendSignDAO() {
// TODO Auto-generated constructor stub
this.phrase = "Phrase";
this.hitCount = 5;
this.wordCount = 1;
this.charCount = 1;
}
}
This working fine in my local host (java 6 Tomcat 6) But when I deployed to jelastic(java 6 Tomcat 6), getting the error WEB-INF/views/home.jsp(26,8) The function getPhrase must be used with a prefix when a default namespace is not specified. The url to access the web app at jelastic is http://lovedmusic.jelastic.servint.net/. Can anyone help me how to debug this?
Your DAO doesn't quite look like a DAO, but nevertheless, using JSP-EL, you should be able to access your getters without the method syntax. Just use the property name:
<td><c:out value="${row.phrase}"/></td>
<td><c:out value="${row.hitCount}"/></td>
<td><c:out value="${row.wordCount}"/></td>
<td><c:out value="${row.charCount}"/></td>

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