I need get data from html to controller with press button also Html data as list.
<thead>
<tr>
<th>Company Name</th>
<th>Book Name</th>
<th>Author</th>
<th>Price</th>
<th>Order</th>
</tr>
</thead>
<tbody>
<tr th:each="Books: ${Books }">
<td th:text="${Books.CompanyName}" />
<td th:text="${Books.BookName}" />
<td th:text="${Books.AuthorName}" />
<td th:text="${Books.Price}" />
<td th:button class="Order-Button" type="button" >Order</button> </td>
Also this is my Controller
#Autowired
private BookRep bookRep;
#RequestMapping(value = "/BookOrder")
ModelAndView submitBookOrder(){
ModelAndView mav = new ModelAndView("BookOrder");
mav.addObject("Books", bookRep.findAll());
return mav;
}
My expect to when user press take order button it will get row datas in controller
I wrote demo code for you. I think it will be useful for you. You can understand what you want by looking at the code
#GetMapping("/Books/{id}")
public String books(#PathVariable("id") Long id, Model model){
model.addAttribute("Books", bookService.getById(id));
return "book-list";
}
<-td> <-a th:href="#{/Books/{id}(id = ${book.id})}">
<-button type="submit" class="btn btn-info col-2" style="min-width: fit-content"> Books List<-/button>
Related
I know theres a similar question in stackoverflow like mine. I tried every answer that i could from this question none of these worked: Thymeleaf using path variables to th:href
Can you help me what did i wrong in my thymeleaf page?
URL that i would like to reach: localhost:8081/students/{stu_id}
My GetMapping looks like:
#GetMapping("/students")
public ModelAndView viewStudentPage() {
List<Student_Dim> listStudent = studentService.getAllStudents();
return new ModelAndView("students","students", listStudent);
}
#GetMapping("/students/{id}")
private ModelAndView getInfo(#PathVariable("id") String stu_id){
Student_Dim student = studentService.getStudentById(stu_id);
return new ModelAndView("student","student",student);
}
Href that i use (students.html):
<tbody>
<tr th:each="student : ${students}">
<td th:text="${student.stu_fname}">First Name</td>
<td th:text="${student.stu_lname}">Last Name</td>
<td th:text="${student.dep_code}">Department Code</td>
<td th:text="${student.fac_code}">Faculty Code</td>
<td th:text="${student.loc_code}">Location Code</td>
<td th:text="${student.marriage_status}">Marriage Status</td>
<td th:text="${student.address}">Address</td>
<td>
Edit
</td>
</tr>
</tbody>
You are using thymeleaf expression inside <a> tag. You have to use th:href instead of href.
<td>
<a th:href="#{/students/{id}(id=${student.stu_id})}">Edit</a>
</td>
I'm building a blog in Java using Spring and Hibernate. I can't seem to figure out what is going on but I keep running into a Bad Request error when I try to add (save) a post and I can't figure out where I am wrong in my mapping.
Error message:
Controller:
#Controller
#RequestMapping("/blog")
public class IndexController {
#Autowired
private PostService postService;
#RequestMapping("/list")
public String showPage (Model theModel) {
// get posts from DAO
List<Post> thePosts = postService.getAllPosts();
// add the posts to the model
theModel.addAttribute("allPosts", thePosts);
return "allPosts";
}
#GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
//create model attribute to bind form data
Post thePost = new Post();
theModel.addAttribute("post", thePost);
return "postSuccess";
}
#PostMapping("/savePost")
public String savePost(#ModelAttribute("post") Post thePost) {
// save the post using our service
postService.savePost(thePost);
return "allPosts";
}
Form snippet:
<div class="table" id="container">
<form:form action="savePost" modelAttribute="post"
method="POST">
<table>
<tbody>
<tr>
<td><label>Title:</label></td>
<td><form:input path="title" /></td>
</tr>
<tr>
<td><label>Author:</label></td>
<td><form:input path="author" /></td>
</tr>
<tr>
<td><label>Date:</label></td>
<td><form:input path="date" /></td>
</tr>
<tr>
<td><label>Post:</label></td>
<td><form:input path="post" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear: both;"></div>
<p>
Back to Home Page
</p>
</div>
All other pages are working correctly so far, just can't add an actual blog post. Any help is greatly appreciated.
I figured this out and it is similar to another spring issue I had in the past.
I don't think this really follows a lot of conventional function/design theory, but I added some code into the controller and it now works. I can add a post easily.
First thing was, I removed the #ModelAttribute tag from my "savePost" method. Then I added #RequestParam to my method parameters. Added a little bit of logic and now it saves to the database and then appears on the blog. Good stuff.
Code:
#PostMapping("/savePost")
public String savePost(#RequestParam("author") String author,
#RequestParam("title") String title, #RequestParam("date") String date,
#RequestParam("post") String post) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date theDate = sdf.parse(date);
// save the customer using our service
Post thePost = new Post();
thePost.setAuthor(author);
thePost.setDate(theDate);
thePost.setTitle(title);
thePost.setPost(post);
postService.addPost(thePost);
System.out.println(thePost.toString()); //testing
return "success";
}
jsp:
<form:form action="savePost" modelAttribute="post" method="POST">
<table>
<tbody>
<tr>
<td><label>Title:</label></td>
<td><input id="title" type="text" name="title"></td>
</tr>
<tr>
<td><label>Author:</label></td>
<td><input id="author" type="text" name="author"></td>
</tr>
<tr>
<td><label>Date:</label></td>
<td><input id="date" type="text" name="date"></td>
</tr>
<tr>
<td><label>Post:</label></td>
<td><textarea id="post" type="text"
name="post"></textarea></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form:form>
I want to generate tables in jsp page using data I got from Map in java. I use which use map value for define 'item'. But, The name of map value that I want to put on 'item' needs value from another map.
To be clear, here my jsp code;
<c:forEach var="wilayahProvinsi" items="${model.kodeKabupatenList}">
<div data-role="page" id="kode${wilayahProvinsi.ID2012}">
<div data-role="header" data-position="inline" data-fullscreen="true">
Back
<h1>${wilayahProvinsi.NAMA}</h1>
</div>
<div class="container">
<table id="example1" class="display nowrap" >
<thead>
<tr>
<th>Kode Komoditas</th>
<th>Jenis Barang</th>
<th>Nilai Konsumsi</th>
<th>Nilai Imputasi</th>
<th>Nilai Konsumsi Akhir</th>
<th>Persentase trhdp Total</th>
<th>Persentase trhdp Kelompok</th>
<th>Persentase trhdp Subkelompok</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tbody>
<!-- this is the problem -->
<c:forEach var="pekerjaanku" items="${model.pekerjaankuList$wilayahProvinsi.ID2012}">
<tr>
<td>${pekerjaanku.kode_komoditas}</td>
<td id="jenis_barang">${pekerjaanku.jenis_barang}</td>
<td style="text-align: right">${pekerjaanku.nilai_konsumsi}</td>
<td style="text-align: right">${pekerjaanku.nilai_imputasi}</td>
<td style="text-align: right">${pekerjaanku.nilai_konsumsi_akhir}</td>
<td style="text-align: right">${pekerjaanku.persentase_total}</td>
<td style="text-align: right">${pekerjaanku.persentase_kelompok}</td>
<td style="text-align: right">${pekerjaanku.persentase_subkelompok}</td>
<td><a href="kotaEdit?id=${pekerjaanku.kode_komoditas}" class="ui-btn ui-mini ui-corner-all ui-icon-edit
ui-btn-icon-left">Edit</a></td>
<td><a href="kotaDelete?id=${pekerjaanku.kode_komoditas}" class="ui-btn ui-mini ui-corner-all ui-icon-delete
ui-btn-icon-left" onclick="return confirm('Yakin ingin menghapus komoditas ${pekerjaanku.jenis_barang}?')">
Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<table>
<tr>
<td colspan="8">Tambah Komoditas Baru</td>
<td colspan="2">Download CSV</td>
</tr>
</table>
</div>
</div>
</c:forEach>
This is my Java code;
#RequestMapping("/jelajahPekerjaanKota")
public ModelAndView getPekerjaanKotaList() {
List<KodeKabupaten> kodeKabupatenList = usersService.getSpecifiedKodeKabupatenList();
Map<String, Object> model = new HashMap<String, Object>();
model.put("kodeKabupatenList", kodeKabupatenList);
for(KodeKabupaten kodeKabupaten : kodeKabupatenList){
model.put("pekerjaankuList" + kodeKabupaten.getID2012(), pekerjaankuService.getPekerjaankuList(kodeKabupaten.getID2012()));
}
return new ModelAndView("/provinsi/jelajahPekerjaanKota", "model", model);
}
To be clear, the objects in Map model is;
model.kodeKabupatenList which has attributes: NAMA, ID2012, PROV, and KAB
model.pekerjaankuList3171 which has attributes: kode_komoditas, jenis_barang, ...
model.pekerjaankuList3172 , the attributes are same with above
model.pekerjaankuList3173 , same with above
my problem is how to get all model.pekerjaankuList** in jsp with looping? I can not run this code in jsp;
<c:forEach var="pekerjaanku" items="${model.pekerjaankuList$wilayahProvinsi.ID2012}">
I have the following form in my Thymleaf page:
<div class="panel-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Issue Date</th>
<th>Payment Schedule</th>
<th>Total</th>
<th>Status</th>
<th>Start Date</th>
<th>End Date</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.issueDate}"></td>
<td th:text="${p.paymentSchedule}"></td>
<td th:text="${p.total}"></td>
<td th:text="${p.status}"></td>
<td th:text="${p.rentalPeriod.startDate}"></td>
<td th:text="${p.rentalPeriod.endDate}"></td>
<td>
<form style='float:left; padding:5px; height:0px' th:object="${po}" th:method="post" th:action="#{'/dashboard/makeAndSendInvoice(email=${po.Email})'}">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
I have tried to send the value of po.Email to the method.
I thought the th:action="#{'/dashboard/makeAndSendInvoice(email=${po.Email})'}"
will make a link like dashboard/makeAndSendInvoice/{Email}
So i tried to get it in the method like this:
#RequestMapping(method=POST, path="makeAndSendInvoice")
public String makeAndSendInvoice(#PathVariable("email") String email){
System.out.println("Invoice is sent to..................."+email);
return "Invoice";
}
but it seems to me it does not work, since it does not recognize my method.
So how can recieve the po.Email in my method
Change th:action to:
th:action="#{/dashboard/makeAndSendInvoice/{email}(email=${po.Email})}"
and add the PathVariable in the RequestMapping value like:
#RequestMapping(method=POST, path="/dashboard/makeAndSendInvoice/{email:.+}")
public String makeAndSendInvoice(#PathVariable("email") String email) {
From Thymeleaf - Link URLs:
Variable templates are also allowed in URL paths, like
#{/order/{orderId}/details(orderId=${orderId})}
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
view
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
view
From Spring - URI Template Patterns:
In Spring MVC you can use the #PathVariable annotation on a method
argument to bind it to the value of a URI template variable:
#RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(#PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}
I'm writing an application which is very basic Online Shop. I got phones category here (2 phones available), and after click one of them new page with info about phone displays, under description I got button "add to cart", and here is a thing - I want that after click the button all informations about that phone will go to database and display them at the same time in page "cart". Connection to db and managing data in IDE isn't problematic for me, but how "Add to Cart" button will know which phone I chose (phone1 or phone2)? I should create another Controller for Cart or here is another solution for that?
PhoneController:
#Controller
#RequestMapping
public class PhoneController {
DBConnection db = new DBConnection();
Cart cart;
#RequestMapping(value="/phone1.html", method = RequestMethod.GET)
public ModelAndView phone1Page() {
ModelAndView phone1 = new ModelAndView("Phone1");
return phone1;
}
#RequestMapping(value="/phone2.html", method = RequestMethod.GET)
public ModelAndView phone2Page() {
ModelAndView phone2 = new ModelAndView("Phone2");
return phone2;
}
#RequestMapping(value="/cart.html", method = RequestMethod.POST)
public ModelAndView addToChart(){
ModelAndView cart = new ModelAndView("Cart");
return cart;
}
}
Phone1.jsp:
<form action="/OnlineShop/cart.html" method="post">
<div style="padding-right: 40px">
<table border="1">
<tr>
<td>Name</td>
<td>iPhone 6</td>
</tr>
<tr>
<td>Company</td>
<td>Apple</td>
</tr>
<tr>
<td>Type</td>
<td>Phone</td>
</tr>
<tr>
<td>Price</td>
<td>400$</td>
</tr>
</table>
<input type="submit" value="Add to Cart"/>
</div>
</form>
Cart.jsp:
<div style="padding-right: 40px">
<table border="1">
<tr>
<td>ID</td>
<td>Product</td>
<td>Name</td>
<td>Company</td>
<td>Type</td>
<td>Price</td>
<td>Action</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>OnlineShop</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and spring-dispatcher-servlet.xml:
<context:component-scan base-package="com.damian.controller" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Do a POST request to your /cart.html mapping with a request parameter for example: /cart.html?selected=iPhone6. Alternatively you could add form data to your post request with the information about the selected phone. I assume you have the phones also in a database with some sort of identifier, if you hide this identifier in your form then you could easily see which device was selected.
This is one way of solving the problem.
<form action="/OnlineShop/cart.html?selectedPhone=iPhone6" method="post">
<div style="padding-right: 40px">
<table border="1">
<tr>
<td>Name</td>
<td>iPhone 6</td>
</tr>
<tr>
<td>Company</td>
<td>Apple</td>
</tr>
<tr>
<td>Type</td>
<td>Phone</td>
</tr>
<tr>
<td>Price</td>
<td>400$</td>
</tr>
</table>
<input type="submit" value="Add to Cart"/>
</div>
</form>
And check the request parameter in your controller:
#RequestMapping(value="/cart.html", method = RequestMethod.POST)
public ModelAndView addToChart(#RequestParam String selectedPhone){
ModelAndView cart = new ModelAndView(selectedPhone);
return cart;
}
If you want all informations about the phone will go to database and display them at the same time in page cart you can try to add commandName like this:
But before you should create a dto class for ex: named PhoneClass
class public PhoneClass{
private name ...;
private ...
// and
setters and getters
}
<form action="/OnlineShop/cart.html" method="post" commandName="phoneInfo">
<div style="padding-right: 40px">
<table border="1">
<tr>
<td>Name</td>
<td>iPhone 6</td>
</tr>
...
<input type="submit" value="Add to Cart"/>
</div>
</form>
And in your controller you can do like this:
#RequestMapping(value="/cart.html", method = RequestMethod.POST)
public String someAction(#ModelAttribute("phoneInfo") PhoneClass phoneInfo, Model model) {
// TODO save un database attributes of `PhoneClass`
model.addAttribute("phoneInfo", phoneInfo);
return "somepage";
}
And in your page Cart.jspyou can use foreach of jstl to retrieve data from atrribute phoneInfo and put them in Cart.jsp like ths:
<div style="padding-right: 40px">
<table border="1">
<tr>
<c:forEach var="element" items="${phoneInfo}" varStatus="status">
<td> Name</td> <td>${status.name}</td>
....
</c:forEach>
</div>