How to display different title depends on action? - java

I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have <h1>..</h1> in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)
#RequestMapping(path = "/.../update", method = RequestMethod.GET)
public String updatePage(#RequestParam("...") String ..., Model model) {
String[] tokens = ....split("_");
Template template= class.method(...);
model.addAttribute("template", template);
return "save";
}
#RequestMapping(path = "/.../save")
public String newMappingPage(Model model) {
Template template = new Template();
template.setCostIndex("10");
model.addAttribute("template", template);
return "save";
}
#RequestMapping(path = "/.../save", method = RequestMethod.POST)
public String saveMapping(#ModelAttribute Template template) {
class.method(template);
return "redirect:/main-page";
}
save.hml file
<html>
<head>
<title>Engine</title>
<link rel="stylesheet" th:href="#{/css/file.css}"/>
</head>
<body>
<h1>New/Update mapping</h1>
<form action="save" method="post" th:object="${template}">
<fieldset>
<label for="...">....[min]</label>
<input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
<label for="...">...</label>
<input type="number" id="...." th:field="*{...}" required="true"/>
<label for="...">....</label>
<input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
<br/>
<br/>
<label for="response">Response</label>
<br/>
<textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
<br/>
<input id="submit" type="submit" class="primary" value="Submit"/>
</fieldset>
</form>
</body>
</html>

You do not need to create two separate methods for add and update as you are storing data into DB from JSP page. use only one /save API.
#PostMapping(path = "/.../{}/save")
public String newMappingPage(Model model) {
Template template = new Template();
template.setCostIndex("10");
model = new Model();
if (model.getId() > 0) {
model = findById(model.getId());
model.addAttribute("heading", "Update Mapping");
} else {
model.addAttribute("heading", "New Mapping");
}
//Call method to store data from jsp file
return "save";
}
In JSP :
<html>
<head>
<title>Engine</title>
<link rel="stylesheet" th:href="#{/css/file.css}"/>
</head>
<body>
<h1>${heading}</h1>
<form action="save" method="post" th:object="${template}">
<fieldset>
<label for="...">....[min]</label>
<input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
<label for="...">...</label>
<input type="number" id="...." th:field="*{...}" required="true"/>
<label for="...">....</label>
<input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
<br/>
<br/>
<label for="response">Response</label>
<br/>
<textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
<br/>
<input id="submit" type="submit" class="primary" value="Submit"/>
</fieldset>
</form>
</body>
</html>

Update your method like this:
#PostMapping(path = "/.../{}/save")
public ModelAndView save(Model model) {
ModelAndView obj = new ModelAndView("save");
model = new Model();
if (model.getId() > 0) {
model = findById(model.getId());
obj .addAttribute("heading", "Update Mapping");
} else {
obj .addAttribute("heading", "New Mapping");
}
//Call method to store data from jsp file
return obj;
}

Related

submitting checkboxes with Thymeleaf + SpringBoot

I have a SpringBoot app. with this thymelaf template, that works fine when submitting:
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()" />
</div>
but when I add another checkbox, It always take in account the first one, regardless which one I click
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()" />
<label for="gre2">GRE2</label>
<input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" th:onclick="submit()" />
</div>
There is no technical problem here. I think there is a problem with your submit() function, because I created a normal form and tried your same instance, and all selection combinations worked correctly.
I am adding the entity, controller and html files respectively for example.
public class Example {
private boolean gre;
private boolean gre2;
public Example() {
}
// getter/setter ...
}
#Controller
#RequestMapping("/example")
public class ExampleController {
#GetMapping("/create")
public String createExample(Model model) {
model.addAttribute("example", new Example());
return "example-form";
}
#PostMapping("/insert")
public String insertExample(Model model, Example example) {
model.addAttribute("example", example);
return "example-form";
}
}
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div>
<form action="/example/insert" method="post" th:object="${example}">
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" />
<label for="gre2">GRE 2</label>
<input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" />
</div>
<button type="submit">Submit Form</button>
</form>
</div>
</body>
</html>
If you don't want to add an attribute into the Model, you can receive checkbox condition via HttpServletRequest.
#GetMapping("/create")
public String createExample() {
return "example-form";
}
#PostMapping("/insert")
public String insertExample(User user, HttpServletRequest request) {
user.setGre(request.getParameter("gre") != null);
user.setGre2(request.getParameter("gre2") != null);
userServiceImp.updateUser(editedUser); //for example updating user in database
return "/";
}
HTML will be like this:
<form th:action="/insert" method="post">
<div class="form-group required-control">
<label>GRE</label>
<input type="checkbox" name="gre"/>
<label>GRE 2</label>
<input type="checkbox" name="gre2"/>
</div>
<button type="submit">Submit Form</button>
</form>

How to re-render previous page when validating form

I have a controller that renders a chores.html page with various sorts of chores.
#GetMapping("/chores")
public String getDueChores(Model model)
{
var tomorrow = LocalDate.now().plusDays(1);
var chores = choreRepository.findByDueBefore(tomorrow);
model.addAttribute("choresDue", chores);
model.addAttribute("allChores", choreRepository.findAll());
model.addAttribute("chore", new Chore());
model.addAttribute("chores", new ArrayList<Chore>());
return "chores";
}
The same page also has a form for adding a new chore. Here's the controller method:
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore)
{
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}
Now I want to display the errors if the new chore is invalid.
Attempt 1:
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore,
Errors errors)
{
if (errors.hasErrors())
{
return "chores";
}
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}
This shows the error message, but sense it's not going through the logic in the GET controller method, all the other chores on the page don't get populated.
Attempt 2:
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore,
Errors errors)
{
if (errors.hasErrors())
{
return "redirect:/chores";
}
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}
This doesn't work because the error information is lost on the redirect, and the errors aren't displayed.
Could anyone point me in the right direction, please?
Here's chores.html, if it's relevant:
<body>
<h1>Due today...</h1>
<form method="post" th:action="#{/chore}" th:object="${chore}">
<ul>
<li th:each="chore: ${choresDue}">
<input type="checkbox" name="choreIds" th:value="${chore.id}"/>
<label th:text="${chore.name}"></label>
</li>
</ul>
<input type="submit" value="Mark Chores Complete">
</form>
<form method="post" action="#" th:action="#{/chores}" th:object="${chore}">
<input type="text" th:field="*{name}" placeholder="Chore name">
<span class="validationError"
th:if="${#fields.hasErrors('name')}"
th:errors="*{name}">Chore name is invalid</span>
<br>
<input type="text" th:field="*{daysBetween}" placeholder="Do chore every # days">
<span class="validationError"
th:if="${#fields.hasErrors('daysBetween')}"
th:errors="*{daysBetween}">Chore name is invalid</span>
<br>
<input type="submit" value="Add chore">
</form>
<hr>
<h1>All Chores</h1>
<form th:method="delete" th:action="#{/deleteChore}" th:object="${chore}">
<ul>
<li th:each="chore: ${allChores}">
<input type="checkbox" name="choreIds" th:value="${chore.id}"/>
<label th:text="${chore.name} + ' every ' + ${chore.daysBetween} + ' days'"></label>
</li>
</ul>
<input type="submit" value="Delete selected chores">
</form>
</body>
Solution is to add Errors to the Model.
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore,
Errors errors,
Model model)
{
if (errors.hasErrors())
{
model.addAttribute("error", errors);
var tomorrow = LocalDate.now().plusDays(1);
var chores = choreRepository.findByDueBefore(tomorrow);
model.addAttribute("choresDue", chores);
model.addAttribute("allChores", choreRepository.findAll());
return "chores";
}
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}

Spring MVC Page

I have a question, I didn't understand why this part of the code(where is registration) Spring doesn't find even if I wrote an url. But the same code in another part, for example, add a new book or add the new author of the book is working correctly it added everything into the database and send me into another page. But if I register the person and click submit it always shows me 400 - bad request error. Please help me. What I wrote wrong?
This is my controller(doesn't work registration part with register book (not redirect to registerbook and doesn't add data into DB)):
#Controller
public class HelloController {
private static final Logger logger = Logger.getLogger(HelloController.class.getName());
#Autowired
#Qualifier("author")
private AuthorzDAO authorzDAO;
#Autowired
#Qualifier("book")
private BooksDAO booksDAO;
#Autowired
#Qualifier("borrow")
private BorrowsDAO borrowsDAO;
#Autowired
#Qualifier("person")
private PersonDAO personDAO;
#RequestMapping(value = "/",method = RequestMethod.GET)
public ModelAndView printHello() {
return new ModelAndView("hello", "command", new LoginPerson());
}
#RequestMapping(value = "/",method = RequestMethod.POST)
public String login(#ModelAttribute("SpringWeb")LoginPerson person, ModelMap model, HttpServletRequest request) {
model.addAttribute("info", personDAO.getInfromStudent(person.getEmail(), person.getPassword()));
model.addAttribute("takenbook", person.getEmail());
if (person.getEmail().equals("admin#admin.com") && person.getPassword().equals("admin")) {
logger.warning("AAAAA");
logger.warning(person.getEmail());
return "admin";
} else if(personDAO.checkPerson(person.getEmail(), person.getPassword()) == true){
logger.warning(personDAO.checkPerson(person.getEmail(), person.getPassword()).toString());
logger.warning("BBBBB");
logger.warning(person.getPassword());
return "personinfo";
} else {
return new ResponseStatusException().error();
}
}
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public ModelAndView registration() {
return new ModelAndView("registration", "person", new Person());
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String register(#ModelAttribute("person") Person person) {
logger.warning("Hello");
logger.warning(person.toString());
personDAO.connectPerson(person);
return "redirect:/registerbook";
}
#RequestMapping(value = "/registerbook", method = RequestMethod.GET)
public ModelAndView registerbook() {
//model.addAttribute("newborrow", new Borrows());
return new ModelAndView("registerbook", "newborrow", new Borrows());
}
#RequestMapping(value = "/registerbook", method = RequestMethod.POST)
public String regbook(#ModelAttribute("newborrow") Borrows borrows, ModelMap model) {
logger.warning(String.valueOf(borrows.getId()));
model.addAttribute("borrowid", borrows.getId());
model.addAttribute("personid", borrows.getStudentid());
model.addAttribute("bookid", borrows.getBookid());
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Timestamp todays30 = Timestamp.valueOf(dateFormat.format(today30));
Timestamp todayy = Timestamp.valueOf(dateFormat.format(today));
borrows.setTakendate(todayy);
borrows.setBroughtdate(todays30);
borrowsDAO.insertBorrow(borrows);
return "hello";
}
#RequestMapping(value = "/addauth", method = RequestMethod.GET)
public ModelAndView addauth() {
return new ModelAndView("addauthbooks", "adding", new Authorz());
}
#RequestMapping(value = "/example", method = RequestMethod.POST)
public String addingauthor(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id_author", authorz.getAuthorid());
model.addAttribute("fname_author", authorz.getName());
model.addAttribute("lname_author", authorz.getSurname());
logger.warning(String.valueOf(authorz.getAuthorid()));
logger.warning(authorz.getName());
logger.warning(authorz.getSurname());
authorzDAO.insertAuthorz(authorz);
return "example";
}
#RequestMapping(value = "/addbooks", method = RequestMethod.GET)
public ModelAndView addbook() {
return new ModelAndView("addbook", "addingbook", new Books());
}
#RequestMapping(value = "/admin", method = RequestMethod.POST)
public String addingbook(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authorid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
model.addAttribute("fragment", books.getFragment());
logger.warning(String.valueOf(books.getId()));
logger.warning(books.getName());
logger.warning(String.valueOf(books.getPagecount()));
booksDAO.insertBook(books);
return "admin";
}
#RequestMapping(value = "/deleteauth", method = RequestMethod.GET)
public ModelAndView deleteauthbooks() {
return new ModelAndView("deleteauthbooks", "deletingauthor", new Authorz());
}
#RequestMapping(value = "/admins", method = RequestMethod.POST)
public String deleteresult(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id", authorz.getAuthorid());
model.addAttribute("name", authorz.getName());
model.addAttribute("surname", authorz.getSurname());
authorzDAO.delete_book(authorz.getSurname());
return "admin";
}
#RequestMapping(value = "/deletebooks", method = RequestMethod.GET)
public ModelAndView deletebook() {
return new ModelAndView("deletebooks", "deletingbook", new Books());
}
#RequestMapping(value = "/nadmin", method = RequestMethod.POST)
public String deletebookresult(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
booksDAO.delete_book(books.getName());
return "admin";
}
#RequestMapping(value = "/borrow", method = RequestMethod.GET)
public ModelAndView borrows() {
return new ModelAndView("borrow", "borrowing", new LoginPerson());
}
#RequestMapping(value = "/res", method = RequestMethod.POST)
public String borrow(#ModelAttribute LoginPerson borrows, ModelMap model) {
logger.warning(borrows.getEmail());
List list_borrows = personDAO.searchStudent(borrows.getEmail());
logger.warning(list_borrows.toString());
model.addAttribute("borrow", list_borrows);
return "result";
}
#RequestMapping(value = "/changebook", method = RequestMethod.GET)
public ModelAndView change() {
return new ModelAndView("changebook", "changing", new Person());
}
#RequestMapping(value = "/changebook", method = RequestMethod.POST)
public String changebook(#ModelAttribute("changebook") Person point, ModelMap model, HttpServletRequest request) {
model.addAttribute("point", point.getPoint());
model.addAttribute("email", point.getEmail());
logger.warning("Upper");
logger.warning(String.valueOf(point.getPoint()));
logger.warning(point.getEmail());
logger.warning(request.getParameter("email"));
if(point.getPoint() != null && request.getParameter("email") != null) {
logger.warning("It works!!!");
personDAO.changeBook(point.getPoint(), request.getParameter("email"));
}
logger.warning("Down");
return "changebook";
}
}
This is my jsp of registration:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-05-19
Time: 17:48
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Registration</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center><h2>Person Information</h2></center>
<%--<form:form method = "post" action = "/springlab_war_exploded/admin" modelAttribute="person">--%>
<form:form method ="post" modelAttribute="person">
<fieldset>
<center>
<div id="legend">
<legend class="">Registration</legend>
</div>
</center>
<center>
<div class="control-group">
<!-- id -->
<label class="control-label" for="id">Id:</label>
<div class="controls">
<input type="number" id="id" name="id" placeholder="" class="input-xlarge">
<p class="help-block">Id can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<label class="control-label" for="name">First name:</label>
<div class="controls">
<input type="text" id="name" name="name" placeholder="" class="input-xlarge">
<p class="help-block">First name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<label class="control-label" for="surname">Last name:</label>
<div class="controls">
<input type="text" id="surname" name="surname" placeholder="" class="input-xlarge">
<p class="help-block">Last name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="" class="input-xlarge">
<p class="help-block">Please provide your Email</p>
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="pass">Password:</label>
<div class="controls">
<input type="password" id="pass" name="pass" placeholder="" class="input-xlarge">
<p class="help-block">Password should be at least 4 characters</p>
</div>
</div>
<div class="control-group">
<!-- Date -->
<label class="control-label" for="birthdate">Date:</label>
<div class="controls">
<input type="datetime" id="birthdate" name="birthdate" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your birthdate</p>
</div>
</div>
<div class="control-group">
<!-- Sex -->
<label class="control-label" for="gender">Sex:</label>
<div class="controls">
<input type="text" id="gender" name="gender" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your gender only M or F</p>
</div>
</div>
<div class="control-group">
<!-- Class -->
<label class="control-label" for="job">Job:</label>
<div class="controls">
<input type="text" id="job" name="job" placeholder="" class="input-xlarge">
<p class="help-block">Job can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- Point -->
<label class="control-label" for="point">Point:</label>
<div class="controls">
<input type="number" id="point" name="point" placeholder="" class="input-xlarge">
<p class="help-block">Point can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- Phone number -->
<label class="control-label" for="phonenumber">Phone number:</label>
<div class="controls">
<input type="tel" id="phonenumber" name="phonenumber" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your phone number</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Next</button>
</div>
</div>
</center>
</fieldset>
</form:form>
</body>
</html>
And my jsp register book
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-06-02
Time: 12:51
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register Book</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<%--<form:form class="form-horizontal" action='/springlab_war_exploded/login' method="post">--%>
<form:form class="form-horizontal" action="/springlab_war_exploded/login" method="post" modelAttribute="newborrow">
<fieldset>
<div id="legend">
<legend class="">Register Book</legend>
</div>
<div class="control-group">
<!-- id -->
<%--<label class="control-label" for="borrowid">Borrow Id:</label>--%>
<div class="controls">
<form:label path="id">Borrow Id:</form:label>
<form:input path="id"/>
<%--<input type="number" id="borrowid" name="borrowid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter borrow id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<%--<label class="control-label" for="personid">Person Id:</label>--%>
<div class="controls">
<form:label path="studentid">Person Id:</form:label>
<form:input path="studentid"/>
<%--<input type="number" id="personid" name="personid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Eneter person id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<%--<label class="control-label" for="bookid">Book Id:</label>--%>
<div class="controls">
<form:label path="bookid">Book Id:</form:label>
<form:input path="bookid"/>
<%--<input type="number" id="bookid" name="bookid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter book id</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Submit</button>
</div>
</div>
</fieldset>
</form:form>
</body>
</html>
Don't need "/" while redirecting or forwarding a request.
Can you try "redirect:registerbook";

spring return object on button click out of list

Hi guys hope you can help me, because i cant get further at the moment
I have my Controller.
#RequestMapping(value="/kundenseite", method= RequestMethod.GET)
public String kundenLogin(ModelMap model) {
if(kundeComponent.getKunde() != null) {
List<Restaurant> restaurants = restaurantService.alleRestaurants();
model.addAttribute("restaurants", restaurants);
return "kundenseite";
}else {
return "redirect:/kunde/login";
}
}
#RequestMapping(value="/kundenseite", method= RequestMethod.POST)
public String kundenLoginAnswer(ModelMap model, #ModelAttribute Restaurant restaurant) {
System.out.println(restaurant.toString());
return "kundenseite";
And my jsp file
<%# include file="common/header.jspf" %>
<div class="jumbotron text-center">
<h1>MiMiMi Lieferservice</h1>
<p>Der schnellste Lieferservice von Passpick</p>
</div>
<div style="margin-right:auto; margin-left:auto; width: 33%">
<h2 style="text-align: center">Restaurant wählen</h2>
<div class="well">
<c:forEach items="${restaurants}" var="restaurant">
<form:form modelAttribute="${restaurant}" method="post">
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.name}</div>
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.restaurantTyp}</div>
<button type="submit">Bestellen</button>
</form:form>
<br style="clear:both;" />
</c:forEach>
</div>
</div>
</body>
</html>
If the user presses a button i want to return a restaurant.
But i don't know how to make that happen, my thought was to use a form but i cant get it to send a complete restaurant object back
If there is no solution for this i have to write the id with the button.
You need input hidden inside the form tab as below input hidden:
<input type="hidden" name="name" value="${restaurant.name}">
<input type="hidden" name="restaurantTyp" value="${restaurant.restaurantTyp}">

How to pass variable number of parameters from jsp page to the java controller

I have a jsp page and a controller with fillowing functionality:
java controller code:
#Controller
public class AddNewItemController {
#RequestMapping(value = "/newItem/submit", method = RequestMethod.POST)
public String getDataForInterval4(#RequestParam("itemId") String itemId, #RequestParam("product1SkusCnt") String product1SkusCnt, #RequestParam("itemName") String itemName, HttpServletRequest request) {
return "ItemSubmitted";
}
}
my main jsp file that submits to controller:
<center>
<table>
<tr>
<td>How many items do you have?</td>
<td> <input type="number" name="productsCnt" id="productsCnt" size="2" min="1" value="1" onchange="productCount()"/> </td>
</tr>
</table>
</center>
<form action="/newItem/submit" method="post">
<br /><br />
<div id="outerDivContainer">
<div id="product1Div" name="product1Div" >
<hr /> Product 1 Name: <input id="product1Name" /> Product 1 ID: <input id="product1ID" /> How many SKUs of Product 1? <input id="product1SkusCnt" type="number" size="2" min="1" value="1" onchange="skusCount(1)"/> <br /><br />
<div id="skusContainer1">
<div id="sku1Div">
SKU 1 Name: <input id="sku1"/>
</div> <br />
</div>
</div>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
<script>
function productCount() {
console.log("onchange product");
document.getElementById('outerDivContainer').innerHTML = "";
var cnt = document.getElementById('productsCnt').value;
console.log("cnt="+cnt);
for (i=0;i<cnt;i++){
var newEl = document.createElement('div');
newEl.class='prodRow';
j=i+1;
newEl.innerHTML = '<div id="product'+j+'Div"><hr /> Product '+j+' Name: <input id="product'+j+'Name" /> Product '+j+' ID: <input id="product'+j+'ID" /> How many SKUs of Product '+j+'? <input id="product'
+j+'SkusCnt" type="number" size="2" min="1" value="1" onchange="skusCount('+
j+')" /> <br /><br /> <div id="skusContainer'+j+'"><div id="sku1Div"> SKU 1 Name: <input id="sku1"/></div> <br /> </div></div>';
document.getElementById('outerDivContainer').appendChild(newEl);
}
}
function skusCount(productId){
console.log("onchange skus, product id= "+productId+";");
var skusCnt = document.getElementById('product'+productId+'SkusCnt').value;
console.log("skusCnt="+skusCnt);
document.getElementById('skusContainer'+productId).innerHTML = "";
for (i=0;i<skusCnt;i++){
var newEl = document.createElement('div');
newEl.class='skuRow';
j=i+1;
newEl.innerHTML = '<div id="sku'+j+'Div">SKU '+j+' Name: <input id="sku'+j+'" /> </div> <br />';
document.getElementById('skusContainer'+productId).appendChild(newEl);
}
}
</script>
ItemSubmitted.jsp is just a jsp file that confirms successful item submission.
The problem is I don't know how many items will be passed to the controller, or how many skus each item might have.
What would be a suggested approach to this problem? Thanks in advance!
The answer to my question is much simpler than I expected. All I have to do is just know how many parameters I will pass and their names. I don't have to specify it in the controller as #RequestParam("itemId") String itemId, #RequestParam("product1SkusCnt") etc.
Instead I should only pass a request as an argument:
#RequestMapping(value = "/newItem/submit", method = RequestMethod.POST)
public String getDataForInterval4(HttpServletRequest request) { return "ItemSubmitted"}
I can call each of those passed parameters in the controller by doing the following:
request.getParameter("product"+i+"SkusCnt"))
Just need to make sure that I pass the total count of products also.
Hope this helps someone.

Categories