#ModelAttribute in Controller does not auto increment ID - spring

I am working on Spring web based project and I am having trouble with #ModelAttribute that return model object to JSP file to be filled then it will be passed to controller function then data will be saved to database. Let me show you some code.
It is my Software Engineering Course Project for more detailed information code is available on github:
https://github.com/IYTECENG316SoftwareEngineering/reddit
#Controller
public class MessageController {
#ModelAttribute("privateMessage")
public PrivateMessage constructPrivateMessage() {
return new PrivateMessage();
}
#RequestMapping(value = "/message/{id}", method = RequestMethod.POST, params = "sendMessage")
public String doSendMessage(Model model, #PathVariable("id") int id,
#Valid #ModelAttribute("privateMessage") PrivateMessage privateMessage, BindingResult result,Principal principal) {
if (result.hasErrors()) {
return showMessage(model,id);
}
User messageOwner = userService.findOne(principal.getName());
//I need to create new instance of PrivateMessage because
//(#ModelAttribute("privateMessage") PrivateMessage privateMessage) this gives always same ID.
PrivateMessage message = new PrivateMessage();
message.setMessage(privateMessage.getMessage());
message.setUser(messageOwner);
PrivateMessageConversation conversation = messageService.findOneWithMessages(id);
message.setPrivateMessageConversation(conversation);
messageService.save(message);
return "redirect:/message/"+message.getID()+".html";
}
}
PrivateMessage object send to jsp file and it filled send back to doSendMessage function with #ModelAttribute. Object come with filled (all the inputs written in to object perfectly) but only problem is that its ID is not auto-incremented. There is one more code that I want to show. We use same template for topic and it works perfectly.Here the code;
#Controller
public class UserController {
#ModelAttribute("topic")
public Topic contructTopic() {
return new Topic();
}
#ModelAttribute("entry")
public Entry contructEntry() {
return new Entry();
}
#RequestMapping(value = "/account", method = RequestMethod.POST)
public String doAddNewTopic(Model model,
#Valid #ModelAttribute("topic") Topic topic,
BindingResult resultTopic, Principal principal,
#Valid #ModelAttribute("entry") Entry entry,
BindingResult resultEntry,
#RequestParam("topic_category") String category_string) {
System.out.println(principal.getName() + " " + category_string + " "
+ topic.getTitle() + " " + entry.getDescription());
if (resultTopic.hasErrors()) {
return account(model, principal);
}
if (resultEntry.hasErrors()) {
return account(model, principal);
}
String name = principal.getName();
Category category = categoryService.findByName(category_string);
topic.setCategory(category);
topicService.save(topic);
entry.setTopic(topic);
entry.setPublishedDate(new LocalDateTime());
entryService.save(entry, name);
return "redirect:/topic/" + topic.getId() + ".html";
}
}
Above code work perfectly. Topic and entry object send to jsp, they filled and send back to controller and all their attributes fine and IDs are auto-incremented. We could not figure auto why first one is not working.
NOTE: We are using Hibernate, Spring Data JPA and Tiles

In your first controller (MessageController) you are constructing a new instance of PrivateMessage and saving that. The hibernate generated id will be changed there. Then you are doing a redirect with a path pattern (redirect:/message/{id}.html). The pattern will be expanded with the original id the method doSendMessage has been called with.
In your second (working) controller you are not creating a new instance of Topic, so after saving topic the hibernate assigned id is contained in your topic. After that you are also not using springs path expansion but constructing a path by hand using the new id.
Change your first controller from
return "redirect:/message/{id}.html";
to
return "redirect:/message/" + message.getId() + ".html";
or
return UriComponentsBuilder.fromUriString("redirect:/message/{id}.html")
.buildAndExpand(message.getId())
.encode()
.toUriString()

Related

Spring MVC and Thymeleaf Prevent Entity Id Leak

I have Demand entity. I can update my entity without any problem but I think my approch have some security problem.
demandController
#RequestMapping(value = "/details/{id}", method = RequestMethod.POST)
public String updateDemand(#PathVariable("id") Long id, #Valid #ModelAttribute Demand demand, BindingResult result) {
if (result.hasErrors()) {
return "demandUpdateForm";
} else {
demand.setDemandId(id);
demandService.updateDemand(demand);
return "redirect:/demands";
}
}
serviceImpl
#Override
public Demand updateDemand(Demand demand) {
return demandRepository.save(demand);
}
form
<form id="vendorForm" th:action="#{/demands/details/__${demand.demandId}__}" th:object="${demand}" method="post" >
As you see I get DemandId from action. For example I want to update 5th id's demand and get the update form. Then I changed demandId via developer tools and click submit. If I modify id for example 2nd and form update my 2nd id demand not original the 5th one. How can I prevent this situation.
I think it would be better if you create unmanaged bean for this operations and will pass it as form backing bean.
public class DemandBean {
private Long id;
private String name;
...
// more fields
}
Controller :
#RequestMapping(value = "/details/update", method = RequestMethod.POST)
public String updateDemand(#Valid #ModelAttribute("demandBean") DemandBean demandBean, BindingResult result) {
if (result.hasErrors()) {
return "demandUpdateForm";
} else {
demandService.updateDemand(demandBean.getId(), demandBean.getName, ...);
return "redirect:/demands";
}
}
Service method :
#Override
public void updateDemand(Long id, String name, //etc) {
Demand d = id == null ? new Demand() : demandRepository.findOne(id);
d.setName(name);
// ...
// set other fields
return demandRepository.save(demand);
}
This approach helps you to avoid security leaks with passing id.

How can I check if the user have correctly submitted the previous form into a Spring MVC application that contemplate some steps?

I am pretty new in Spring MVC and I have the following situation.
I am working on a Spring MVC application that implement a user registration process. The prcess is divided into 4 steps. In each step the user insert some information into a form that is submitted and that is handled by the related method into the controller class. Each of these controller method take the related command object that contains the information of the submitted form.
So I have something like this:
#Controller
public class RegistrazioneController {
// This is the first step and show a view that contain the first form:
#RequestMapping(value = "/registrationStep1")
public String registrationStep1(Model model) {
return "/registrazione/registration-step1";
}
#RequestMapping(value = "/registrationStep2", method = RequestMethod.POST)
public String registrationStep2(#ModelAttribute RegistrationStep1 registrationStep1, Model model) throws APIException {
.......................................................
.......................................................
.......................................................
return "/registrazione/registration-step2";
}
#RequestMapping(value = "/registrationStep3", method = RequestMethod.POST)
public String registrationStep3(#ModelAttribute RegistrationStep3 registrationStep3, Model model) throws APIException {
.......................................................
.......................................................
.......................................................
return "/registrazione/registration-step3";
}
// This method return the final view after the completation of the user registration:
#RequestMapping(value = "/registrationStep4", method = RequestMethod.POST)
public String registrationStep2(#ModelAttribute RegistrationStep4 registrationStep4, Model model) throws APIException {
.......................................................
PERFORM THE USER REGISTRATION
.......................................................
return "/registrazione/registration-step4";
}
}
So it works pretty fine. My problem is that the application have tho check that, when enter into a registration step, the previous steps are completed (the previous form was compiled and submitted).
So I think that I have to do something like this, for example: ** when enter into the registrationStep3() have to check if the command object of the previous registrationStep2() step method was correctly setted (it is valid), so it means that the user have completed the previous registration step.
The application have to prevent that the user try to acces the registration starting from a step without having complete the previous steps of the registration process.
What is the best way to implement this behavior?
I have worked in some Sap Hybris projects and this platform suggest to use the following process :
Step1Form, Step2Form and Step3Form, if you have first name and last name in your 1 step form you ll have the same in Step1Form class as attributes.
and for each class create a validator, in the next step controller u have to validate the previous step if it is not valid redirect the user to the previous step.
you already have RegistrationStep1, and RegistrationStep2 and RegistrationStep3
lets create a validator for RegistrationStep1 :
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
#Component(value = "registrationStep1Validator")
public class RegistrationStep1Validator implements Validator
{
#Override
public boolean supports(final Class<?> aClass)
{
return RegistrationStep1.class.equals(aClass);
}
#Override
public void validate(final Object object, final Errors errors)
{
final RegistrationStep1 step1= (RegistrationStep1) object;
final String name = step1.getName();
final String email = step1.getEmail();
if (email.isEmpty or email == null)
{
errors.reject("email", "Email must not be blank or null");
}
if (name.isEmpty or name== null)
{
errors.reject("name", "Name must not be blank");
}
if (!EmailValidator.getInstance().isValid(email))
{
errors.reject("email", "Email must be valid");
}
}
}
//later in your controller
#RequestMapping(value = "/registrationStep2", method = RequestMethod.POST)
public String registrationStep2(#ModelAttribute RegistrationStep1 registrationStep1,final BindingResult bindingResult, Model model) {
registrationStep1Validator.validate(registrationStep1,bindingResult);
if (bindingResult.hasErrors())
{
return "/registrazione/registration-step1";
}
return "/registrazione/registration-step2";
}

AJAX jQuery CRUD with spring mvc without repeating RequestMethods

i have a page with a form and i have a AJAX function that returns a json with user details to fill some fields of that form and also in the same page i have a button to create a user from the information of that form
my problem is that to do this i have 3 controllers of the same page like this
this controllers returns the form with a GET method
#Controller
#RequestMapping("forms")
public class myController {
#RequestMapping(value = "myForm", method = RequestMethod.GET)
public String getPage (Model model) {
return "forms/myForm";
}
this controller is the one that gets me the some of the data in the form
RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody String searchSomeFields(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objectMap = mapper.readValue(json, User.class);
//get some data a fill some fields in the form
return toJsonInsertar(objectMap);
}
and in this controller i do the insert
RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody boolean insertUser(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objectMap = mapper.readValue(json, User.class);
//insert the user with all the data in the form
return toJsonInsertar(objectMap);
}
i try using two GET in the firts two controllers but i get a error saying that i already have a controller with the same requestMethod and value, i try puting PUT in the third controller that does the insert and it worked, but i read that PUT is used to do EDITS.
how can i do this insert with what i have ?

Pass object from one controller action to another controller action in spring mvc3

in my project i have one to many mapping between company and location.While adding location i want company object.
I have two differnt controller for company and location
In company Controller:
addCompany
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCompany(#ModelAttribute("company")
Company company, BindingResult result,Model model) {
companyService.addCompany(company);
return "companyPage";
}
updateCompany
#RequestMapping(value = "/update", method = RequestMethod.POST)
public String updateCompany(#ModelAttribute("company")
Company company, BindingResult result,#RequestParam(value = "submitVal") String updateOrRestore
,Model model) {
if (updateOrRestore.equalsIgnoreCase("update")) {
companyService.updateCompany(company);
model.addAttribute("location", new Location());
} else if (updateOrRestore.equalsIgnoreCase("restore")) {
Company prevCompany = companyService.restoreCompany();
model.addAttribute("company", prevCompany);
model.addAttribute("location", new Location());
}
return "companyPage";
}
In location Controller:
addLocation
#RequestMapping(value="/addLocation", method = RequestMethod.POST )
public String addLocation(#ModelAttribute("location")
Location location,BindingResult reult, Model model){
logger.info("Location is added"+location);
//Here b4 adding location in db i want to set company obj
//location.setCompany(company);
locationService.addLocation(location);
}
How can i get company object that one is save or updated in company controller action??
Just get Company object from DB with help of Its ID.
You have to maintain this ID in hidden input box inside form post and do in controller like below
#RequestMapping(value="/addLocation", method = RequestMethod.POST )
public String addLocation(#ModelAttribute("location")
Location location,BindingResult reult, Model model,#requestParam("cmpID") long ID){
//Company companyObj=get from DB with help of ID
//location.setCompany(companyObj);
locationService.addLocation(location);
return "yourview";
}

Spring Framework 3 and session attributes

I have form object that I set to request in GET request handler in my Spring controller. First time user enters to page, a new form object should be made and set to request. If user sends form, then form object is populated from request and now form object has all user givern attributes. Then form is validated and if validation is ok, then form is saved to database. If form is not validated, I want to save form object to session and then redirect to GET request handling page. When request is redirected to GET handler, then it should check if session contains form object.
I have figured out that there is #SessionAttributes("form") annotation in Spring, but for some reason following doesnt work, because at first time, session attribute form is null and it gives error:
org.springframework.web.HttpSessionRequiredException: Session attribute 'form' required - not found in session
Here is my controller:
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm(#ModelAttribute("form") Form form) {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
FormUtils.populate(form, request);
if(form.validate())
{
formDao.save();
}
else
{
return viewForm(form);
}
return null;
}
It throws Exception if controller called first time even though added #SessionAttributes({"form"}) to class. So add following populateForm method will fix this.
#SessionAttributes({"form"})
#Controller
public class MyController {
#ModelAttribute("form")
public Form populateForm() {
return new Form(); // populates form for the first time if its null
}
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm(#ModelAttribute("form") Form form) {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
// ..etc etc
}
}
The job of #SessionAttribute is to bind an existing model object to the session. If it doesn't yet exist, you need to define it. It's unnecessarily confusing, in my opinion, but try something like this:
#SessionAttributes({"form"})
#Controller
public class MyController {
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm(#ModelAttribute("form") Form form) {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
// ..etc etc
}
}
Note that the #SessionAttributes is declared on the class, rather than the method. You can put wherever you like, really, but I think it makes more sense on the class.
The documentation on this could be much clearer, in my opinion.
if there is no defined session object so I think it's gonna be like this:
#SessionAttributes({"form"})
#Controller
public class MyController {
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm() {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
// ..etc etc
}
}
#Controller
#SessionAttributes("goal")
public class GoalController {
#RequestMapping(value = "/addGoal", method = RequestMethod.GET)
public String addGoal(Model model) {
model.addAttribute("goal", new Goal(11));
return "addGoal";
}
#RequestMapping(value = "/addGoal", method = RequestMethod.POST)
public String addGoalMinutes(#ModelAttribute("goal") Goal goal) {
System.out.println("goal minutes " + goal.getMinutes());
return "addMinutes";
}
}
On page addGoal.jsp user enters any amount and submits page. Posted amount is stored in HTTP Session because of
#ModelAttribute("goal") Goal goal
and
#SessionAttributes("goal")
Without #ModelAttribute("goal") amount entered by user on addGoal page would be lost
I'm struggling with this as well. I read this post and it made some things clearer:
Set session variable spring mvc 3
As far as I understood it this basically says:
that Spring puts the objects specified by #SessionAttributes into the session only for the duration between the first GET request and the POST request that comes after it. After that the object is removed from the session. I tried it in a small application and it approved the statement.
So if you want to have objects that last longer throughout multiple GET and POST requests you will have to add them manually to the HttpSession, as usual.

Resources