Spring Framework 3 and session attributes - session

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.

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 ?

Injecting custom parameter to request mapping method in Spring MVC

In Spring MVC, I can wire session with my method. That's OK.
#RequestMapping(value = "/{cid}/read")
public #ResponseBody
boolean markAsRead(#PathVariable("cid") Comment comment, HttpSession session) {
User user = ((User) session.getAttribute("user"));
... }
Can I wire above user definition to the method definition? I mean instead of wiring session
#RequestMapping(value = "/{cid}/read")
public #ResponseBody
boolean markAsRead(#PathVariable("cid") Comment comment, User user) {
//No need to inject HttpSession and
//no need to call user = ((User) session.getAttribute("user"));
... }
You should be able to retrieve it using the #ModelAttribute tag, and annotating the user as a session attribute, this way:
#SessionAttributes("user")
public class MyController {
#RequestMapping(value = "/{cid}/read")
public #ResponseBody
boolean markAsRead(#PathVariable("cid") Comment comment, #ModelAttribute("user") User user) {
//No need to inject HttpSession and
//no need to call user = ((User) session.getAttribute("user"));
... }
}

Nested Velocity template with Spring formView

I have a Spring app that I'd like to add a login feature to. I'd like to put the login form in the header of the site. This means that it'll be included on several pages. When defining the controller that the form submits to, what do I specify as the formView?
Is it possible to specify the login template that's included in header (that's included in each head :-)) as the formView?
Thanks for the help. If anything is unclear than I'm happy to provide more details or show code.
Nevermind. I realized that it doesn't matter whether the Velocity template is included in another file. I added this to the template:
<form method="POST">
#springBind("credentials.*")
and my controller looks like this:
#Controller
public class SplashController implements Serializable {
protected final Log logger = LogFactory.getLog(getClass());
private static final long serialVersionUID = 7526471155622776147L;
#ModelAttribute("credentials")
public LoginCredentials getFormBean() {
return new LoginCredentials();
}
#RequestMapping(method = RequestMethod.GET)
public String showForm() {
logger.info("In showForm method of SplashController");
return "splash";
}
#RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(LoginCredentials credentials, BindingResult bindingResult) {
logger.info("In onSubmit method of SplashController");
logger.info("Username = " + credentials.getUsername());
logger.info("Password = " + credentials.getPassword());
ModelAndView modelAndView = new ModelAndView("home");
return modelAndView;
}
}
and it works.

Resources