JSP Display User Details not working at all - java

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

Related

Using ftl display list from POST method

Sorry for my english!
I am new to Spring and FTL.
I want to display firstName and lastName using <#list template, but I could not recognize any sequences in my POST method, could some one please explain to me. Again I am a newbie and please don't judge me if I don't understand what I should. I am using CUBA STUDIO 6.8 and IDEA. Also I'm working on this task in portal module
This is how I add firstName and lastName to database using my ftl form and Portal Controller:
#GetMapping("/add")
public String add(Model model){
PersonPojo personPojo = new PersonPojo();
model.addAttribute("personPojo", personPojo);
return "add";
}
#PostMapping("/add")
public String save(Model model, #ModelAttribute("personPojo") PersonPojo personPojo){
String firstName = personPojo.getFirstName();
String lastName = personPojo.getLastName();
PersonPojo newPerson = new PersonPojo(firstName, lastName);
Person standardEntity = metadata.create(Person.class);
standardEntity.setFirtName(newPerson.getFirstName());
standardEntity.setLastName(newPerson.getLastName());
dataManager.commit(standardEntity);
return "redirect:/allPersons";
}
My ftl form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" name="person">
First Name: <input type="text" name="firstName"> <br>
Last Name: <input type="text" name="lastName"> <br>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
<input type="submit" value="Create">
</form></body>
</html>
Thank you!
So, If someone is interested i will post my solution here:
#RequestMapping(value = "/allPersons", method = RequestMethod.GET)
public String getPersons(Model model) {
LoadContext loadJohn = new LoadContext(John.class);
loadJohn.setQueryString("select u from test6$John u");
model.addAttribute("users", dataService.loadList(loadJohn));
return "list";
}
And the ftl should look like this:
The problem i faced next was I did not know I have to check list for null. !"" does that
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>Person List</h3>
Add Person
<br><br>
<div>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<#list users as show>
<tr>
<td>${show.firstName!""}</td>
<td>${show.lastName!""}</td>
</tr>
</#list>
</table>
</div>
</body>
</html>
I hope this will help to people like me.
Also, If someone knows how to delete and update data please share.
Thanks!

Bind a list of radio buttons with Spring and Thymeleaf

my problem is that I need to get the radio buttons that are selected in HTML file and use it in the PostMapping.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Do Test Excercise</title>
<script language="javascript">
</script>
</head>
<body>
<h1>Do Test Exercise</h1>
<form method="POST">
<span align="left" th:each="question : ${exercise.getQuestions()}">
<p valign="top" th:text="${question.text}">Text</p>
<tr align="left" th:each="solution : ${question.getSolutions()}">
<input width="5%" type="radio" th:name="${question.question_ID}" th:text="${solution.text}"
th:value="${solution.text}"/><BR>
</tr>
</span>
<input type="submit" value="Submit">
</form>
</body>
</html>
However I don't know how to get that values for the radio buttons and save it in a array of String
#GetMapping("doTest/{post}/{exercise}")
public String doTest(Model model, #PathVariable String exercise) {
model.addAttribute("exercise", exercisesDAO.getExerciseByType(exercise, "Test"));
return "exercise/doTestExercise";
}
#PostMapping("doTest/{post}/{exercise}")
public String doTest(#RequestParam(value = "solution") String[] solution, #PathVariable String post, #PathVariable String exercise, RedirectAttributes redirectAttributes) {
exercisesDAO.solve(exercise, solution, "admin", "Test");
redirectAttributes.addAttribute("post", post);
redirectAttributes.addAttribute("exercise", exercise);
return "redirect:/showMark/{post}/{exercise}";
}
Thanks
You need to change the name of your inputs from th:name="${question.question_ID}", to th:name="${'solution['+ question.question_ID + ']'}". After that, you need to change your controller, so that instead of an array of Strings, it will receive a HashMap, where you will get for each id, the chosen solution.
Form
<form method="POST" th:action="#{doTest/${post.id}/${exercise.id}}">
<span align="left" th:each="question : ${exercise.getQuestions()}">
<p valign="top" th:text="${question.text}">Text</p>
<tr align="left" th:each="solution : ${question.getSolutions()}">
<input width="5%" type="radio" th:name="${'solution['+ question.question_ID + ']'}" th:text="${solution.text}" th:value="${solution.text}"/><BR>
</tr>
</span>
<input type="submit" value="Submit">
</form>
Controller
#PostMapping("doTest/{post}/{exercise}")
public String doTest(#RequestParam(value = "solution") HashMap<String, String> solutions, #PathVariable String post, #PathVariable String exercise, RedirectAttributes redirectAttributes) { ... }

set Java class Object values into JSP Page

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.

How to populate a simple table with thymeleaf in spring mvc

I have a list of objects and I want to display the values of those objects in a table using thymeleaf, this is what I have so far:
Here is my controller class that adds my list of objects:
#RequestMapping(value = "/showTableWithValues", method = RequestMethod.GET)
public String showTableWithValues(Model model)
{
//list with Persons
ArrayList<Persons> personsList=
new ArrayList<Persons>();
personsList= this.getListOfPersons();
model.addAttribute("list", personsList);
return "showTableWithValues";
}
This is my .html file where i want to show my values:
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1>
Show Values
</h1>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Cost</th>
<th>Mins to prepare</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:each="persons : ${list}">
</tr>
</tbody>
</table>
</body>
</html>
And my Person.java class:
public class Person {
private String name;
private String last_name;
private String nickname;
.....get,setters and constructor
}
You are missing your <TD> tags providing the template which fields to print where. See the Iteration Basics of the documentation
Add <td> tags under <th> and then use the <td th:text="${persons.ID}"></td> respectively to display the relevant data in the table.

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