I am having a small issue with Spring Boot forms displaying the information of the path value instead of the placeholder once you get to the editProfile.jsp. I want the input field to look like this;
Edit Profile Page instead of this Wrong Edit Profile. I do not want my users to have to click, select and delete the auto completed value. I want it to show the placeholder only and allow them to overwrite what is shown with ease.
This is the editProfile.jsp
<%--#elvariable id="editProfile" type=""--%>
<form:form method="POST" modelAttribute="editProfile">
<div class="MyForm form-group">
<h1>Edit Profile</h1>
<form:input type="email" class="MyInput" id="email" path="email" placeholder="${editProfile.email}" />
<form:button type="submit" class="from-control">Submit</form:button>
</div>
<div>
<img src="images/reg1.png" alt="picture">
</div>
</form:form>
</body>
</html>
This is the code specified in the Controller
#RequestMapping(value = "edit/{email}", method = RequestMethod.GET)
public String getEditUserData(#PathVariable("email") String email, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
model.addAttribute("editProfile", accountInstance);
return "editProfile";
}
#RequestMapping(value = "edit/{email}", method = RequestMethod.POST)
public String enterEditUserData(#ModelAttribute("login") AccountEntity accountForm, #PathVariable("email") String email, Model model ) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
accountInstance.setEmail(accountForm.getEmail());
accountRepo.save(accountInstance);
return "redirect:/login";
}
I have figured it out; You have to add a model of a new Entity, so the path variable does not fill in with the instance of the specific path value. Here is the new code, and compare it to the one I sent above.
#RequestMapping(value = "edit/{email}", method = RequestMethod.GET)
public String getEditUserData(#PathVariable("email") String email, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
model.addAttribute("editProfile2", new AccountEntity());
model.addAttribute("editProfile1", accountInstance);
return "editProfile";
}
<%--#elvariable id="editProfile" type=""--%>
<%--#elvariable id="editProfile2" type=""--%>
<form:form method="POST" modelAttribute="editProfile2">
<div class="grid form-group">
<h1>Edit Profile</h1>
<form:input type="email" class="MyInput" id="email" path="email" placeholder='${editProfile1.email}' />
<form:button type="submit" class="from-control">Submit</form:button>
</div>
Related
I have two hidden input fields to implement Friend system. I pass user and friend's ids in Model and then use them in thymeleaf page to pass them in form to PostMapping and save changes. However, PostMapping cannot see my second #RequestParam.
Both customer and friend are properly passed to model as I tried to output them on website using th:text
Snippets of code:
Adding both users to model:
#GetMapping("/customer/{customerId}")
public String getCustomer(Model theModel, #PathVariable int customerId, #AuthenticationPrincipal MyUserDetails user) {
Customer currUser = customerService.findById(user.getCustomer().getId());
Customer foundCustomer = customerService.findById(customerId);
theModel.addAttribute("friend", foundCustomer);
theModel.addAttribute("customer", currUser);
return "customerdetails";
Snippet of Thymeleaf code:
<form action="#" th:action="#{/home/addFriend}" th:object="${friend}" method="post">
<input type="hidden" th:field="${friend.id}" th:attr="name='friendId'" />
<input type="hidden" th:field="${customer.id}" th:attr="name='customerId'" />
<input type="submit" value="Add Friend" class="btn btn-primary flex-grow-1" />
</form>
PostMapping (where issue occurs):
#PostMapping("/addFriend")
public String getPost(#RequestParam("friendId") int friendId, #RequestParam("customerId") int customerId) {
Customer friendCustomer = customerService.findById(friendId);
Customer currCustomer = customerService.findById(customerId);
System.out.println(currCustomer.getFirstName());
System.out.println(friendCustomer.getFirstName());
return "redirect:/home";
}
Code of error:
[org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'friendId' for method parameter type int is not present]
It will be a lot easier to implement using a custom form object.
For example, create this class:
public class AssignFriendFormData {
private String friendId;
private String customerId;
// getter and setters here
}
Use this in your #GetMappping:
#GetMapping("/customer/{customerId}")
public String getCustomer(Model theModel, #PathVariable int customerId, #AuthenticationPrincipal MyUserDetails user) {
Customer currUser = customerService.findById(user.getCustomer().getId());
Customer foundCustomer = customerService.findById(customerId);
AssignFriendFormData formData = new AssignFriendFormData();
formData.setFriendId(foundCustomer.getId());
formData.setCustomerId(currUser.getId());
theModel.addAttribute("formData", formData);
return "customerdetails";
Change the form to this:
<form action="#" th:action="#{/home/addFriend}" th:object="${formData}" method="post">
<input type="hidden" th:field="*{friendId}" />
<input type="hidden" th:field="*{customerId}" />
<input type="submit" value="Add Friend" class="btn btn-primary flex-grow-1" />
</form>
Finally, update the #PostMapping to use the form data object:
#PostMapping("/addFriend")
public String getPost(#Valid #ModelAttribute("formData") AssignFriendFormData formData) {
Customer friendCustomer = customerService.findById(formData.getFriendId());
Customer currCustomer = customerService.findById(formData.getCustomerId());
System.out.println(currCustomer.getFirstName());
System.out.println(friendCustomer.getFirstName());
return "redirect:/home";
}
See Form handling with Thymeleaf for a more in-depth tutorial on this.
How to send data from jsp to controller in spring using form ?
<form:form action="${searchUrl}" method="post">
<div class="form-group">
<label class="control-label"> search by ID </label>
<br>
<input type="text" id="ticketId" placeholder=" Enter ticket ID ">
</div>
</form:form>
Could not able to get ticketId using this method
You need to declare name attribute (name="ticketId") and access the same on the controller. Like below.
JSP:
<input type="text" name="ticketId" id="ticketId" placeholder=" Enter ticket ID">
Controller:
#RequestParam(value = "ticketId", required = false) String ticketId
I hope it is helpful to you, for me it is working fine.
If you want to use spring forms, make sure to follow the below steps :
Step:1.In the spring controller, you should return the bean object like below to respected JSP.
Class User {
private String ticketId;
// setter & getter
}
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String init(Model model) {
model.addAttribute("msg", "Please Enter Your Login Details");
model.addAttribute("loginBean", new User());
return "login";
}
Step:2 add a model attribute and add taglib in the JSP page.
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<form:form action="${searchUrl}" method="post"
modelAttribute="loginBean">
<div class="form-group">
<label class="control-label"> search by ID </label>
<br>
<form:input type="text" id="ticketId" path = "ticketId"
placeholder=" Enter ticket ID " />
</div>
</form:form>
Step : 3
#RequestMapping(value = "/test", method = RequestMethod.Post)
public String init(Model model,
#ModelAttribute("user") User user,BindingResult
result) {
sout("user"+user);
return "home";
}
Html
<form th:object="${klient}" th:action="#{/osoba}" method="post">
<div class="form-row">
<div class="form-group col-md-4">
<label >ImiÄ™</label>
<input type="text" class="form-control" th:field="*{imie}" >
</div>
<div class="form-group col-md-4">
<label >Nazwisko</label>
<input type="text" class="form-control" th:field="*{nazwisko}" >
</div>
<div class="select-list" id="selectlist">
<select th:field="*{UserId}" >
<option> -- </option>
<option th:each=" users : ${user}"
th:value="${users.UserId}"
th:utext="${users.lastName}"/>
</select>
</div>
Cod
#RequestMapping (value = "/osoba", method = RequestMethod.POST)
public String dodaj (Klient klient){
System.out.print(klient);
return "redirect:/osoba";
}
#RequestMapping (value = "/dodaj" , method = RequestMethod.GET)
public String tworz (Model model){
model.addAttribute("klient" , new Klient());
List<User> lista = userService.getAllUser();
model.addAttribute("user" , lista);
return "dodaj";
}
I want to create a form in which he completes the fields for the client and assign an existing user to him.The problem is that I can't get the selected user id.
I get a message about the first select
Error during execution of processor 'org.thymeleaf.spring5.processor.SpringSelectFieldTagProcessor
The error message shows that there is a problem with a property named uzytkownik , which I don't see anywhere in your template. Of course, you didn't include the complete template, so all I can say is that the problem is coming from somewhere else... apparently from line 178.
Create the getter and setter methods for userId in Klient:
public String getUserId()
public void setUserId(String userId)
I found a solution:
in select I changed
<select id="UserId" name="UserId" >
in controller
#RequestMapping (value = "/osoba", method = RequestMethod.POST)
public String dodaj (#ModelAttribute("UserId") Set<User> user, Klient klient){
klient.setUsers(user);
System.out.print(klient);
klientServicee.createOrUpdateKlient(klient);
return "redirect:/osoba";
}
it works but is it correct?
I am trying to submit a form to controller in using java spring, in following code i am retrieving file element by following way successfully but not getting how to retrieve other elements(shortname and full name)value.
please help me out.
<body>
<div style="text-align: center; margin-top: 60px;">
<form action="upload" enctype="multipart/form-data">
<input type="hidden" id="shortName" name="michael">
<input type="hidden" id="fullName" name="michael jackson">
Select file:
<input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
<div style="text-align: center; margin-top: 100px;">
<input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
</div>
</form>
</div>
</body>
Controller side code :
#RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response,
#RequestPart("dataFile") MultipartFile file
){
System.out.println(file.getSize());
}
first change the input elements and create the name attribute for both shortName and fullName like so :
<input type="hidden" id="shortNameId" name="shortName" value="michael">
<input type="hidden" id="fullNameId" name="fullName" value="michael jackson">
however you can remove the default value attribute and just enter the value yourself when the page render so value="michael" & value="michael jackson" are optional !
Then you can retrieve those input elements like this :
#RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response, #RequestParam("shortName")String shortName, #RequestParam("fullName")String fullName
#RequestPart("dataFile") MultipartFile file
){ .... }
Good Luck !
In your controller, try something like this,
#RequestMapping(value = "/your/url/{formParamenter}", method = RequestMethod.GET)
public String yourfunction(#PathVariable("formParameter") Type formParameter{}
The Type is the type of data, (String/int/float..etc).
In your case just change RequestPart to #PathVariable
I need to show the fetched values from database which are stored in an arraylist using spring form:input tag. However i found that the 'value' attribute isn't supported. Please help!
I guess you are expecting something like this.
//Assumes you have the following in your class
public class Students{
private String name;
private List<String> Departments;
/* getters/setters */
}
In the HTML would be.
<form:input path="departments[0]" />
<form:input path="departments[1]" />
For more details about click http://www.javacodegeeks.com/2013/07/spring-mvc-form-handling-vol-5-select-option-options-tags.html
Please first retrieve the list from the datebase and set the list on the model attribute in the controller see the example set the
#Controller
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String userHome(Model model, EventBean event, UserService userService,ImageBean image)
{
List<Event> events = userService.viewNews(); //retrieve the list from datebase
model.addAttribute("event", event); //add bean object
model.addAttribute("events", events); //add list in model attribute
return "home";
}
}
your jsp page
<form:form modelAttribute="event"> <!--set the model attribute here -->
<form:input path="news" value="${events.get(0).news}" />
</form:form>
This is my code,please have a look and say what i might be doing wrong,
JAVA
public ModelAndView userEditProfile(#ModelAttribute("userDetails") UserFormbean registration,BindingResult result,HttpServletRequest request){
ModelAndView mav=null;
HttpSession httpSession=null;
List userProfileList=new ArrayList();
httpSession=request.getSession();
if (httpSession != null) {
UserFormbean formbean=(UserFormbean)httpSession.getAttribute("UserRegistrationFormBean");
userProfileList= userRegistrationService.getUserProfileInfo(formbean);
mav=new ModelAndView("EditProfile");
mav.addObject("userProfileInfoList", userProfileList);
}
return mav;
}
JSP::
-----
<c:if test="${not empty userProfileInfoList}">
<c:forEach var="temp" items="${userProfileInfoList}">
<div>
<form:label path="userRegistration.email"><spring:message code="label.email"/></form:label>
<form:input path ="userRegistration.email" value="${temp.get(0).UserRegistration.email}"/>
<form:errors path="userRegistration.email"/>
</div>
<div>
<form:label path="userRegistration.firstName"><spring:message code="label.firstname"/></form:label>
<form:input path ="userRegistration.firstName" value="${temp.get(0).UserRegistration.firstName}"/>
<form:errors path="userRegistration.firstName"/>
</div>
<div>
<form:label path="userRegistration.lastName"><spring:message code="label.lastname"/></form:label>
<form:input path ="userRegistration.lastName" value="${temp.get(0).UserRegistration.lastName}"/>
<form:errors path="userRegistration.lastName"/>
</div>
</c:forEach>
</c:if>