Property or field 'email' cannot be found on null - java

I'm trying to POST from a form within a Boostrap Modal.
Here's my form:
<form role="form" id="emailForm" action="#" th:action="#{/emailSubmission}" th:object="${university}" method="post">
<div class="form-group">
<label for="emailID"><span class="glyphicon glyphicon-user"></span> Username</label>
<input type="text" class="form-control" id="emailID" th:value="*{email}" placeholder="Enter email"></input>
</div>
<button type="submit" value="Submit" id="submitButton" class="btn btn-default btn-success btn-block" ><span class="glyphicon glyphicon-check"></span> Register</button>
</form>
Here's my controller:
#Controller
public class RegistrationController {
#RequestMapping(value = "/emailSubmission", method = RequestMethod.POST)
public String registerEmail(#ModelAttribute("university") University uni, BindingResult result, Model model)
{
System.out.println(uni.getEmail());
return "index";
}
}
And my University class:
public class University {
private String email;
public University(){
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
}
I'm new to Spring and can't figure out what's going wrong and why I'm receiving the error mentioned in the title.
Changing:
th:value="*{email}"
to:
th:field="*{email}"
gives me 'Neither BindingResult nor plain target object for bean name 'university' available as request attribute' error.

You have to add the university object as an attribute to the model in your controller:
#GetMapping(value = "/index")
public String login(Model model) {
model.addAttribute("university", new University());
return "index";
}

Here is what I have for your, hope it helps. If you don't understand just tell me, have a good night.
target.request(MediaType.APPLICATION_JSON)
.post(Entity.json(Json.createObjectBuilder()
.add("attribute1", "value1")
.add("attribute2", "value2")
.build()));
or if you prefer:
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.add("attribute1", "value1");
map.add("attribute2", "value2");
target.request(MediaType.APPLICATION_FORM_URLENCODED)
.post(Entity.form(map));
Now what I should do with it?
#POST
public Response post(JsonObject json) {
return Response.ok(service.persist(MyFactory.create(json.getString("attribute1"), json.getString("attribute2"))).build();
}
Or of course if you prefer:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(#FormParam("attribute1") String attribute1, #FormParam("attribute2") String attribute2) {
return Response.ok(service.persist(MyFactory.create(attribute1, attribute2))).build();
}

Related

Invalid property 'xxx' of bean class. Does the return type of the getter match the parameter type of the setter?

I am aware that this question has been asked before but after looking through all of the examples, non of the solutions helped me.
I am simply trying to render a video form on my application via spring controller, but I keep
getting the aforementioned error on every field except two. Below is my html
<form th:action="#{/upload-video}" method="POST" enctype="multipart/form-data" th:object="${video}">
<input id="i_file" type="file" name="file" accept="video/*">
<div class="video_container">
<label for="video_name">Video Name</label>
<input class="textInput" id="video_name" type="text" th:field="*{videoName}" placeholder="Example: image.png">
<label for="videoDesc">Video Description</label>
<input id="videoDesc" type="text" placeholder="Enter a description..." th:field="*{video_Description}">
<label for="file_path">File Path</label>
<input id="file_path" class="file_path_input textInput" type="text" placeholder="File Path..."><br>
<video src="">
Enter a video...
</video>
</div>
<button type="submit">Upload</button>
</form>
The error is now being generated on the videoDescription input tag. Below is my GET controller:
#RequestMapping(value = "/upload-video", method = RequestMethod.GET)
private String uploadVideoPage(Model model) {
model.addAttribute("video", new Video());
return "upload-video";
}
Here is my video class:
#Entity()
#Table(name = "user_videos")
public class Video {
#Id
#GeneratedValue
private Long videoId;
private String videoName;
private String videoTagLine;
private String video_Description;
private Date uploadDate;
#Transient
private String uploadDateStr;
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public String getVideoTagLine() {
return videoTagLine;
}
public void setVideoTagLine(String videoTagLine) {
this.videoTagLine = videoTagLine;
}
public String getVideo_Description() {
return video_Description;
}
public void setVideo_Description(String videoDescription) {
this.video_Description = videoDescription;
}
public Date getUploadDate() {
return uploadDate;
}
public void setUploadDate(Date uploadDate) {
this.uploadDate = uploadDate;
}
public String getUploadDateStr() {
return uploadDateStr;
}
public void setUploadDateStr(String uploadDateStr) {
this.uploadDateStr = uploadDateStr;
}
}
I've google and googled and googled and non of the solutions have worked. Any help would be appreciated.

How to get querystring passed value from the url into spring controller?

I want to get the querystrting passing value from the given url, like: http://localhost:8080/app?contentid=10 I want to get the value of contentid is: 10 from the above url in my spring controller, how can I get this ?
Please note that if I pass any value there(like 10, 50,100, 200, ...etc - it can be any number), so whatever I am passing to contentid, that value should get into my controller. I want to get this contentid value from that url only, not from my html page or I don't want to pass from my html page. Currently I am getting null from the below code in controller, I am not getting the passing value(like 10 from the url). How can I achieve this ? Thanks in advance for your help !
app.html:
<form action="#" th:action="#{/app}" th:object="${TestData}" method="post">
<div class="form-group">
<label for="firstname">First Name: </label> <input type="text"
class="form-control" id="firstname" name="firstname" ></textarea>
</div>
<div class="form-group">
<label for="secondname">Second Name:</label> <input type="text"
class="form-control" id="secondname" name="secondname" />
</div>
<button type="submit" value="Submit">Submit</button>
</form>
TestData.java:
public class TestData implements Serializable{
private String firstname;
private String secondname;
private int contentid;
//setters and getters
public TestData() {}
public TestData(String firstname, String secondname, int contentid, ){
this.firstname = firstname;
this.secondname = secondname;
this.contentid = contentid;
}
#Override
public String toString() {
return String.format(
"TestData[firstname=%s, secondname=%s, contentid=%d]",
firstname, secondname, contentid);
}
}
Controller:
public class TestDataController {
#Autowired
TestService testDataService;
#RequestMapping(value="/app", method=RequestMethod.POST)
public String testDataSubmit(#RequestParam(required=false) Integer contentid, #ModelAttribute TestData testData, Model model, HttpServletRequest request) {
String id = request.getQueryString();
System.out.println("My Id: "+id);//null
System.out.println("URL Parameter: "+testData.getContentid());//0
System.out.println("URL Parameter passed objectid: "+contentid); //null
testDataService.saveTestDataDetails(testData);
return "app";
}
}
Service:
#Service
public class TestService {
#PersistenceContext
private EntityManager entityManager;
public void saveTestDataDetails(TestData testData) {
StoredProcedureQuery sp = entityManager.createStoredProcedureQuery("APP.TESTDATA");
sp.registerStoredProcedureParameter("firstname", String.class, ParameterMode.IN);
sp.registerStoredProcedureParameter("secondname", Integer.class, ParameterMode.IN);
sp.registerStoredProcedureParameter("contentid", Integer.class, ParameterMode.IN);
sp.setParameter("firstname", testData.getFirstname());
sp.setParameter("secondname", testData.getSecondname());
sp.setParameter("contentid", testData.getContentid());
sp.execute();
}
}
After discussion per chat I will provide you a working solution where you can specifiy any stuff by your own needs.
app.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<title></title>
</head>
<body>
<th:block th:if="${contentid != null}">
<div th:text="${'contentId: ' + contentid}"></div>
</th:block>
<form action="#" th:action="#{/app(contentid=${contentid})}" th:object="${TestData}"
method="post">
<div class="form-group">
<label for="firstname">First Name: </label>
<input type="text" class="form-control" id="firstname"
name="firstname" />
</div>
<div class="form-group">
<label for="secondname">Second Name:</label>
<input type="text" class="form-control" id="secondname"
name="secondname" />
</div>
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
Controller:
#Controller
public class MyController {
#GetMapping("/app")
public String getApp(Model model) {
return "app";
}
#PostMapping("/app")
public String postApp(#RequestParam(required=false) Integer contentid, #ModelAttribute TestData testData, Model model, HttpServletRequest request) {
System.out.println(contentid);
if(contentid == null) {
contentid = ThreadLocalRandom.current().nextInt(0, 100 + 1);
}
model.addAttribute("contentid",contentid);
return "app";
}
}
First change your html code th:action="#{/app?contentid=10} and then add setter and getter method for the instance variable in the class TestData.

Bind list data to a model using ajax in spring mvc

I have a scenario where I want to bind data to a Model Class in spring using ajax
Model Class : EmployeeBean
private List<FamilyBean> familyDetails;
private String name;
//Getters and setters
FamilyBean Class goes here :
private String memberId;
private String empUserId;
private String relationship;
private String memberName;
private String age;
private String occupation;
private String contact;
private String isIncludeMedIns;
private String modefiedBy;
private String modifiedOn;
//Getters and Setters
JSP :
<input type="text" name="familyDetails[0].relationship" value="A">
<input type="text" name="familyDetails[0].memberName" value="B">
<input type="text" name="familyDetails[0].age" value="C">
<input type="button" value="Previous" name="_target1" id="previous">
Ajax Call:
$("#previous").click(function(){
$.ajax({
type: "POST",
url:"saveTempEmployeeData",
data:$("#formData").serialize(),//formData is id of the form
success:function (map) {
//alert("SUCCESS");
},
error:function (xhr) {
//alert(xhr.statusText+" ERROR");
}
});
});
Spring Controller :
#RequestMapping(value="/saveTempEmployeeData", method=RequestMethod.POST, headers="Accept=*")
public #ResponseBody void saveTempEmployeeData(HttpServletRequest request, HttpServletResponse response, #ModelAttribute("employeeBean")EmployeeBean employeeBean, ModelMap map) throws Exception{
userService.saveTempEmployeeData(employeeBean, pageNumber);
try{
System.out.println("In controller");
}
catch(Exception e){
}
response.setContentType("application/json");
response.setCharacterEncoding("ISO-8859-1");
response.getWriter().write(new Gson().toJson(map));
}
Data is not being binded to model attribute in the controller.
Is there any way to do it?
N.B : <input type="text" name="name" value="Sunny">
This data is being binded to the model.
I think you should name your input controls in JSP as shown below:
<input type="text" name="employeeBean.familyDetails[0].relationship" value="A">
<input type="text" name="employeeBean.familyDetails[0].memberName" value="B">
<input type="text" name="employeeBean.familyDetails[0].age" value="C">
That way Spring will know that it has to populate familyDetails inside employeeBean.
#ModelAttribute("employeeBean")EmployeeBean employeeBean
This was the problem. I changed it to :
#ModelAttribute EmployeeBean employeeBean
Now everything works fine.
Thank you all for your support.

Not able to hit controller with Spring Boot

Can anyone please help me as I am not able to hit the controller for one of my URLs. Here is the code:
#Controller
#RequestMapping("/posts")
public class PostController {
#Autowired
private PostRepository repository;
#RequestMapping(value = "", method = RequestMethod.GET)
public String listPosts(Model model) {
model.addAttribute("posts", repository.findAll());
return "postList";
}
#RequestMapping(value = "/new", method = RequestMethod.GET)
public String newProject() {
return "newPost";
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView create(#RequestParam("postDescription") String comment) {
repository.save(new Posts());
return new ModelAndView("redirect:/postList");
}
//...
}
and the JSP:
<form action="<spring:url value="/posts/create" />">
<div class="form-group">
<label for="postDescription">Post</label>
<button type="submit" id="save" class="btn btn-primary">Save</button>
</form>
I'm able to hit RegistrationController but not PostController.
Do I need to configure something else?

Spring 3.2 form errors long restful URLs

Think this is an easy one but don't know how to handle it.
I have a form like this.
<c:url value="edit" var="editprofileUrl" />
<form:form class="form" id="signup" action="${editprofileUrl}" method="post" modelAttribute="editProfileForm">
<div class="formInfo">
<s:bind path="*">
<c:choose>
<c:when test="${status.error}">
<div class="text-danger">Unable to change profile. Please fix the errors below and resubmit.</div>
</c:when>
</c:choose>
</s:bind>
</div>
<div class="form-group">
<label for="firstName">First name</label>
<form:errors path="firstName" cssClass="text-danger" />
<form:input class="form-control" path="firstName" />
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<form:errors path="lastName" cssClass="text-danger" />
<form:input class="form-control" id="last-name" path="lastName" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Save profile</button>
</div>
</form:form>
And the java form like this:
public class EditProfileForm {
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And a controller like this:
#Controller
#Transactional
public class EditProfileController {
#PersistenceContext
private EntityManager entityManager;
#RequestMapping(value = "/users/{username}/edit", method = RequestMethod.POST)
public String editProfile(#PathVariable String username, Principal currentUser, #Valid EditProfileForm form, BindingResult formBinding) {
if (formBinding.hasErrors()) {
return null;
}
Account user = entityManager.find(Account.class, currentUser.getName());
user.setFirstName(form.getFirstName());
user.setLastName(form.getLastName());
entityManager.persist(user);
return "home";
}
#RequestMapping(value = "/users/{username}/edit", method = RequestMethod.GET)
public ModelAndView editProfileForm(#PathVariable String username, Principal currentUser, WebRequest request, Model model) {
Account account = entityManager.find(Account.class, username);
if (account != null) {
model.addAttribute("account", account);
}
EditProfileForm form = new EditProfileForm();
form.setFirstName(account.getFirstName());
form.setLastName(account.getLastName());
return new ModelAndView("editprofile", "editProfileForm", form);
}
}
Everything works good besides when I don't fill in anything in one of the fields and it should give an error.
Something breaks in this code snippet:
if (formBinding.hasErrors()) {
return null;
}
Instead of returning the same page again with the errors it looks for a view that does not exist:
HTTP Status 404 - /project/WEB-INF/views/users/nilsi/edit.jsp
How do I return the same view again with the errors? Usually it works when i have a shorter #RequestMapping like /signup.
Thanks for any help on this!
In the event of binding errors, return the name of the form view again so that the user can correct the errors.
if (formBinding.hasErrors()) {
return "editprofile";
}
If you return null, Spring tries to guess a view name by looking at the url. Since your url ends with ".../edit", it tries to load edit.jsp.

Categories