I have searched every where, but can't find the help I need.
In my servlet I receive a String containing JSON data. These data are rows from a database and contains this:
[{"note_id":1,"title":"Homework","text":"Math ex. 15, 16, 17.","color":"Yellow","datetime":""}]
My problem is that I'm not able to show these data on a html table using jstl.
This is what I get:
(I'm getting stressed and can't figure out how to solve this).
Servlet code (post method):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.
.
.
String output = resp.getEntity(String.class);
System.out.println("* JSON string contains: * " + output); //prints the string with json data successfully
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<ArrayList<Note>> mapType = new TypeReference<ArrayList<Note>>() {};
ArrayList<Note> jsonToList = objectMapper.readValue(output, mapType);
request.setAttribute("allNotesOfUser", jsonToList);
RequestDispatcher rd = request.getRequestDispatcher("/Notes.jsp");
rd.forward(request, response);
}
jsp code (just the table part):
<table class="table table-striped">
<thead>
<tr>
<th> Id </th>
<th> Title </th>
<th> Text </th>
<th> Color </th>
<th> Date/Time </th>
</tr>
</thead>
<tbody>
<c:forEach items="${allNotesOfUser}" var="pp">
<tr>
<td><${pp.note_id}</td>
<td><${pp.title}</td>
<td><${pp.text}</td>
<td><${pp.color}</td>
<td><${pp.datetime}</td>
</tr>
</c:forEach>
</tbody>
</table>
Note entity:
#XmlRootElement
public class Note {
private int note_id;
private String title;
private String text;
private String color;
private String datetime;
public Note(int note_id, String title, String text, String color, String datetime){
this.note_id = note_id;
this.title = title;
this.text = text;
this.color = color;
this.datetime = datetime;
}
public Note(){
super();
}
public int getNote_id() {
return note_id;
}
public void setNote_id(int note_id) {
this.note_id = note_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
}
I don't know why, but I tried to insert <c:out value="" /> in my JSP code, so it looked like this:
<c:forEach items="${allNotesOfUser}" var="pp">
<tr>
<td><c:out value="${pp.note_id}" /></td>
<td><c:out value="${pp.title}" /></td>
<td><c:out value="${pp.text}" /></td>
<td><c:out value="${pp.color}" /></td>
<td><c:out value="${pp.datetime}" /></td>
</tr>
</c:forEach>
So now it's working:
Here is a link for some reference of the c:out
(Now i'll just continue and get stuck somewhere else T-T crying XD)
simple way you can send the Note entity to jsp page and print it. and you can also use JSON object bt bst way with JSON object you have to use java script. but you can also use com.google.gson.JSONObject for resolve this problem.
Related
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>
I am rewriting an IBM Teamroom application with graph db. I am wondering what is most efficient to gather and display collections of vertices?
E.g. I have:
public JsonJavaArray getProfiles() {
DFramedTransactionalGraph<DGraph> graph = GraphHelper.getProfilesGraph();
Iterable<Profile> all = graph.getElements(Profile.class);
JsonJavaArray json = new JsonJavaArray();
int count = 0;
for (Profile profile : all) {
JsonJavaObject jo = new JsonJavaObject();
jo.putString("name", profile.getName());
jo.putString("department", profile.getDepartment());
jo.putString("location", profile.getLocation());
json.put(count, jo);
count++;
}
return json;
}
So I can display it on an XPage as followed in a table:
<table class="table table-sm table-inverse">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<xp:repeat rows="30"
value="#{javascript:profiles.getProfiles();}" var="col"
indexVar="index">
<tr>
<td>
<xp:text escape="true"
value="#{col.name}">
</xp:text>
</td>
<td>
<xp:text escape="true"
value="#{col.department}">
</xp:text>
</td>
<td>
<xp:text escape="true"
value="#{col.location}">
</xp:text></td>
</tr>
</xp:repeat>
</tbody>
</table>
My profile class:
package com.wordpress.quintessens.graph.teamroom;
import org.openntf.domino.graph2.annotations.AdjacencyUnique;
import org.openntf.domino.graph2.builtin.DVertexFrame;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.frames.Property;
import com.tinkerpop.frames.modules.typedgraph.TypeValue;
#TypeValue("profile")
public interface Profile extends DVertexFrame {
#Property("$$Key")
public String getKey();
// optional fields
#Property("Name")
public String getName();
#Property("Name")
public void setName(String n);
#Property("Department")
public String getDepartment();
#Property("Department")
public void setDepartment(String n);
#Property("Location")
public String getLocation();
#Property("Location")
public void setLocation(String n);
#Property("Email")
public String getMail();
#Property("Email")
public void setMail(String n);
// real edges!
#AdjacencyUnique(label = "hasWritten", direction = Direction.IN)
public void addTopic(Post post);
#AdjacencyUnique(label = "hasWritten", direction = Direction.IN)
public void removeTopic(Post post);
#AdjacencyUnique(label = "hasWritten", direction = Direction.IN)
public Iterable<Post> getPosts();
}
All pretty "vanilla" and it works fine. Nevertheless I am wondering if I have chosen the correct approach or have I overlooked something (read: make the architecture simpler)?
i am trying to display a JSTL loop using list in a JSP code but it is not displying anything , neither it is giving any type of error nor any result
servlet code :
public void doGet(HttpServletRequest req , HttpServletResponse res) throws ServletException,IOException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter pw = res.getWriter();
String n=req.getParameter("action");
HttpSession ses = req.getSession();
String userid = ses.getAttribute("uname").toString();
if(n.equalsIgnoreCase("viewcart")) {
ses.setAttribute("cartlist", o.showCart(userid));
rd=req.getRequestDispatcher("/Register/cart.jsp");
rd.forward(req, res);
}
}
java function (showCart)
List<product> cart=new ArrayList<product>();
try {
conn = obj.connect();
String sql="it is working i checked in DB";
cs=conn.createStatement();
rs=cs.executeQuery(sql);
while(rs.next()) {
product p=new product();
p.setPname(rs.getString(1));
p.setQuantity(rs.getString(2));
p.setPrice(rs.getString(3));
p.setDtime(rs.getString(4));
p.setImg(rs.getString(5));
cart.add(p);
}
JSP code :
<c:forEach items="${cartlist}" var="product">
<tr>
<td>jbefjkw<c:out value="${product.pname}" /></td>
<td><c:out value="${product.quantity}" /></td>
<td><c:out value="${product.price}" /></td>
<td><c:out value="${product.dtime}" /></td>
<td>Rs <c:out value="${product.price}" /></td>
</tr>
product class :
public class product {
private String quantity;
private String dtime;
etc ..
public void setPname(String pname) {
this.pname=pname;
}
public String getPname() {
return pname;
}
etc and etc ....
the query is working in DB i checked multiple times .... the issue is guess with the forEach , it is unable to fetch the variables and the loop is not even running once
thnks in advance
Following contains the code inside my controller class , i am using the method public String getRegistrationForm(Map model) to return a jsp-page with a spring form on it , in this method i am setting userTab.setIsMfaEnabled(new Boolean(true)) , upon submitting the form the method :
public String registerUser(#ModelAttribute("user") UserTab user , BindingResult results , Map model)
is invoked as the handler method , but in this method the property 'isMfaEnabled' of user attribute set in the previous method is null and the line:System.out.println("user.getIsMfaEnabled() is nul"); is printing in the logs . Kindly tell me what is wrong here .
#Controller
#RequestMapping("/register")
public class RegisterUserController {
#Autowired
RegisterUserService registerUserService;
#RequestMapping(value = "/registeruser.action" , method = RequestMethod.POST)
public String registerUser(#ModelAttribute("user") UserTab user , BindingResult results , Map<String,Object> model){
System.out.println("executing regsiterUser ");
if(user == null)
System.out.println(", user is null");
if(results == null)
System.out.println("results is null");
UserTabValiator userTabValidator = new UserTabValiator();
if(user.getIsMfaEnabled() == null)
System.out.println("user.getIsMfaEnabled() is nul");
userTabValidator.validate(user, results);
if(results.hasErrors()){
return "registeruser";
}
try {
boolean val = registerUserService.isExistingUsername(user.getLoginName());
if(val){
System.out.println("username already exists");
model.put("message", "username already exists");
return "registeruser";
}
if(!val){
model.put("username", user.getLoginName());
model.put("message", "registration success ... ");
return "registrationsuccess";
}
} catch (Exception e) {
System.out.println("exception thrown");
e.printStackTrace();
return "errorpage";
}
return "errorpage";
}
#RequestMapping(value="/registeruser.view", method=RequestMethod.GET)
public String getRegistrationForm(Map<String,Object> model){
System.out.println("executing getRegistrationForm");
if(registerUserService == null)
System.out.println("register user service is null");
try{
ArrayList<MfaQuestion> allMfaQuestions = (ArrayList<MfaQuestion>) registerUserService.getAllMfaQuestions();
UserTab userTab = new UserTab();
userTab.setIsMfaEnabled(true);
model.put("user", userTab);
model.put("message", "register new user");
model.put("allMfaQuestions", allMfaQuestions);
return "registeruser";
}
catch(Exception e){
e.printStackTrace();
model.put("user", new UserTab());
model.put("message", "unable to get MFA questions");
return "registeruser";
}
}
}
UserTab Model Class :
package com.persistance.beans;
import java.util.Date;
public class UserTab {
private Integer userTabID;
private String loginName;
private String password;
private Date created;
private Date lastUpdated;
private Date lastLoginAttempt;
private Boolean isAccountLocked;
private Integer loginFailsNumber;
private Boolean isMfaEnabled;
private UserMfaMap userMfaMap;
public String toString(){
String str ="";
System.out.println("[userTabID , loginName , password");
return str;
}
public UserMfaMap getUserMfaMap() {
return userMfaMap;
}
public void setUserMfaMap(UserMfaMap userMfaMap) {
this.userMfaMap = userMfaMap;
}
public UserTab() {
super();
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Date getLastLoginAttempt() {
return lastLoginAttempt;
}
public void setLastLoginAttempt(Date lastLoginAttempt) {
this.lastLoginAttempt = lastLoginAttempt;
}
public Boolean getIsAccountLocked() {
return isAccountLocked;
}
public void setIsAccountLocked(Boolean isAccountLocked) {
this.isAccountLocked = isAccountLocked;
}
public Integer getLoginFailsNumber() {
return loginFailsNumber;
}
public void setLoginFailsNumber(Integer loginFailsNumber) {
this.loginFailsNumber = loginFailsNumber;
}
public Boolean getIsMfaEnabled() {
return isMfaEnabled;
}
public void setIsMfaEnabled(Boolean isMfaEnabled) {
this.isMfaEnabled = isMfaEnabled;
}
public Integer getUserTabID() {
return userTabID;
}
public void setUserTabID(Integer userTabID) {
this.userTabID = userTabID;
}
}
RegisterUser JSP page :
<form:form method="POST" action="${pageContext.request.contextPath}/register/registeruser.action" commandName ="user">
<table>
<tr>
<td><form:label path="loginName">UserName</form:label></td>
<td><form:input path="loginName" /></td>
<form:errors path="loginName" cssClass="error"/>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:input path="password" /></td>
<form:errors path="password" cssClass="error"/>
</tr>
<div id="question1" class="questionblock">
<tr>
<form:select path="userMfaMap.question1" >
<c:forEach items="${allMfaQuestions}" var="mfaQuestion">
<form:option value="${mfaQuestion.mfaQuestionId}">
<c:out value="${mfaQuestion.mfaQuestion}" />
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><form:label path="userMfaMap.answer1">Answer:</form:label></td>
<td><form:input path="userMfaMap.answer1" /></td>
<form:errors path="userMfaMap.answer1" cssClass="error"/>
</tr>
</div>
<div id="question2" class="questionblock">
<tr>
<form:select path="userMfaMap.question2">
<c:forEach items="${allMfaQuestions}" var="mfaQuestion">
<form:option value="${mfaQuestion.mfaQuestionId}">
<c:out value="${mfaQuestion.mfaQuestion}" />
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><form:label path="userMfaMap.answer2">Answer:</form:label></td>
<td><form:input path="userMfaMap.answer2" /></td>
<form:errors path="userMfaMap.answer2" cssClass="error"/>
</tr>
</div>
<div id="question3" class="questionblock">
<tr>
<form:select path="userMfaMap.question3">
<c:forEach items="${allMfaQuestions}" var="mfaQuestion">
<form:option value="${mfaQuestion.mfaQuestionId}">
<c:out value="${mfaQuestion.mfaQuestion}" />
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><form:label path="userMfaMap.answer3">Answer:</form:label></td>
<td><form:input path="userMfaMap.answer3" /></td>
<form:errors path="userMfaMap.answer3" cssClass="error"/>
</tr>
</div>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form:form>
Add code in the JSP form to bind the value of isMfaEnabled
<form:input path="isMfaEnabled" />
I have set a List of book and set to the request.setAttribute("booksa", allbooks); and in jsp i try to print the List in table but no values printed only the empty table.
This is my Servelet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
if (userPath.equals("/index")) {
// TODO: Implement category request
userPath = "/index";
}
else if (userPath.equals("/books"))
{
List<Book> allbooks = bookFacade.findAll();
userPath = "/books";
request.setAttribute("booksa", allbooks);
//System.out.print(allbooks);
}
else
{
}
String url = userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is my Book.jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table border="1">
<!-- column headers -->
<tr>
<td>ISBN</td>
<td>TITLE</td>
<td>PRICE</td>
<td>YEARS</td>
<td>LANGUAGE</td>
</tr>
<!-- column data -->
<c:forEach var="vehicle" items="${booksa}">
<tr>
<td><c:out value="${vehicle.isbn}" /></td>
<td><c:out value="${vehicle.title}" /></td>
<td><c:out value="${vehicle.price}" /></td>
<td><c:out value="${vehicle.years}" /></td>
<td><c:out value="${vehicle.languages}" /></td>
</tr>
</c:forEach>
</table>
</body>
But when i redirect to this page the view page source show like this
<!-- column data -->
<c:forEach var="vehicle" items="[ejb.Book[ isbn=SR001 ]]">
<tr>
<td><c:out value="" /></td>
<td><c:out value="" /></td>
<td><c:out value="" /></td>
<td><c:out value="" /></td>
<td><c:out value="" /></td>
</tr>
</c:forEach>
My Book class
public Book() {
}
public Book(String isbn) {
this.isbn = isbn;
}
public Book(String isbn, String title, double price, int years, String languages) {
this.isbn = isbn;
this.title = title;
this.price = price;
this.years = years;
this.languages = languages;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public String getLanguages() {
return languages;
}
public void setLanguages(String languages) {
this.languages = languages;
}
#XmlTransient
public Collection<Author> getAuthorCollection() {
return authorCollection;
}
public void setAuthorCollection(Collection<Author> authorCollection) {
this.authorCollection = authorCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (isbn != null ? isbn.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Book)) {
return false;
}
Book other = (Book) object;
if ((this.isbn == null && other.isbn != null) || (this.isbn != null && !this.isbn.equals(other.isbn))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejb.Book[ isbn=" + isbn + " ]";
}
}
values are coming to page but i don't know how to print please give me a help
Include the following line in your JSP, in the beginning. That should solve your issue
<%# taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
If you not added the jstl to your build path , just add from the references here ,
1.Adding jstl support
2.Getting JSTL to run within Tomcat and Eclipse
hope this helps!!