Servelet set attribute doesn't print in jsp - java

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

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>

Problems Creating Login/Registration Page with servlets/MySQL in Eclipse

So here is my issue. I am working on a school project and I am basically hitting a wall. I cannot get my RegistrationServer to work at all. I can get it to run, and correctly display the Registration.jsp that it is built behind, but none of the information is entered into the database at all. In fact, I cannot even tell if that is where exactly I am failing. Here is the code for the Registration function:
Registration.jsp
<%# 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">
<style>
div.container {
//width: 100%;
// border: 1px solid gray;
// padding:5px;
}
table, th, td {
//border: 1px solid black;
}
.textright{float:right;padding:10px}
</style>
<title>Registration</title>
<script>
function validate()
{
var firstname = document.form.firstname.value;
var lastname = document.form.lastname.value;
var username = document.form.username.value;
var password = document.form.password.value;
var address = document.form.address.value;
var contact = document.form.contact.value;
if (firstname==null || firstname=="")
{
alert("First Name can't be blank");
return false;
}
else if (lastname==null || lastname=="")
{
alert("Last Name can't be blank");
return false;
}
else if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if (password==null || password=="")
{
alert("Password can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (address==null || address=="")
{
alert("Address can't be blank");
return false;
}
else if (contact==null || contact=="")
{
alert("Contact can't be blank");
return false;
}
}
</script>
</head>
<body bgcolor="#D3D3D3">
<form name="form" action="RegistrationServlet" method="post"
onsubmit="return
validate()">
<td style="float:left"><image
src="file:///G:/College/Winter%202018/CSC%20363/Computer%20logo.png"
width="100px" height="100px"></image></td>
<p style="float:right"><b> ${members[3]} <br> CSC 363<br>Final Project</b>
</p>
<td style="clear:float"></td>
<p style="align-text"left">Team</p>
<p style="float:left">${members[0]} <br> ${members[1]} <br>
${members[2]} </p>
<td style="close:float"></td>
<table style="float:right">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact</td>
<td><input type="text" name="contact" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></input>
</tr>
</table>
</form>
</body>
</html>
RegistrationServlet
package com.mvc.RegistrationServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.Bean.RegistrationBean;
import com.mvc.Dao.RegistrationDao;
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegistrationServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String[] members = new String[4];
members[0] = "Jamie W.";
members[1] = "Evan D.";
members[2] = "Tim D.";
members[3] = "Hardware Plus";
request.setAttribute("members", members);
request.getRequestDispatcher("/Registration.jsp").forward(request,
response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
RegistrationBean registrationBean = new RegistrationBean();
registrationBean.setFirstName(firstName);
registrationBean.setLastName(lastName);
registrationBean.setUserName(userName);
registrationBean.setPassword(password);
registrationBean.setAddress(address);
registrationBean.setContact(contact);
RegistrationDao registrationDao = new RegistrationDao();
String userRegistered = registrationDao.registrationUser(registrationBean);
if(userRegistered.equals("SUCCESS"))
{
request.getRequestDispatcher("/ProductSalesPage.jsp").forward(request,
response);
}
else
{
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/RegistrationServlet.jsp").forward(request,
response);
}
}
}
RegistrationDao
package com.mvc.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mvc.Bean.RegistrationBean;
import com.mvc.RegistrationDB.RegistrationDB;
public class RegistrationDao {
public String registrationUser(RegistrationBean registrationBean)
{
String firstName = registrationBean.getFirstName();
String lastName = registrationBean.getLastName();
String userName = registrationBean.getUserName();
String password = registrationBean.getPassword();
String address = registrationBean.getAddress();
String contact = registrationBean.getContact();
Connection con = null;
PreparedStatement preparedStatement = null;
try
{
con = RegistrationDB.createConnection();
String query = "insert into
users(SlNo,firstName,lastName,userName,password,address,contact) values
(NULL,?,?,?,?,?,?)";
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
preparedStatement.setString(3, userName);
preparedStatement.setString(4, password);
preparedStatement.setString(5, address);
preparedStatement.setString(6, contact);
int i= preparedStatement.executeUpdate();
if (i!=0)
return "SUCCESS";
}
catch(SQLException e)
{
e.printStackTrace();
}
return "Oops.. Something went wrong there..!";
}
}
RegistrationDB
package com.mvc.RegistrationDB;
import java.sql.Connection;
import java.sql.DriverManager;
public class RegistrationDB {
public static Connection createConnection()
{
Connection con = null;
String url = "jdbc:mysql#localhost:3306/project/users";
String username = "root";
String password = "password";
try
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
System.out.println("Printing connection object "+con);
}
catch (Exception e)
{
e.printStackTrace();
}
return con;
}
}
RegistrationBean
package com.mvc.Bean;
public class RegistrationBean
{
private String firstName;
private String lastName;
private String userName;
private String password;
private String address;
private String contact;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getContact() {
return contact;
}
}
Anything anyone can offer as far as why this servlet will not run would be gladly appreciated. The error messages that Eclipse throws are so generic, but the issue seems to be basically writing the registration information to the database. I can load the registration page and enter the information, and the if statements work because the page wont forward with blank text entry boxes or a password less than 6 characters. The problem is when you submit, and it throws HTTP Status 404 and says the requested resource is unavailable.
It might be because you're retrieving the incorrect parameter names in your RegistrationServlet.
For example: you are retrieving with request.getParameter("firstname") but your input have name="firstName". Note the upper case 'N' (java EE servers are case sensitive for URIs).
Try this in your RegistrationServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName"); // upper case N
String lastName = request.getParameter("lastName"); // upper case N
String userName = request.getParameter("userName"); // upper case N
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
//...

How to display String of Json in jsp table

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.

Property on model attribute set in one controller method is not available in another controller method

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 want to add "Edit" functionality. When I click Edit, it adds a duplicate record instead of editing

This is my Operations.java, products.Java class and Products.jsp file:
In which I implemented the Add and Edit functionality. The add button is working fine but the edit button is adding a duplicate record instead of editing the record. Please tell me how do I implement edit function in my program ?
package metier;
import java.util.ArrayList;
public class Operation {
private ArrayList<Produit> produits = new ArrayList<Produit>();
public ArrayList<Produit> getProduits() {
return produits;
}
public void setProduits(ArrayList<Produit> produits) {
this.produits = produits;
}
public void add(Produit p){
produits.add(p);
}
public void remove(Long id){
for(Produit p:produits){
if(p.getId()==id){ //equals
produits.remove(p);
break;
}
}
}
public void edit(Long id){
for(Produit p:produits){
if(p.getId()==id){
p.getId();
p.getName();
p.getContactno();
p.getSPS();
produits.add(p);
break;
}
}
}
public ArrayList getAll(){
return produits;
}
}
package metier;
public class Produit {
private Long id;
private String name, address, contactNo, SparePartsService;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactno() {
return contactNo;
}
public void setContactno(String contactNo) {
this.contactNo = contactNo;
}
public String getSPS() {
return SparePartsService;
}
public void setSPS(String SparePartsService) {
this.SparePartsService = SparePartsService;
}
public Produit() {
super();
// TODO Auto-generated constructor stub
}
public Produit(String name, String address, String contactNo, String SparePartsService) {
super();
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
public Produit(Long id, String name, String address, String contactNo, String SparePartsService) {
super();
this.id = id;
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
#Override
public String toString() {
return id + " - " + name + " - " + address + " - " + contactNo + " - " + SparePartsService + " .";
}
public void Show(){
System.out.println(toString());
}
}
<%# page import="web.ProduitBeans"%>
<%# page import="metier.Produit"%>
<%# page import="java.util.Iterator"%>
<%# 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>Getiteasy.Net</title>
</head>
<body>
<%
ProduitBeans produits;
if(request.getAttribute("modele") != null){
produits = (ProduitBeans) request.getAttribute("modele");
}else{
produits = new ProduitBeans();
}
%>
<h3>Tutorial MVC(Model, View, Controller)</h3>
<h5>Ajouter un nouveau produit</h5>
<form action="prodserv" method="post">
<table border="1" width="45%">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td>Contact No.</td>
<td><input type="text" name="contactNo"></td>
</tr>
<tr>
<td>Spare Parts Service(Yes/No)</td>
<td><input type="text" name="SparePartsService"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Valider"></td>
</tr>
</table>
</form>
<table border="1" width="60%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Contact No.</th>
<th>Spare Parts Service</th>
<th>Option</th>
</tr>
<%
Iterator<Produit> list = produits.getListe().iterator();
while(list.hasNext()){
Produit p = list.next();
%>
<tr>
<td><%=p.getId() %></td>
<td><%=p.getName() %></td>
<td><%=p.getAddress() %></td>
<td><%=p.getContactno() %></td>
<td><%=p.getSPS() %></td>
<td>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="action" value="supprimer" >
<input type="submit" value="supprimer"/>
</form>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="editaction" value="Edit" >
<input type="submit" value="Edit"/>
</form>
</td>
</tr>
<%
}
%>
</table>
What do you want your edit method to do? Look at your edit method. If you find a product with the ID you are just calling the getter methods and you are doing nothing with the data. After that you are just adding the same object again to your list. You need to define what data you want to edit and then overwrite the data with a setter method. And don't add the object again to your list.
Working with an ArrayList for this purpose is very unefficiant, you will be looping your list many many times which will take longer and longer as your list is growing. Better make use of a Map, it "maps" a key to a value so you can call that value directly by the predefined key and don't have to loop the whole list.
In your Operation class:
change the ArrayList<Produit> produits ... to Map<Long,Produit> = new HashMap<>()
(Also I would recommand you making it static, to ensure the you keep the same list across the board)
Add a private static Long idCounter=0L
Then when you Add a new Produit, do:
public void add(Produit p){
idCounter++;
p.setId(idCounter);
produits.put(idCounter,p);
}
Remove:
public void remove(Produit p){
produits.remove(p.getId());
}
Note.
No idcounter--; here because you don't know if it is the last one in your map, So baicly you will be skipping some id's if you removed alot of elements.
The id of the Produit that you want to remove has to be set on the p parameter.
Edit:
public void edit(Produit p){
produits.put(p.getId(),p);
}
Note.
The ID of the Produit that you want to remove has to be set on the p parameter.
getAll:
public Collection<Produit> getAll(){
produits.values();
}
In your JSP page:
You have to somehow tell your controller what action it has to do. You can do this by using an Action parameter.
You have done this for one case (Delete (=supprimer FR)).
<input type="hidden" name="action" value="supprimer" >
To edit you must do it again, so change:
<input type="hidden" name="editaction" value="Edit" >
to
<input type="hidden" name="action" value="Edit" >
Note. "name"-tag is the name of the parameter like number is the name of the variable Int number.
In your Controller (servlet):
your:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
else { // Recuprer les information
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}
In the "else"-clause of you if-satement that checks if action-parameter is null, you only have the functionality to add a Produit.
you must add:
if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
Result:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
// Recuprer les information
else if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
}
Note. You must add a new "else if"-clause for every possible action-parameter value that you want to implement.
I advise you to put the functionality that is within these if-clauses in a seperate private function, if not your doPost(...) function will get very long.
Or even better take a look at the Command-patern.

Categories

Resources