I have two objects Employee and Department Employee contains the dept_id. What i want to do is display the content of Employee in a table in jsp page. But instead of displaying dept_id i want to display dept_name from Department table. So far i have my controller method as:
public ModelAndView viewEmployee(HttpServletRequest request,
HttpServletResponse response) throws Exception {
List<Employee> employeeList = employeeService.getAllEmployee();
List<Department> departmentList = new ArrayList<Department>();
for (Employee e : employeeList) {
departmentList.add(departmentService.getDepartment(e.getDept_id()));
}
Map<String, Object> model = new HashMap<String, Object>();
model.put("employee", employeeList);
model.put("department", departmentList);
return new ModelAndView("viewEmployee", "model", model);
}
viewEmployee.jsp
<table border="1px" bordercolor="black" width=80% align="center">
<tr>
<td>Name</td>
<td>Gender</td>
<td>Salary</td>
<td>Department</td>
<td>Action</td>
</tr>
<c:forEach items="${model.employeeList}" var="element">
<tr>
<td><c:out value="${element.name}" /></td>
<td><c:out value="${element.gender}" /></td>
<td><c:out value="${element.salary}" /></td>
<td>display Department Name here </td>
<td><a
href="<c:url value="editEmployee.htm">
<c:param name="emp_id" value="${element.id}"/>
</c:url>
">Edit</a>
<a
href="<c:url value="deleteEmployee.htm">
<c:param name="emp_id" value="${element.id}"/>
</c:url>
">Delete</a>
</td>
</tr>
</c:forEach>
</table>
Any help? I am not being able to display the map content to the jsp page.
it should be <c:forEach items="${model.employee}" var="element">
Also department should be a property of Employee , so that you can use ${employee.department.name}
Related
===============================update====================================
try{
// snip
while (rs.next()) {
BookListEntity entity = new BookListEntity();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setSubject(rs.getString("subject"));
entity.setInsertTime(rs.getString("insert_time"));
entity.setRentalCheck(rs.getInt("rental_check"));
BookList.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("TestList",BookList);
this is first controller
-> get BookList to "TestList" and move to view(jsp)
<c:forEach var="listValue" items="${TestList}">
<form action="rentalandreturn.do" method="post">
<tr class="active">
<td><c:out value="${listValue.id}" /></td>
<td><c:out value="${listValue.name}" /></td>
<td><c:out value="${listValue.subject}" /></td>
<td><c:out value="${listValue.insertTime}" /></td>
<c:if test="${listValue.rentalCheck eq 1}">
<td>
<input type="submit" value="貸し出しする" />
</td>
</c:if>
<c:if test="${listValue.rentalCheck eq 0}">
<td><input type="submit" value="返納する" /></td>
</c:if>
</tr>
</form>
</c:forEach>
This is jsp(view) code
->and I want to use c:out value something do
#Controller
public class Rentalandreturn {
#RequestMapping(value = "rentalandreturn", method = RequestMethod.POST)
public String rentalandreturn(HttpServletRequest request, Model model) {
//How can i get c:out value?
String id = (String) request.getAttribute("value");
System.out.println(id);
return "BookList";
}
}
and this is second java code(Controller)
-> I want to get c:out value what I print view page.
is there any way to get c:out value in Controller(=java code)?
sorry about my English. if you don't understand my question. say to comment.
you can not read directly in controller class as it is in , better to write a javascript code to to read the data and from that on an action you can send to controller.
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'm trying to make a CRUD application using Spring MVC, but whenever I click the edit button to update an entry in a row, my jsp page to edit an entry (wizardeditform.jsp) has the 'designation' and 'wand' inputs filled in from that entry with the correct values. I would like all the input boxes to have the default values from that row, not just the 'wand' and 'designation' input boxes. Does anyone have any idea why this is happening? (Ive been following this tutorial: http://www.javatpoint.com/spring-mvc-crud-example)
wizardeditform.jsp
<h1>Edit Witch or Wizard</h1>
<form:form method="POST" action="/WizardingWorld/editsave">
<table>
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>First name :</td>
<td><form:input path="firstname"/></td>
</tr>
<tr>
<td>Last name :</td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation"/></td>
</tr>
<tr>
<td>School and house :</td>
<td><form:input path="schoolAndHouse" /></td>
</tr>
<tr>
<td>wand :</td>
<td><form:input path="wand" /></td>
</tr>
<tr>
<td>Blood Type</td>
<td><form:input path="bloodtype" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
Controller class
// displays form to input data, "command" is request attr. used to display
// object data into form
#RequestMapping("/wizardform")
public ModelAndView showform() {
return new ModelAndView("wizardform", "command", new Wizard());
}
// saves object into database. The #ModelAttribute puts request data into
// model object.
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("wizard") Wizard wizard) {
dao.save(wizard);
return new ModelAndView("redirect:/viewwizard");// will redirect to
// viewwizard request
// mapping
}
// provides list of employees in model object
#RequestMapping("/viewwizard")
public ModelAndView viewwizard() {
List<Wizard> list = dao.getWizards();
return new ModelAndView("viewwizard", "list", list);
}
// It displays object data into form for the given id. The #PathVariable
// puts URL data into variable
#RequestMapping(value = "/editwizard/{id}")
public ModelAndView edit(#PathVariable int id) {
Wizard wizard = dao.getWizardById(id);
return new ModelAndView("wizardeditform", "command", wizard);
}
// updates model object
#RequestMapping(value = "/editsave", method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("wizard") Wizard wizard) {
dao.update(wizard);
return new ModelAndView("redirect:/viewwizard");
}
The first image is the jsp page to view all the table entries, and the second image is is the wizardeditform.jsp , right after clicking the edit button on the previous page with all the entries.
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}">
How to remove some of the "magic value" impression of "command" modelName parameter to create a ModelAndView ?
Example:
#RequestMapping(value = "/page", method = GET)
public ModelAndView render() {
return new ModelAndView("page", "command", new MyObject());
}
One hope was to use a spring constant such as
new ModelAndView("page", DEFAULT_COMMAND_NAME, new MyObject());
I found "command" in the 3 following classes of the spring-webmvc-3.0.5 sources jar:
$ ack-grep 'public.*"command"'
org/springframework/web/servlet/mvc/BaseCommandController.java
140: public static final String DEFAULT_COMMAND_NAME = "command";
org/springframework/web/servlet/mvc/multiaction/MultiActionController.java
137: public static final String DEFAULT_COMMAND_NAME = "command";
org/springframework/web/servlet/tags/form/FormTag.java
56: public static final String DEFAULT_COMMAND_NAME = "command";
The problem is :
BaseCommandController is deprecated
We don't use MultiActionController and FormTag
When you use on your jsp spring tag <form:form>
<form:form method="POST" action="../App/addCar">
<table>
<tr>
<td><form:label path="brand">Name</form:label></td>
<td><form:input path="brand" /></td>
</tr>
<tr>
<td><form:label path="year">Age</form:label></td>
<td><form:input path="year" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
you must write:
#RequestMapping(value = "/car", method = RequestMethod.GET)
public ModelAndView car() {
return new ModelAndView("car", "command", new Car());
}
Because the spring framework expects an object with name "command".
Default command name used for binding command objects: "command".
This name to use when binding the instantiated command class to the request.
http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/web/servlet/mvc/BaseCommandController.html
But when you use html form <form> you can write:
#RequestMapping(value = "/car", method = RequestMethod.GET)
public ModelAndView car() {
return new ModelAndView("car", "YOUR_MODEL_NAME", new Car());
}
But on your page
<form method="POST" action="../App/addCar">
<table>
<tr>
<td><form:label path="YOUR_MODEL_NAME.brand">Name</form:label></td>
<td><form:input path="YOUR_MODEL_NAME.brand" /></td>
</tr>
<tr>
<td><form:label path="YOUR_MODEL_NAME.year">Age</form:label></td>
<td><form:input path="YOUR_MODEL_NAME.year" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
I wouldn't use the default name. If the object is a User call it user, if it's Item call it item. If you need a default (for example - for a generic framework), define your own constant.