set Java class Object values into JSP Page - java

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.

Related

Write to a text file from a JSP page

I can't write to a text file from JSP page. Please help me
public class UserIO {
public static void add(User user, String filepath) throws IOException {
File file = new File(filepath);
PrintWriter out = new PrintWriter(new FileWriter(file, true));
out.println(user.getEmailAddress() + "|" + user.getFirstName() + "|"
+ user.getLastName());
out.close();
}
}
<%# 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>Murach's Java Servlets and JSP</title>
</head>
<body>
<%# page import="business.*, data.*"%>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
User user = new User(firstName, lastName, emailAddress);
UserIO.add(user, path);
%>
<h1>Thank for joining our email list</h1>
<p>Here is the information that you entered</p>
<table cellspacing="5" cellpadding="5" border="1">
<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>
<p>
To enter another email address, click on the Back <br> button in
your browser or Return button shown <br> below.
</p>
<form action="EmailRegistrationStep1.html" method="post">
<input type="submit" value="Return">
</form>
</body>
</html>
My JSP page displays the correct User class data. But i want to write user's data on EmailList.txt.
I place EmailList.txt on WEB-INF/EmailList.txt. But nothing happend in EmailList.txt.
Please help me

JSP Display User Details not working at all

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title>Mail Registration</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="newcss.css">
<link rel="text/javascript" href="validateForm.js">
</head>
<body>
<div id="container">
<div id="header">
<h1>Online Book Store Mailing Registration</h1>
</div>
<div id="content">
<div id ="leftSide">
<p>Welcome to the Online Book Store Registration.
In order to join our mailing list you must complete the form. Then press the Submit button.</p>
</div>
<div id="rightSide">
<h2>Thanks for joining our email list</h2>
<h3>Here is the information that you entered:</h3>
<%# page import="user.User" %>
<% User user = (User) request.getAttribute("User");%>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<th align="right">First Name:</th>
<th>${user.getFirstName}</th>
</tr>
<tr>
<th align="right">Last Name:</th>
<th>${user.getLastName}</th>
</tr>
<tr>
<th align="right">Town:</th>
<th>${user.getTown}</th>
</tr>
<tr>
<th align="right">Country:</th>
<th>${user.getCountry}</th>
</tr>
<tr>
<th align="right">Email Address:</th>
<th>${user.getEmailAddress}</th>
</tr>
</table>
</form>
<br />
</div>
</div>
<div id="footer">
<h2>xxx</h2>
</div>
</div>
</body>
</html>
This is my first time working with JSP, I have to display user details that have been added to database. I have been looking for some time now at other questions asked here about displaying details and I have not found an answer yet.
I have java class called User.java in user Package.
If anyone could point me where I went wrong I would be thankful.
I have this in my servlet
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String town = request.getParameter("town");
String country = request.getParameter("country");
String emailAddress = request.getParameter("emailAddress");
// create the User object
User User = new User();
User.setFirstName(firstName);
User.setLastName(lastName);
User.setTown(town);
User.setCountry(country);
User.setEmailAddress(emailAddress);
MailDB.insert(User);
request.setAttribute("User", User);
String url = "/return_user_details.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
I suppose that your User class is like this :
Class User {
private String firstName;
private String lastName;
private String country;
.
.
.
/*generating getters & setters*/
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
}
So the problem you're having is here ${user.getFirstName} this will never work unless your attribute is named getFirstName which I don't think you did so to solve this issue you simply have to :
replace
${user.getFirstName} with ${user.firstName} , generally use the attribute name and not the getters and setters methods name.

error Neither BindingResult nor plain target object for bean name 'XXX' available as request attribute

I am getting this error, I am sure I have matched with the same name.
please help me
"Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute"
this is index.jsp
<%# include file="/WEB-INF/jsp/taglibs.jsp" %>
<div class="row">
<div class="panel panel-default">
<div class="panel-body">
<form:form action="dummy" method="post" commandName="userForm">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</form>
</div>
</div>
</div>
This is the file DummyControllor.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* #author ***
*/
#Controller
#RequestMapping("/dummy.htm")
public class DummyController extends AbstractGCEController {
protected static Logger logger = Logger.getLogger("controller");
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Model model) {
User userForm = new User();
model.addAttribute("userForm", userForm);
List<String> professionList = new ArrayList<>();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.addAttribute("professionList", professionList);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("userForm") User user, Map<String, Object> model) {
// implement your own registration logic here...
// for testing purpose:
System.out.println("username: " + user.getUsername());
System.out.println("profession: " + user.getProfession());
return "RegistrationSuccess";
}
}
The User.java
public class User {
private String username;
private String profession;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String profession) {
this.username = username;
this.profession = profession;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
}
the registrationSuccess.jsp
<%# 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>
</head>
<body>
</body><%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>Registration Success</title>
</head>
<body>
<div align="center">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Registration Succeeded!</h2></td>
</tr>
<tr>
<td colspan="2" align="center">
<h3>Thank you for registering! Here's the review of your details:</h3>
</td>
</tr>
<tr>
<td>User Name:</td>
<td>${userForm.username}</td>
</tr>
<tr>
<td>Profession:</td>
<td>${userForm.profession}</td>
</tr>
</table>
</div>
</body>
</html>
</html>

Error handling of a Custom Form Handler in ATG

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()

JSP form doesn't send to database. Using beans

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.

Categories

Resources