I'm currently having inconsistent of adding and deleting data which happen randomly without any errors showing. The page will just keep loading forever until I stop my tomcat server. I can't identify where is the problem which is causing this inconsistency.
Controller
#RequestMapping(value = "menu/{userId}", method = RequestMethod.GET)
public ModelAndView orderPizzaForm(#ModelAttribute(value = "pizzaform") PizzaTO pizzaTO,
#PathVariable String userId) {
ModelAndView model = new ModelAndView("pizzaform");
List pizzaList = pizzaService.getListByUserId(userId);
model.addObject("pizzaList", pizzaList);
return model;
}
#RequestMapping(value = "menu/add/{userId}", method = RequestMethod.POST)
public ModelAndView orderPizza(#ModelAttribute(value = "pizzaform") PizzaTO pizzaTO, #PathVariable String userId,
BindingResult result) {
ModelAndView model = new ModelAndView("pizzaform");
pizzaFormValidator.validate(pizzaTO, result);
if (result.hasErrors()) {
List pizzaList = pizzaService.getListByUserId(userId);
model.addObject("pizzaList", pizzaList);
return model;
} else {
pizzaTO.setUserId(userId);
String[] data = pizzaTO.getPizzaSize().split("\\|");
pizzaTO.setPizzaSize(data[0]);
pizzaTO.setPizzaPrice(Double.parseDouble(data[1]));
pizzaService.addPizza(pizzaTO);
List pizzaList = pizzaService.getListByUserId(userId);
model.addObject("pizzaList", pizzaList);
return model;
}
}
////////////////////////////// DELETE PIZZA //////////////////////////////
#RequestMapping(value = "menu/delete/{userId}/{pizzaId}", method = RequestMethod.GET)
public ModelAndView editEmployee(#ModelAttribute(value = "pizzaform") PizzaTO pizzaTO, #PathVariable String pizzaId,
#PathVariable("userId") String userId) {
pizzaService.deletePizza(pizzaId);
ModelAndView model = new ModelAndView("pizzaform");
List pizzaList = pizzaService.getListByUserId(userId);
model.addObject("pizzaList", pizzaList);
return model;
}
pizzaform.jsp
<body>
<div style="text-align: center">
<form:form commandName="pizzaform"
action="${pageContext.request.contextPath}/menu/add/${userId}" method="POST">
<form:hidden path="userId" value="${userId}" />
<table align="center">
<tr>
<td><label id="pizzaCrust">Choose a crust:</label></td>
<td><form:radiobutton path="pizzaCrust" value="Hand Tossed" />Hand
Tossed <form:radiobutton path="pizzaCrust" value="Thin Crust" />Thin
Crust<form:errors
path="pizzaCrust" class="error" /></td>
</tr>
<tr>
<td><label id="pizzaFlavour">Choose a flavour:</label></td>
<td><form:radiobutton path="pizzaFlavour" value="Pepperoni" />Pepperoni
<form:radiobutton path="pizzaFlavour" value="BBQ Chicken" />BBQ
Chicken <form:radiobutton path="pizzaFlavour"
value="Spicy Chicken" />Spicy Chicken<form:errors
path="pizzaFlavour" class="error" /></td>
</tr>
<tr>
<td><label id="pizzaSize">Choose a size:</label></td>
<td><form:radiobutton path="pizzaSize" value="10|23.80" />10 inch (Regular - 4 Pax)
<form:radiobutton path="pizzaSize" value="12|30.80" />12 inch (Medium - 6 Pax)
<form:radiobutton path="pizzaSize" value="14|37.80" />14 inch (Large - 8 Pax)<form:errors
path="pizzaSize" class="error" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add" />
<button type="button" name="back"
onclick="window.location='${pageContext.request.contextPath}/main'">Back</button></td>
</tr>
</table>
</form:form>
<br> <br>
<table border="1" bgcolor="black" width="600px" align="center">
<tr
style="background-color: white; color: black; text-align: center;"
height="30px">
<td><b>Crust</b></td>
<td><b>Flavor</b></td>
<td><b>Size (Inch)</b></td>
<td><b>Price (S$)</b></td>
<td></td>
</tr>
<c:forEach items="${pizzaList}" var="pizza">
<tr
style="background-color: white; color: black; text-align: center;"
height="30px">
<td><c:out value="${pizza.pizzaCrust}" /></td>
<td><c:out value="${pizza.pizzaFlavour}" /></td>
<td><c:out value="${pizza.pizzaSize}" /></td>
<td><c:out value="${pizza.pizzaPrice}" /></td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</div>
Related
I tried all the solutions but I keep getting this error. Moreover if i don't use form:form in jsp file and use a simple HTML, I get the desired output.
Controller Class
#Controller
public class controller_class {
/*
* #RequestMapping(path = "/index", method = RequestMethod.GET) public
* ModelAndView mar() { return new ModelAndView("index","command",new marks());
* }
*/
#RequestMapping("/index")
public ModelAndView showComments() {
return new ModelAndView("marks","command",new marks());
}
#RequestMapping(value = "/addMarks", method = RequestMethod.POST)
public ModelAndView stud(#ModelAttribute("marks") marks m) {
ModelAndView mv = new ModelAndView("result");
int k = m.calculate();
mv.addObject("tot_marks", k);
return mv;
}
}
index.jsp
<form:form method = "POST" modelAttribute="marks" action = "/springmvc_qa3/addMarks">
<table>
<tr>
<td><form:label path = "sci_marks">Name</form:label></td>
<td><form:input path = "sci_marks" /></td>
</tr>
<tr>
<td><form:label path = "maths_marks">Age</form:label></td>
<td><form:input path = "maths_marks" /></td>
</tr>
<tr>
<td><form:label path = "eng_marks">id</form:label></td>
<td><form:input path = "eng_marks" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
Correct Output if I use this instead
<form method="POST" action="/springmvc_qa3/addMarks" >
<table>
<tr>
<td><label >Science Marks</label></td>
<td><input type="text" name="sci_marks" /></td>
</tr>
<tr>
<td><label >Mathematics Marks</label></td>
<td><input type="text" name="maths_marks" /></td>
</tr>
<tr>
<td><label >English Marks</label></td>
<td><input type="text" name="eng_marks" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
What is the reason that I can't get the right output using the first method?
add the following to your controller class:
#ModelAttribute("marks")
public Marks nameOfMethodDoesntMatter(){
return new Marks();
}
make sure your Marks class has getters, setters and default constructor.
consider calling your class MarksDTO or something similar to convey its meaning better (DTO = data transfer object).
I have this html template in thymeleaf.
<table id="listAllAccountantTable" th:cellspacing="0" class="table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th>No. </th>
<th>Registered Date</th>
<th>Status</th>
<th>Name</th>
<th>Email</th>
<th>Contact No.</th>
<th>IC No.</th>
<th>IC attachment</th>
<th>Actions </th>
</tr>
<tr th:each="acc,iterationStatus : ${accountantListing}">
<td th:text="${iterationStatus.count}">1</td>
<td th:text="${acc.currentTimeStamp}"></td>
<td th:text="${acc.active}">1</td>
<td th:text="${acc.name}">Name</td>
<td th:text="${acc.email}">Email</td>
<td th:text="${acc.phoneNumber}">Contact No.</td>
<td th:text="${acc.icNumber}">IC No.</td>
<td th:text="${acc.id}"> To be fixed: upload IC image</td>
<td>
<form action="#" data-th-action="#{/accountantApplication}" method="post">
<button type="submit" name="action" th:id="${acc.id}"
value="Accept">Accept</button>
<button type="submit" name="action" th:id="${acc.id}"
value="Reject">Reject</button>
</form>
</td>
</tr>
My Spring controller is:
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Accept")
public ModelAndView Accept() {
ModelAndView modelAndView = new ModelAndView();
System.out.println("######## Accepting accountant");
modelAndView.setViewName("AccountantListing");
return modelAndView;
}
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Reject")
public ModelAndView Reject() {
ModelAndView modelAndView = new ModelAndView();
System.out.println("######## Rejecting accountant");
modelAndView.setViewName("AccountantListing");
return modelAndView;
}
The table shows a list of accountants.
All accountants are loaded from db and displayed on the table.
They need to be accepted or rejected.
When I click the accept button, Accept() is called.
How do I get the ID attached to button?
Or if there is better way of immplementing this. let me know too. Thanks so much
In your form, you should have a hidden input:
<form action="#" data-th-action="#{/accountantApplication}" method="post">
<input type="hidden" name="id" th:value="${acc.id}" />
<button type="submit" name="action" value="Accept">Accept</button>
<button type="submit" name="action" value="Reject">Reject</button>
</form>
Then, in your controllers:
public ModelAndView accept(#RequestParam String id) {
.
.
.
}
public ModelAndView Reject(#RequestParam String id) {
.
.
.
}
Also, as a side note, you can replace:
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Accept")
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Reject")
with
#PostMapping(value="/accountantApplication", params="action=Accept")
#PostMapping(value="/accountantApplication", params="action=Reject")
i have following scenario :
#ModelAttribute("persons")
public void addAttributes(Model model) {
Person person = new Person()
;
person.setAge(26);
person.setFirstName("mars");
model.addAttribute("persons", person);
}
#RequestMapping(value="/process-person")
public ModelAndView processPerson(#ModelAttribute Person person,#ModelAttribute ("persons")Person persons,ModelAndView modelAndView ) {
//
//ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("person-result-page");
modelAndView.getModel().remove("personObj");
modelAndView.addObject("pers", person);
----> modelAndView.addObject("pers2", persons);// persons holds the myname1 provided in input box
modelAndView.addObject("personObj", person);
return modelAndView;
}
As shown in the --> i want this variable -persons to hold the value obtained from addAttributes() method but it is taking the same values that i input from the jsp page :
<form:form method="POST" commandName="person-entity" action="process-person.html">
<table>
<tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
<td></td>
<td></td>
</tr>
</table>
</form:form>
<br/>
i saw few similar questions but none of them resolved this problem . Here i want values from addAttribute method to placed inside "persons" object, but it is taking the same value as that of "person" being provided from the form.jsp.
please help me out
I am developing an app where LoginForm.jsp and UserRegistration.jsp will lead to UserAccount jsp page on specific action.In LoginForm when a user presses a 'Login' button ->UserAccount form is displayed.In UserRegistration Form when details are entered and submitted ->UserAccount form is displayed.
Below is the controller code when a request comes as UserAccount.html
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#Valid #ModelAttribute("user") UserDetails user,BindingResult result) {
if(result.hasErrors())
{ System.out.println(result.getAllErrors());
ModelAndView model1=new ModelAndView("UserRegistration");
return model1;
}
// User validation
System.out.println(user.getAccountType());
userDAO.create(user);
ModelAndView model1 = new ModelAndView("UserAccount");
return model1;
}
LoginForm.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h1
style="background-color: green; color: Yellow; padding: 10px; text-align: center;">Mybank
Online Login</h1>
<form:errors path="user.*" />
<form action="/MyBankProject/UserAccount.html" method="post">
<div
style="background-color: yellow; color: black; padding: 10px; text-align: center;"
align="center">
<p>
User ID <input type="text" name="userName" />
</p>
<p>
Password <input type="password" name="password" />
</p>
<input type="submit" value="Login" /> New User?
</div>
<input type="hidden" name="page" value="LoginForm"/>
</form>
</body>
</html>
UserRegistration.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h1>${headerMessage}</h1>
<h3>USER REGISTRATION</h3>
<form:errors path="user.*" />
<form action="/MyBankProject/UserAccount.html" method="post">
<table border="1" style="width:100%" >
<tr>
<td>FirstName :</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>LastName :</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User's EmailId :</td>
<td><input type="text" name="emailId" /></td>
</tr>
<tr>
<td>user's gender :</td>
<td><select name="gender" multiple>
<option value="M">Male</option>
<option value="F">Female</option>
</select></td>
</tr>
<tr>
<td>user's age :</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td>user's DOB :</td>
<td><input type="text" name="dOB" /></td>
</tr>
<tr>
<td>Account Type :</td>
<td><select name="accountType" multiple>
<option value="Savings">Savings</option>
<option value="Current">Current</option>
<option value="FixedDeposit">Fixed Deposit</option>
</select>
<td>
</tr>
<tr>
<td>Amount :</td>
<td><input type="text" name="amount" /></td>
</tr>
</table>
<table>
<tr>
<td>UserName</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
</table>
<table>
<tr>
<td>User's Address :</td>
</tr>
<tr>
<td>country: <input type="text" name="address.country" /></td>
<td>city: <input type="text" name="address.city" /></td>
<td>street: <input type="text" name="address.street" /></td>
<td>pincode:<input type="text" name="address.pincode" /></td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
<td><input type="button" onclick="history.back();"
value="Cancel"></td>
</tr>
</table>
<input type="hidden" name="page" value="UserRegistration"/>
</form>
</body>
</html>
Now for me I need to know the jsp page from which the UserAccount invoked ,to perform different actions based on that.
I am new to Spring MVC and searched all over the internet for the solution.
HTTP is a stateless protocol. This means that you can not make assumptions about previous states.
I think you have two options to get information about the previous page anyways.
Add a hidden field to your form and send the name of the page with the request.
HTML:
<form>
<input type="hidden" name="page" value="[the name of the current page]"/>
</form>
Controller:
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#RequestParam(value="page", required=false) String page) {
[...]
}
Now you can check the page value.
Use the session. Store the current page in the controller methods that render the form:
#RequestMapping("/login")
public String login(HttpServletRequest request) {
request.getSession().setAttribute("lastPage", "login");
return "redirect:/UserAccount.html";
}
#RequestMapping("/register")
public String register(HttpServletRequest request) {
request.getSession().setAttribute("lastPage", "register");
return "redirect:/UserAccount.html";
}
Check the lastPage value in userAccountForm():
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(HttpServletRequest request) {
HttpSession session = request.getSession();
String lastPage = (String) session.getAttribute("lastPage");
session.removeAttribute("lastPage");
[...]
}
Check the referer field of the request header.
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#RequestHeader(value = "referer", required = false) String referer) {
[...]
}
This gives you the referer as a method argument if there is one. Be careful. It is possible that there was no referer or that the field was manipulated by the client.
Hope this will solve your need.
URL url = new URL(request.getHeader("referer"));
System.out.println("last page url"+ url.getPath());
if(url.getPath().equals("your last url"){
//code
}
my controller
#RequestMapping("/")
public String loadHome(#RequestParam(value="tab",defaultValue="pending_users") String tab,Model model) {
UsersManager um = new UsersManager();
TagsManager tm = new TagsManager();
if(tab.equals("pending_users"))
model.addAttribute("pending_users",um.getPendingUsers(""));
else if(tab.equals("registered_users"))
model.addAttribute("registered_users",ForumUserUtility.sortPointEarned(um.getUsers(0,um.getNoOfUsers(""),"")));
else if(tab.equals("suspended_users"))
model.addAttribute("suspended_users",ForumUserUtility.sortPointEarned(um.getSuspendedUsers(0,um.getNoOfUsers(""),"")));
else if(tab.equals("tags"))
model.addAttribute("tags",tm.getTagsPopular(""));
else if(tab.equals("admins")){
model.addAttribute("admins",ForumUserUtility.sortPointEarned(um.getAdminList(0,um.getNoOfUsers(""),"")));
}
model.addAttribute("tab",tab);
return "admin_view";
}
#RequestMapping("/DeleteAdmin")
public String deleteAdmin(#RequestParam(value="user_id") String userId, Model model){
UsersManager um = new UsersManager();
um.deleteAdmin(Integer.parseInt(userId));
model.addAttribute("messageAdmin", "Admin Successfully Deleted");
return loadHome("admins", model);
}
my jsp
<c:if test="${loggedInUserType == 'master_admin' }">
<c:if test="${tab == 'admins'}">
${messageAdmin }
<div>
<input onkeyup="showAdmins(this.value)" placeholder="Search Admin" type="text"/>
<div id="admin_box">
<c:if test="${not empty admins}">
<table class='table table-bordered' id="admins">
<tr>
<th colspan='6' style='text-align:center'>Admins</th>
</tr>
<tr>
<th style='text-align:center'>Username</th>
<th style='text-align:center'>First Name</th>
<th style='text-align:center'>Last Name</th>
<th style='text-align:center'>Email</th>
<th style='text-align:center' colspan="2">Action</th>
</tr>
<c:forEach var="user" items="${admins}">
<tr>
<td>${user.username}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.emailAddress}</td>
<td>
<a href="" onclick="return suspendUser(${user.userId})">
Suspend
</a>
</td>
<td>
<a href="" onclick="return deleteAdmin(${user.userId})">
Delete Admin
</a>
</td>
</tr>
</c:forEach>
</table>
</c:if>
</div>
<c:if test="${empty admins}">
<h1>No Suspended User</h1>
</c:if>
</div>
</c:if>
</c:if>
i need to send a message in my jsp notifying the user that the admin was already deleted but the ${messageAdmin} cannot be seen in my view. what do you think is wrong in my code? here is my jsp too.