spring auto populate user details for every request - spring-mvc

I have a spring MVC based web application. Currently in my web page i am showing the user first name and last name after user logs in. The way i am doing this is, for every HttpServletRequest that comes into #Controller#RequestMapping, i get the Principal object and get the user details from it, then populate the ModelMap with firstname and lastname attribute. For example here is the sample code
#Autowired
private SecurityDetails securityDetails;
#RequestMapping(method = RequestMethod.GET)
public String showWelcomePage(HttpServletRequest request,
HttpServletResponse response, ModelMap model, Principal principal)
{
securityDetails.populateUserName(model, principal);
... lot of code here;
return "home";
}
public boolean populateUserName(ModelMap model, Principal principal) {
if (principal != null) {
Object ob = ((Authentication)principal).getPrincipal();
if(ob instanceof MyUserDetails)
{
MyUserDetails ud = (MyUserDetails)ob;
model.addAttribute("username", ud.getFirstName() + " " + ud.getLastName());
}
return true;
}
else
{
logger.debug("principal is null");
return false;
}
}
My problem is i am having to call the populateUserName method for every RequestMapping. Is there a elegant way, like populating this in Interceptor method, which will result in this method being called just in one place for entire application?

Its good that you want to prevent duplication of code. Here is how you can do it.
Create a custom HandlerInterceptor http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/HandlerInterceptor.html
Post handle is the only method of interest for us, for the others return defaults.
In the post handle method, you have access to the model and view returned from your controller, go ahead and add whatever you want.
The Principal will not be available directly here, you will have to look it up using some code like SecurityContextHolder.getContext().getAuthentication().getPrincipal()
Wire the handler interceptor to intercept all or some of your controllers.
Hope this helps.

You can use either Servlet Filters or Spring Interceptors.
BTW, where do you populate the Principal from?
In any case, thats where you should do this populating stuff.

Related

passing values from One controller to another Controller using Session or TempData not working?

I have integrated payment gateway now, on success URL I want to pass some data from one controller to another controller but it's not working properly it's showing null value sometimes so, What I have to use instead of Session or TempData.
public void Index(UserRegistreModel model)
{
TempData["model2"]= model;
redirecturl += "&return=" + ConfigurationManager.AppSettings["SuccessURL"].ToString();
}
public ActionResult AnotherControllerMethod(UserRegistreModel model)
{
UserRegistreModel add = (UserRegistreModel) TempData["model2"];
//not getting any values
}
Your are adding User type class to Temp Data but you are extracting UserRegistreModel type so, that's why this was empty, Use like this :-
public void Index(User model)
{
TempData["model2"]= model;
redirecturl += "&return=" +
ConfigurationManager.AppSettings["SuccessURL"].ToString();
}
public ActionResult AnotherControllerMethod(User model)
{
User add = (User) TempData["model2"];
//not getting any values
}
How u are Passing Data ? Is it a forward or redirect? Forward will take the current data of your Request Object as it is the same Request but ur URL will not be changed in client.
And If u are redirecting then its a new Request. In This case the response will go to the client first (browser) then come to your new controller. As it is a new request, it will not have the old data from your calling controller.
Spring Has a special type of pojo called RedirectAttributes for this. Where you can add FlashAttribute for this type of requirement. Check the similar thing in .net

Front end ASP.NET MVC4 as one project, and an ASP.NET Web API as another project in same solution - how to call WebAPI from front end?

I have an ASP.NET MVC4 front end as one project in my solution, and a separate ASP.NET Web API as another project in the same solution. The Web API will contain all of my CRUD operations.
2 questions
How do I call my Web API from my front end to perform CRUD operations? I have my entity data model defined in my Web API project, and I will need to bind my front end views to it, how would I do that?
Once this is deployed to my web servers, the front end will reside on one server, and the Web API will reside on another server (the server that holds most of our web services). So, I guess along the same lines, how would I call the Web API from my front end once deployed? I understand Web API's are simply called with an HTTP request, but in terms of passing my models (which are defined in my Web API project) into my Views (in my front end project), how can I do this?
While Kevin is right, I did this the non-Ajax way. Keep in mind that I am working with JSON data, so this is centered around JSON.
In your controller page, remove anything that has to do with DbContext, Entity Framework, etc. The reason is by default, the controller will want to perform CRUD operations by calling the DbContext, and we don't want this. We want to call the WebAPI instead to do this.
First and foremost, declare some member variables in your controller. The rest of your controller will utilize these:
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
Uri contactUri = null;
In your controller, create a constructor for your controller, as such:
public ContactController()
{
// set base address of WebAPI depending on your current environment
client.BaseAddress = new Uri("http://server/YourAPI/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
Replace the Index action's code with something like the following. Note that the only relevant pieces are the client.GetAsync() call and the var contacts assignment. Everything else is not necessary for the context of this problem. The value inside the client.GetAsync() should be the name of your controller, prepended by any custom routing you set up in your WebApiConfig.cs - in my case, I added the api part in my route to distinguish between API calls and normal calls:
public ActionResult Index()
{
response = client.GetAsync("api/contact").Result;
if (response.IsSuccessStatusCode)
{
var contacts = response.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
return View(contacts);
}
else
{
// add something here to tell the user hey, something went wrong
return RedirectToAction("Index");
}
}
Replace the Create action (the HttpPost action) with something like the following. Again, the only important piece is the client.PostAsJsonAsync() part - this is what calls the WebAPI's POST action which takes care of, in my case, inserting a new record into the database:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Contact contact)
{
// Create a new product
response = client.PostAsJsonAsync("api/contact", contact).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
// add something here to tell the user hey, something went wrong
return RedirectToAction("Index");
}
}
Replace the Edit action (the non-HttpPost action) with something like the following. This was a little tricky because in order to edit, you had to retrieve the record first, so basically, the HttpPost version of Edit will contain somewhat similar code, with an additional line of code that performs the edit POST (PUT). Below, we're getting the response from the WebAPI by passing it a specific record ID. So, just like for Index (GET), we are doing the same thing only passing in the ID so we only get back one record. Then, we cast the response to an actual object that can be operated on in the View:
public ActionResult Edit(int id = 0)
{
response = client.GetAsync(string.Format("api/contact/{0}", id)).Result;
Contact contact = response.Content.ReadAsAsync<Contact>().Result;
if (contact == null)
{
return HttpNotFound();
}
return View(contact);
}
Replace the Edit action (the HttpPost action) with something like the following. Below, we're getting the record to be edited by calling client.GetAsync() and passing in the primary key as a parameter (contact_id). Then, we're getting the RequestUri from that response and saving it. Then, we're calling client.PutAsJsonAsync() and passing in the Uri.PathAndQuery (what we just saved) as well as the object to be edited.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Contact contact)
{
response = client.GetAsync(string.Format("api/contact/{0}", contact.contact_id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.PutAsJsonAsync(contactUri.PathAndQuery, contact).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
// add something here to tell the user hey, something went wrong
return RedirectToAction("Index");
}
}
Replace the Delete action (the non-HttpPost action) with something like the following. So again, we're getting the record from the database by simply calling client.GetAsync() and casting it to an actual object my app knows of.
public ActionResult Delete(int id = 0)
{
response = client.GetAsync(string.Format("api/contact/{0}", id)).Result;
Contact contact = response.Content.ReadAsAsync<Contact>().Result;
if (contact == null)
{
return HttpNotFound();
}
return View(contact);
}
Finally, replace the Delete action (the HttpPost action) with something like the following. Again, we're doing something similar to that of the Edit action. We are getting the record to be deleted, casting it to an object, and then passing that object into a client.DeleteAsync() call, as shown below.
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
response = client.GetAsync(string.Format("api/contact/{0}", id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.DeleteAsync(contactUri).Result;
return RedirectToAction("Index");
}
You can call your Web API from the client using jQuery ajax method. But since you are calling from a site other than where the Web API is deployed you will have to use JSONP, instead of JSON. Take a look at this QA to see how you use JSONP with Web API. Your models will be passed as JSON which you will have to render on the client side, instead of using Razor to render it on the server side. I would use something like Knockout to create a View Model on the client that will bind your model to the HTML elements on the client.

AttributeRouting mandatory parameter

Can I add mandatory parameter to all controller?
I develop RESTful api, so I want to require special "apikey" parameter for every route.
[HttpPut]
[PUT("create")]
public PostDto Create(string title, string description, string tag, long photo, float lat, float lon, int error)
{
if (description.Length > DescriptionMaxLength)
throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength));
throw new NotImplementedException();
}
[HttpPost]
[POST("edit/{id:int}")]
public bool Edit(int id, string title, string description, int? photo)
{
if (description.Length > DescriptionMaxLength)
throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength));
throw new NotImplementedException();
}
[HttpDelete]
[DELETE("delete/{id:int}")]
public bool Delete(int id)
{
if (id < 0)
throw new ApiException(ErrorList.InvalidValue, "id is smaller than 0");
throw new NotImplementedException();
}
But I don't want to do it manually for every method.
First of all, you need to determine the exact way you are going to retrieve the API key inside the action's body.
Since you don't want to pass it as the method's argument, it can be a property of the controller (not the best way to do this, you have to create a custom base controller class, but it may work for the simple scenarios) or another temporary per-request storage.
Then you need to create a Web API action filter. It's similar to the regular ASP.NET MVC action filters, there are plenty of tutorials over the web, most of them are about the authorization though.
This filter will try to inject the API key from the request into the controller or the temporary storage of your choice - inside the filter's OnActionExecuting method you have an access to both the request info and the controller context.
When it's all done, just register your filter in the Web API config, here is an example on how to do this.

What does it mean when Spring MVC #Controller returns null view name?

I downloaded the code for the Spring MVC 3 Showcase. One thing puzzles me (well, more than one), why does this (edited for concision) sample return null?
#Controller
#RequestMapping("/form")
public class FormController {
#RequestMapping(method=RequestMethod.POST)
public String processSubmit(#Valid FormBean form,
BindingResult result,
WebRequest webRequest,
HttpSession session, Model model) {
if (result.hasErrors()) {
return null;
} else {
session.setAttribute("form", form);
return "redirect:/form";
}
}
}
If a controller returns a null view name, or declares a void return type, Spring will attempt to infer the view name from the request URL.
In your case, it will assume the view name is form, and proceed on that assumption.
It does this using an implementation of RequestToViewNameTranslator, the default implementation of which is DefaultRequestToViewNameTranslator, the javadoc for which explains the exact rules it applies.
AnnotationMethodHandlerAdapter.invokeHandlerMethod() takes care of invoking handler methods. Here, a ModelAndView will be retrieved via ServletHandlerMethodInvoker.getModelAndView().
In your case, getModelAndView() gets provided the handler method's null return value. The getModelAndView() method checks for the return value's type, but as in Java null is never an instanceof any class, that method's logic will create a new ModelAndView. A new ModelAndView has initially its view property set to null.
Then later back up the call stack, in DispatcherServlet.doDispatch(), there is a test if the ModelAndView object has a View associated with it ( mv.hasView() ). Because view == null, doDispatch()'s logic calls mv.setViewName(getDefaultViewName(request)). It delegates to the registered RequestToViewNameTranslator, whose default implementation is DefaultRequestToViewNameTranslator. This subclass translates the request URI into a view name, in your case form.
Later in doDispatch(), via render() -> resolveViewName(), this sample's ViewResolvers are provided with the view name form. Only one ViewResolver, InternalResourceViewResolver is used in this sample. Also, this InternalResourceViewResolver was configured in src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml to add the prefix /WEB-INF/views/ and the suffix .jsp to the view name. So in total, it will create a View using the JSP file /WEB-INF/views/form.jsp. Luckily, a JSP file exists at exactly this location.

How to manage validation in GET form and submit POST form?

the enviroment is Spring 3.0 with new function Vallidation.
I create an annotated controller (ResetUserPasswordController) which manages a showForm on HTTP.GET and the submit form on HTTP.POST. The function is a reset user password requested by email : the user access previously to another form, where i fill is email address and a recaptcha control, if recaptcha is correct, the user receive a mail with a link which contains a paramter. The two methods (on HTTP.GET, and HTTP.POST) have two different command bean have different paramters(i choice two differents beans to manage the validation process in two diffent validators classes). Probably you are questioning : why do you define two differents commands? I have defined the following role : Every bussiness and basic (like notnull validation etc) validation process must be managed by a validator class which supports a specific command bean
I want to create the istance of command bean managed by the POST, in the GET method, but during some tests I realized that this can be not correct beacuse if the validation process goes bad, I have all errors on the input command which is different from which i'm gogin to put in the returned ModelAndView.
Someone has some suggestion to manage correctly this scenario?
#RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(#Valid #ModelAttribute("command") ResetUserPasswordCommand command, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
getValidator().validate(command, result);
if (result.hasErrors()) {
// TODO : implements error page.
return new ModelAndView();
} else {
Map<String, Object> model = new HashMap<String, Object>();
try {
PasswordChangeRequest passwordChangeRequest = getUserService().findPasswordChangeRequest(command.getUuid());
getUserService().updateUserPassword(command.getUuid(), command.getPassword());
autoLogin(request, response, passwordChangeRequest.getAccount(), command.getPassword());
} catch (ApplicationThrowable aex) {
return new ModelAndView("responseKO", model);
}
return new ModelAndView("Home", model);
}
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView setupForm(#Valid #ModelAttribute("command") ResetUserPasswordFormCommand command, BindingResult result) {
getFormValidator().validate(command, result);
if (result.hasErrors()) {
// TODO : implements error page.
return new ModelAndView();
} else {
Map<String, Object> model = new HashMap<String, Object>();
ResetUserPasswordCommand resetUserPasswordCommand = new ResetUserPasswordCommand();
resetUserPasswordCommand.setUuid(command.getUuid());
model.put("command", resetUserPasswordCommand);
model.put("reCaptchaHTML", getReCaptchaService().getReCaptchaObjectNoSSL().createRecaptchaHtml(null, null));
return new ModelAndView("user/ResetUserPassword", model);
}
}

Resources