Java SpringBoot Postgres remove rows - java

Help me please to remove the row in Postgres by clicking the Del button.
Maybe to link id in DB and id on the HTML page, but how?
Maybe I need to parse the HTML page and pass String id?
Any ideas will help me.
here is my database schema:
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<th><form action="/remove" method="post">
<input type="submit" value="Del"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
</form>
</th>
</tr>
{{/messages}}
</tbody>
#Entity
#Table(name = "message")
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String text;
private String sn;
private String owner;
public Message() {
}
public Message(String text, String sn, String owner) {
this.text = text;
this.sn = sn;
this.owner = owner;
}
Rows are forming in database by:
#PostMapping("/main")
public String add (
#RequestParam String owner,
#RequestParam String text,
#RequestParam String sn, Map<String, Object> model) {
Message message = new Message (text, sn, owner);
if (text != null && !text.isEmpty() & sn != null && !sn.isEmpty() & owner != null &&
!owner.isEmpty()) {
if (!text.matches("^[0-9].*$")) {
messageRepo2.save(message);
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else
model.put("error", "ТМЦ не должно начинаться с цифры");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else {
model.put("error", "Заполните все поля!");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
}
return "main";
}

There are two issues with your html code:
it would be to let the form element outside the table
need to use <input type="hidden" name="xxx" value="{{xxx}}" /> in order to let it can pass parameter to your controller method
<form action="/remove" method="post">
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}} <input type="hidden" name="id" value="{{id}}" /></td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i> <input type="hidden" name="sn" value="{{sn}}" /></td>
<td><i>{{owner}}</i> <input type="hidden" name="owner" value="{{owner}}" /></td>
<td><input type="submit" value="Del"/></td>
</th>
</tr>
{{/messages}}
</tbody>
</table>
</form>

<thead>
<tr>
<th>ID ТМЦ</th><th>Наименование ТМЦ</th><th>Серийный номер ТМЦ</th><th>За кем числится</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<td>
<form action="/remove" method="post" name="remove">
<input type="submit" value="Удалить"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<input type="hidden" name="sn" value="{{sn}}"/>
</form>
</td>
</tr>
{{/messages}}
</tbody>
import com.example.webapp.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Transactional
public interface MessageDel extends CrudRepository<Message, Long>{
List<Message> deleteBySn (String sn);
}
#PostMapping("/remove")
public String remove (#RequestParam String sn, Map<String, Object> model) {
Message messagedel = new Message (sn);
messageDel.deleteBySn(sn);
model.put("messages", messagedel);
return "redirect:/main";
}

Related

Passing thymeleaf information to a hidden form

I am trying to pass the information from a thymeleaf list and trying to add it to database.
I am getting data from the tmdb and it will be changing so i display the information obtain to the endpoint "/LatestMovies" this information is not saved in the db and ether should it be. so i am trying to add a save button for the custumer to add the movie listed.(its simple it just haves movieid and moviename)
Showing the movies listed i have no problem and it works fine but where i get error is when i add a hidden form. The current code i have is this:
<div class="container">
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="LatestMovies : ${latestMovies}">
<td th:text="${LatestMovies.id}"></td>
<td th:text="${LatestMovies.movieName}"></td>
<td>
<form action="#" th:action="#{/LatestMovies}" th:object="${addMovies}" method="post">
<p><input type="hidden" th:field="*{id}" th:attr="value = ${LatestMovies.id}" /></p>
<p><input type="hidden" th:field="*{movieName}" th:attr="value = ${LatestMovies.movieName}" /></p>
<p><input type="submit" value="Submit" /></p>
</form>
</td>
</tr>
</table>
#Controller
public class LatestMoviesController {
#Autowired
private LatestMoviesDao listOfMovies;
#Autowired
private savedMoviesDao movieRepo;
#GetMapping("/LatestMovies")
public String prueba(Model model) {
TmdbMovies movies = new TmdbApi("22914f477aaa3e7f86c6f5434df8d1eb").getMovies();
ResultsPage<MovieDb> movie = movies.getPopularMovies("en", 1);
for(int i=0; i <= 19; i++){
int movieId = movie.getResults().get(i).getId();
String movieName = movie.getResults().get(i).toString();
listOfMovies.save(new LatestMovies(movieId, movieName));
}
model.addAttribute("latestMovies", listOfMovies.findAll());
return "index";
}
#PostMapping("/LatestMovies")
public String save(#ModelAttribute("addMovies") Model model, SavedMovies addMovies) {
movieRepo.save(addMovies);
return "index";
}
}
Thx in advance
First, let's change your form. You don't need to add a new object to it, since you are already iterating through a list of them. That way, you will also avoid having to add the value for each field manually using th:attr. What we are gonna do, is send the required params separately and then build our movie object with them.
<div class="container">
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="LatestMovies : ${latestMovies}">
<td th:text="${LatestMovies.id}"></td>
<td th:text="${LatestMovies.movieName}"></td>
<td>
<form th:action="#{/LatestMovies}" method="post">
<p><input type="hidden" th:value="${LatestMovies.id}" name="id"/></p>
<p><input type="hidden" th:value="${LatestMovies.movieName}" name="name"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</td>
</tr>
</table>
</div>
Now, on your controller, do the following modifications.
#PostMapping("/LatestMovies")
public String save(#RequestParam("id") Integer id, #RequesParam("name") String name) {
SavedMovies movie = new SavedMovies();
movie.setId(id);
movie.setName(name);
movieRepo.save(movie);
return "index";
}
These changes should do the trick.

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 how to link between 2 java classes to add items to arraylist and display them in JSP

Heyy I'm new to JSP and would like to know how to solve a small problem. I'm not sure how to do the link between the Client.java and Item.java to be able to add new items into the ArrayList and display it on the jsp page.
This is my Client.java code:
package javaCode;
import java.util.ArrayList;
public class Client {
private String name;
private String email;
private int phone;
private String address;
private String country;
private String city;
public ArrayList<Item> list;
private String shipping;
private int fee;
private double discount;
private Item item;
public Client() {
list = new ArrayList<Item>();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPhone(int phone) {
this.phone = phone;
}
public int getPhone() {
return phone;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
public void setShipping(String shipping) {
this.shipping = shipping;
}
public String getShipping() {
return shipping;
}
public void setFee() {
if(this.shipping == "") {
this.fee = 0;
}
if(this.shipping == "USPS Express Mail") {
this.fee = 200;
}
if(this.shipping == "USPS Priority Mail") {
this.fee = 300;
}
if(this.shipping == "DHL") {
this.fee = 400;
}
if(this.shipping == "FedEx") {
this.fee = 50;
}
}
public int getFee() {
return fee;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getDiscount() {
return discount;
}
public void setItem(Item item) {
list.add(this.item);
}
public ArrayList<Item> getList() {
return list;
}
}
This is my Item code:
package javaCode;
public class Item {
private String item;
private int quantity;
private double price;
public Item() {
}
public void setItem(String item) {
this.item = item;
}
public String getItem() {
return item;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
//Client.list.add(this);
}
public int getQuantity() {
return quantity;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public double getTotal() {
return (quantity*price);
}
}
This is the clientdetails.jsp file:
<jsp:useBean id="iteminfo" class="javaCode.Item"/>
<jsp:setProperty property="*" name="iteminfo"/>
<jsp:useBean id="userinfo" class="javaCode.Client" scope="request"/>
<jsp:setProperty property="*" name="userinfo"/>
<h2>Personal Information</h2>
<table border="1">
<tr>
<td>Name</td>
<td><jsp:getProperty property="name" name="userinfo"/></td>
</tr>
<tr>
<td>E-mail</td>
<td><jsp:getProperty property="email" name="userinfo"/></td>
</tr>
<tr>
<td>Phone</td>
<td><jsp:getProperty property="phone" name="userinfo"/></td>
</tr>
<tr>
<td>Address</td>
<td><jsp:getProperty property="address" name="userinfo"/></td>
</tr>
<tr>
<td>Country</td>
<td><jsp:getProperty property="country" name="userinfo"/></td>
</tr>
<tr>
<td>City</td>
<td><jsp:getProperty property="city" name="userinfo" /></td>
</tr>
<tr>
<td>Shipping Method</td>
<td><jsp:getProperty property="shipping" name="userinfo"/></td>
</tr>
<tr>
<td>Shipping Amount</td>
<td><jsp:getProperty property="fee" name="userinfo"/></td>
</tr>
<tr>
<td>Discount</td>
<td><jsp:getProperty property="discount" name="userinfo"/></td>
</tr>
<tr>
<td>List</td>
<td><jsp:getProperty property="list" name="userinfo"/></td>
</tr>
</table>
<br><br>
<table border="1">
<tr>
<td>Name</td>
<td>Item1</td>
</tr>
<tr>
<td>Quantity</td>
<td><jsp:getProperty property="quantity" name="iteminfo"/></td>
</tr>
<tr>
<td>Unit Price</td>
<td><jsp:getProperty property="price" name="iteminfo"/></td>
</tr>
<tr>
<td>Total</td>
<td><jsp:getProperty property="total" name="iteminfo"/></td>
</tr>
</table>
This is the form.jsp file (containing html form):
<html>
<head>
<title>Order Form</title>
<link rel="stylesheet" type="text/css" href="formstyle4.css">
<script type="text/javascript"></script>
</head>
<body>
<form name="order" id="orderForm" action="clientdetails.jsp" method="post">
<p id="date"><script type="text/javascript"></script></p>
<h2>Personal Information</h2>
<label id="fname">* Name</label><input type="text" name="name" id="name" onkeypress="return !isNumber(event)" required>
<label id="labemail">E-mail</label><input type ="text" name="email" id="email" onblur="validateEmail(this)" required><br/><br/>
<label for="address" id="labaddr">* Address</label>
<textarea rows="4" cols="25" id="address" name="address" required></textarea>
<label id="labcountry">Country</label>
<select id="country" name="country">
<option value=""></option>
<option value="Lebanon">Lebanon</option>
<option value="UAE">UAE</option>
<option value="United States">United States</option>
<option value="France">France</option>
<option value="Italy">Italy</option>
</select><br/><br/>
<label id="labphone">* Phone</label><input type="text" name="phone" id="phone" onkeypress="return isNumber(event)" onblur="validPhone()" required>
<label id="labcity">City</label><input type="text" name="city" id="city" onkeypress="return !isNumber(event)" required><br><br>
<br><br>
<table id="orderTable">
<th colspan="4">Order Details</th>
<tr id="first">
<td>Item</td>
<td>Quantity</td>
<td>Unit Price</td>
<td>Total</td>
</tr>
<tr>
<td id="item">Item1</td>
<td><input onblur="findTotal(1)" class="item" type="text" name="quantity" id="quantity" onkeypress="return isNumber(event)"/></td>
<td><input onblur="findTotal(1)" class="item" type="number" min="0" step="0.01" name="price" id="price" onkeypress="return isNumber(event)"/></td>
<td><input onblur="totals()" class="item" type="text" name="total" id="total" readonly></td>
</tr>
<!--
<tr>
<td id="item">Item2</td>
<td><input onblur="findTotal(2)" type="text" name="quantity" id="quantity" onkeypress="return isNumber(event)"/></td>
<td><input onblur="findTotal(2)" type="text" name="price" id="price" onkeypress="return isNumber(event)"/></td>
<td><input onblur="totals()" type="text" name="total" id="total" readonly></td>
</tr>
<tr>
<td id="item3">Item3</td>
<td><input onblur="findTotal(3)" type="text" name="val3" id="qt3" onkeypress="return isNumber(event)"/></td>
<td><input onblur="findTotal(3)" type="text" name="val3" id="price3" onkeypress="return isNumber(event)"/></td>
<td><input onblur ="totals()" type="text" name="total" id="total3" readonly></td>
</tr> -->
<tr>
<td id="colshipping">Shipping Method</td>
<td colspan="2">
<select id="shipping" name="shipping">
<option value="empty"></option>
<option value="USPS Express Mail">USPS Express Mail</option>
<option value="USPS Priority Mail">USPS Priority Mail</option>
<option value="DHL">DHL</option>
<option value="FedEx">FedEx</option>
</select>
</td>
<td><input type="text" id="fee" onblur="totals()" readonly></td>
</tr>
<tr>
<td id="coldis">Discount</td>
<td colspan="2"><input onchange="totals()" type="text" name="discount" id="discount" onkeypress="return isNumber(event)" required> %</td>
<td><input type="text" onchange="totals()" id="amount" name="amount" readonly></td>
</tr>
<tr>
<td id="coltotal" colspan="3">Total</td>
<td><input type="text" name="totalPrice" id="totprice" readonly></td>
</tr>
</table>
<br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
My problem is whenever I fill-in the information in "form.jsp", "clientdetails.jsp" opens and shows me the details I entered except the list element, it keeps showing as empty. I'm not sure how to be able to connect between the item class and client class to be able to display the Item1 instance in list. They told me that maybe I should do some modifications in setItem(Item item) method by how?
Please any hint or advice might help me a lot! Thank you!
In below method,
public void setItem(Item item) {
list.add(this.item);
}
Why are you doing list.add(this.item); ? shouldn't it be list.add(item);?
Change it to list.add(item); .

How to keep a check on the "date value" on JSP page as I have modified the date in the setter if it is null

I have some trouble with my jsp page's date value. Basically I have a date picker which allows me to pick date and save it to database. If I do not pick a date, the value is null which I check before setting it and passing it to the database. If its null, I modify it to a dummy date and then save it to database. This part works fine. But if the jsp page throws the not null validation, the value goes to the setter as null, gets modified there to the dummy value and reflected back in the form. I don't want that dummy value to be visible to the user. So is there any way I can put a check on the jsp page so that if the value is a dummy date value it will be visible as null to the user?
<b>Order Information</b>
<table>
<tr>
<td align="left"><form:label for="orId" path="orId" cssErrorClass="error">* Order Id :</form:label></td>
<td align="left"><form:input path="orId" size="35" maxlength="35" /> <form:errors path="orId" /></td>
</tr>
<tr>
<td align="left"><form:label for="orServicetag" path="orServicetag" cssErrorClass="error">* Service tag:</form:label></td>
<td align="left"><form:input path="orServicetag" size="35" maxlength="35" value= "${ticketList.ticServicetag}"/> <form:errors path="orServicetag" /></td>
</tr>
<tr>
<td align="left"><form:label for="orOwnerSUUsername" path="orOwnerSUUsername" cssErrorClass="error">* SU UserName:</form:label></td>
<td align="left"><form:input path="orOwnerSUUsername" id="suusnm" size="35" maxlength="35" value= "${ticketList.ticOwnerSuUsername}"/> <form:errors path="orOwnerSUUsername" /></td>
</tr>
<tr>
<td align="left"><form:label for="orTicId" path="orTicId" cssErrorClass="error">* Ticket Id</form:label></td>
<td align="left"><form:input path="orTicId" id="ticcrdt" size="35" maxlength="35" value= "${ticketList.ticId}"/> <form:errors path="orTicId" /></td>
</tr>
<tr>
<td align="left"><form:label for="orTicCreatedDate" path="orTicCreatedDate" cssErrorClass="error">* Ticket Date (YYYY-MM-DD):</form:label></td>
<td align="left"><form:input path="orTicCreatedDate" size="35" maxlength="35" value= "${ticketList.ticDate}"/> <form:errors path="orTicCreatedDate" /></td>
</tr>
<tr>
<td align="left"><form:label for="orPartOrdered" path="orPartOrdered" cssErrorClass="error">* Part Name :</form:label></td>
<td align="left"><form:input path="orPartOrdered" size="35" maxlength="35" /> <form:errors path="orPartOrdered" /></td>
</tr>
<tr>
<td align="left"><form:label for="orOrderedDate" path="orOrderedDate" cssErrorClass="error">* Part Ordered Date (YYYY-MM-DD):</form:label></td>
<td align="left"><form:input path="orOrderedDate" id="datepicker1" size="35" maxlength="35" /> <form:errors path="orOrderedDate" /></td>
</tr>
<tr>
<td align="left"><form:label for="orRecievedDate" path="orRecievedDate" cssErrorClass="error"> Part Received Date (YYYY-MM-DD):</form:label></td>
<td align="left"><form:input path="orRecievedDate" id="datepicker2" size="35" maxlength="35" /> <form:errors path="orRecievedDate" /></td>
</tr>
<tr>
<td align="left"><form:label for="orStatus" path="orStatus" cssErrorClass="error">* Order Status:</form:label></td>
<td align="left">
<select name="orStatus" id = "orStatus" id="slectboxid1">
<option value = "">---Select---</option>
<option value="Open">Open</option>
<option value="Progress">Progress</option>
<option value="Part Ordered">Part Ordered</option>
<option value="Part Arrived">Part Arrived/ Received</option>
<option value="Waiting for Owner's computer">Waiting for Owner's computer</option>
<option value="Installation">Installation in progress</option>
<option value="Closed">Closed</option>
</select>
<form:errors path="orStatus" /></td>
</tr>
</table>
<div align="center" style="margin-top:15px;" >
<form action="OrderDatabase" method="get">
<input type="submit" name="submit" value="View Order"/>
<input type="submit" name="save" value="save"/> |
<input type="reset" name="reset"/>
</form>
</div>
</form:form>
The Code for the ticketDetailsBean is as follows:
package com.helplaw.beans;
//import java.sql.*;
import java.util.Date;
public class OrderDetailsBean {
private String orId;
private String orPartOrdered;
private Date orTicCreatedDate;
private Date orOrderedDate;
private Date orRecievedDate;
private String orOwnerSUUsername;
private String orServicetag;
private String orStatus;
private int orTicId;
public String getOrId() {
return orId;
}
public void setOrId(String orId) {
this.orId = orId;
}
public String getOrPartOrdered() {
return orPartOrdered;
}
public void setOrPartOrdered(String orPartOrdered) {
this.orPartOrdered = orPartOrdered;
}
public Date getOrTicCreatedDate() {
return orTicCreatedDate;
}
public void setOrTicCreatedDate(Date orTicCreatedDate) {
this.orTicCreatedDate = orTicCreatedDate;
}
public Date getOrOrderedDate() {
return orOrderedDate;
}
public void setOrOrderedDate(Date orOrderedDate) {
this.orOrderedDate = orOrderedDate;
}
public Date getOrRecievedDate() {
return orRecievedDate;
}
public void setOrRecievedDate(Date orRecievedDate) {
if(orRecievedDate == null){
System.out.println("d11:" + orRecievedDate);
this.orRecievedDate = new Date(000000001);
}
else if(orRecievedDate.toString().equals("1969-12-31")){
System.out.println("d12:" + orRecievedDate);
this.orRecievedDate = null;
}
else{
System.out.println("d13:" + orRecievedDate);
this.orRecievedDate = orRecievedDate;
}
}
public String getOrOwnerSUUsername() {
return orOwnerSUUsername;
}
public void setOrOwnerSUUsername(String orOwnerSUUsername) {
this.orOwnerSUUsername = orOwnerSUUsername;
}
public String getOrServicetag() {
return orServicetag;
}
public void setOrServicetag(String orServicetag) {
this.orServicetag = orServicetag;
}
public String getOrStatus() {
return orStatus;
}
public void setOrStatus(String orStatus) {
this.orStatus = orStatus;
}
public int getOrTicId() {
return orTicId;
}
public void setOrTicId(int orTicId) {
this.orTicId = orTicId;
}
}
Just remove the NULL validation because it will never be null in your case where you are always setting a dummy value.
Alternatively, you can achieve it using hidden input field.
Steps to follow:
create hidden input fields one for each date input field.
set the value in hidden input field if value is changed in actual date input field using JavaScript
now set the dummy value in hidden input field rather than actual input field if value is null
read values from hidden input fields to save it in database
Note: swap the path attribute date input field with hidden input fields so that it will be picked from hidden input fields when form is submitted.

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

Categories

Resources