Spring: mapping string and numbers with RequestMapping - java

I have the following form in Spring:
<form:form method="post" action="addprice.html" commandName="addprice">
<form:input path="name" />
<form:input path="price" />
<input type="submit" value="<spring:message code="Add price"/>"/>
</form:form>
And I need to pass the parameters to the following function:
#RequestMapping("/addprice")
public String addPrice(
// WHAT I NEED TO WRITE HERE?
)
{
// function code
}
What I need to write between parentesys in the previous function in order to retrieve "name" and "price"?
I tried using #ModelAttribute but it seems to work only with entities and I don't have a unique entity in this case but just two simple parameters.

Use the #RequestParam annotation :
#RequestMapping("/addprice")
public String addPrice(#RequestParam String name, #RequestParam double price)
{
// function code
}

Related

How to use the two Modal Class attribute in a Spring MVC Form in java

New Registeration Form
Step 1: UserLoginDTO.java
private String userName;
private String password;
Step 2: UserInfoDTO.java
private String firstName;
private String lastName;
Step 3 : Navigating to the Registration Form
http://localhost:8080/Demo/navigate/customerRegisterForm
Controller :
#Controller
#RequestMapping("/navigate")
public class NavigationController {
#RequestMapping("/customerRegisterForm")
public String customerRegisterForm(Map modelmap) {
System.out.println("Entering the New Customer Registarion Portal... ");
UserInfoDTO infoDto = new UserInfoDTO();
UserLoginDTO loginDto = new UserLoginDTO();
modelmap.put("infoDto", infoDto);
modelmap.put("loginDto", loginDto);
return "customer/newCustomer";
}
}
Step 4 : newCustomer.jsp
<form:form method="post" modelAttribute="loginDto">
<form:input path="userName"/>
<form:input path="password"/>
<form:input path="firstName"/>
<form:input path="lastName"/>
<input type="submit" value="Add Employee"/>
</form:form>
NOTE: In Step 3, two model class are added into the modelmap and in step 4 modelAttribute="loginDto" is alone used. So the Below is error is thrown. org.springframework.beans.NotReadablePropertyException: Invalid property 'firstName' of bean class [com.pharmacy.dto.UserLoginDTO] I need to use the both model class in the view part
Add a new class FormDto having your two existing model as attribute.
public class FormDto {
private UserLoginDto loginDto;
private UserInfoDto infoDto;
//......add getter/setter
}
Modify your controller to send FormDto as modelAttribute.
#RequestMapping("/customerRegisterForm")
public String customerRegisterForm(Map modelmap) {
System.out.println("Entering the New Customer Registarion Portal... ");
FormDto formDto = new FormDto();
modelmap.put("formDto", formDto);
return "customer/newCustomer";
}
Finally, change your form attributes.
<form:form method="post" modelAttribute="formDto">
<form:input path="loginDto.userName"/>
<form:input path="loginDto.password"/>
<form:input path="infoDto.firstName"/>
<form:input path="infoDto.lastName"/>
<input type="submit" value="Add Employee"/>
</form:form>

Spring MVC how to display data from database into a table

I am very new with SPRING MVC so really I dont know much about it as of the moment. I want to display all the fields in the database in a table view how do I do this?
in my controller
#RequestMapping(value = "task", method = RequestMethod.GET)
public String taskList(Map<String, Object> model) {
model.put("task", taskRepository.findAll());
return "/tasks/list";
}
my jsp:
<%#include file="/WEB-INF/views/includes/header.jsp"%>
<h4 class="form-header">${title}</h4>
<div class="forms col-md-12 bounceInDown mainContent" data-wow-delay="0.2s">
<table class="table table-striped">
<thead>
<tr>
<th>Task ID</th>
<th>Task Name</th>
<th>Task Description</th>
</tr>
</thead>
<tbody>
<c:if test="${empty task}">
<tr>
<td colspan="8">No task to Display</td>
</tr>
</c:if>
<c:if test="${not empty task}">
<c:forEach items="${tasks}" var="task">
<tr class="">
<td>${task.taskid}</td>
<td>${task.taskName}</td>
<td>${task.taskDescription}</td>
<td>
<fmt:message key="task.list.status.text.${task.status}" />
</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
</div>
<%#include file="/WEB-INF/views/includes/footer.jsp"%>
i dont have anything inside my taskRepository atm
For the starters:
#RequestMapping(value = "task", method = RequestMethod.GET)
public String taskList(Map<String, Object> model) {
model.put("task", taskRepository.findAll());
return "/tasks/list";
}
You should return some object you have created instead of String value. Let's asume you want to transfer two fields to you page lets name them field1 and field2. Now create your Data Transfer Object:
public class MyEntityDto{
private String filed1;
private String field2;
//Getter and setter method
.
.
.
}
Now your controller should look something like this:
#Autowired
SomeSevice someService;
#RequestMapping(value = "task", method = RequestMethod.GET)
#ResponseBody
public List<MyEntityDto> taskList(Map<String, Object> model) {
List<MyEntityDto> dtoList = someService.findALl();
return dtoList;
}
Your service from the other hand should look something like this:
#Service
public class SomeService(){
#Autowired
TaskRepository taskRepository;
public List<MyEntityDto> findAll(){
return assemblyTasks(taskRepository.findAll());//TODO implement method assemblyTasks
}
}
Notice that I put your repository usage into the service.This is the way it supposed to be done. You should use services in order to fetch data from your database and than you want to return your data using specificlly design for that purpose object - Data Transfer Object.
I leave the implementation of assemblyTask method to you. What you need to do there is to assign fields you want to pass from entity to view through your dto object. Generally you would want to have an assembler class for every DTO object but for the sake of simplicity I introduced the idea by using method. If you want to read more about DTO, view this post:
getting-value-of-invalid-field-after-methodargumentnotvalidexception
If you are completely new to the Spring world I recommend also find some basics web tutorials, for example here:
gonetoseries

How do I pass the dropdown select value to a button click in the controller and search against the value in data base?

here is the controller
#RequestMapping(value = "/submitrule", method = RequestMethod.POST)
public String addruleSerch(#ModelAttribute("SpringWeb") Rule obj2, ModelMap model) {
model.addAttribute("Select", obj2.getId());
System.out.println("********" + obj2.getId());
ruleApi.getRule(obj2.getId());
model.addAttribute("listrule", ruleApi.getRule(obj2.getId()));
return "redirect:/hello";
}
here is the html....
<form action="/CommissionTool/submitrule" method="post">
<table>
<tr>
<td><select name="Select"><c:forEach items="${listRules}" var="rule">
<option value="${rule.id}">
<c:out value="${rule.id}" />
</option>
</c:forEach>
</select>
</td>
<td><input type="submit" onClick="addRow('in_tbl_name')" VALUE="Add New"></td>
</tr>
</table>
</form>
How could i fix this.. please help me
Thanks in Advance...
Well you need to do several changes in your code, but is pretty near.
You need to send the object you want to use as modelAttribute to the view the first time.
In your html you need to say to the form which is the object to render, your model attribute
Create a POST method in your controller to retrieve the object
Lets put all together in this this example. I have a class called RuleForm, which contains an attribute of type Rule.
public class RuleForm {
...
#Getter #Setter //here use lombok, but you could create your getters-setters methods
private Rule rule;
...
}
Now in the controller, into the GET method, we set the view resolver(JSP) and the object we will send to there. In this case an object of type FormRule
#RequestMapping(value = "/submitrule", method = RequestMethod.GET)
public ModelAndView addruleSerch() {
ModelAndView model = new ModelAndView("yourView");
//here you choose the name you will use in your view, is up to you the name to choose
model.addObject("formRule", new FormRule());
return model;
}
Now we need to pick up that object we sent to the view and use it into our form tag.
<form action="/CommissionTool/submitrule" method="post" model="formRule">
...
<select name="rule.id"><c:forEach items="${listRules}" var="rule">
<option value="${rule.id}">
<c:out value="${rule.id}" />
</option>
</c:forEach>
</select>
In this point when we send the form to the Controller, we will send the RuleForm object with a value into rule.id object, then in the controller we have to get that id value and add out business logic.
#RequestMapping(value = "/submitrule", method = RequestMethod.POST)
public String addruleSerch(#ModelAttribute RuleForm ruleForm) {
//Here you will have access to your object
ruleForm.getRule().getId();// rule selected in the form
... your business logic
return "redirect:/someUrl";
}

list of string not displayed

I use spring 3. I'm trying to display a value of an object in a jsp.
public class UserForm implements Serializable {
private List<String> values;
private String date;
...
}
Here is my controller:
#Controller
#RequestMapping("/user.htm")
public class UserController {
#Autowired
private IUserService userService;
#RequestMapping(method = RequestMethod.GET)
public String userStat(Model model) {
UserForm stat = userService.populateStatistique();
stat.setDate("today");
model.addAttribute("statistiqueForm", stat);
return "userStat";
}
}
Here is my jsp:
<form:form commandName="userForm" name="userForm">
Date: <form:input path="date"></form:input>
<br/>
Expediteur:
<form:select path="values" items="${values}" />
<br/>
<input type="submit" value="create" />
</form:form>
In the jsp I can see the today value for the date field, but the listbox is empty.
any idea?
thanks
Well, use addAttribute("values", list) if you want it accessible in the jsp. You are currently not setting it and so it is empty.
If that list is contained in the statistiqueForm object, then use items="${statistiqueForm.values}".
You're correctly passing the form object to the jsp page. In that page you have a list box, which has a list of potential values and a list of selected values. The object form contains the list of selected values, but you should also setup the list with all potential values. In fact you reference ${values} in the jsp, but you don't pass it to the jsp. You should add this code to your controller:
model.addAttribute("values", potentialValueList);
I also suggest you to change the name of that list to avoid confusion, so it will be easy to understand the difference from selected values to potential values.

Equivalent Spring custom Collection property editor when using JSF

I would like to know how to use Converters in Java Server Faces similar to Spring collection property editor
Suppose the following model
public class Group {
private String name;
List<User> users = new ArrayList<User>();
// getter's and setter's
}
And equivalent form
<form ...>
<h1>Group form</h1>
<label for="name">Enter name</label>
<input type="text" name="name"/>
<label for="users">Select users</label>
<!--value attribute stores userId-->
<input type="checkbox" value="1" name="users"/> User 1
<input type="checkbox" value="2" name="users"/> User 2
<input type="checkbox" value="3" name="users"/> User 3
</form>
If i use Spring to bind users property in Group class, i call
binder.registerCustomEditor(List.class, new CustomCollectionEditor() {
protected Object convertElement(Object userId) {
return new User((Integer) userId);
}
});
How do i get the same effect when using Java Server Faces ?
regards,
For that you can implement javax.faces.convert.Converter. Its API is pretty self-explaining: write the getAsString() method accordingly that it returns the String representation of the Object, which can be under each the technical ID such as userId. Then, to get JSF set the right Object during apply request parameters phase, you need to implement getAsObject() that it returns the Object associated with the given String value.
Basically:
public class UserConverter implements Converter {
private UserDAO userDAO = SomeDAOManager.getUserDAO();
public String getAsString(FacesContext context, UIComponent component, Object value) {
return String.valueOf(((User) value).getId());
}
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return userDAO.find(Long.valueOf(value));
}
}
Register it in faces-config.xml as follows:
<converter>
<converter-for-class>com.example.model.User</converter-for-class>
<converter-class>com.example.converter.UserConverter</converter-class>
</converter>
That should be it. For more insights you may this or this article useful.

Categories

Resources