what i need to write in else part in the following code? - spring-mvc

#RequestMapping("/insert")
public String insertEmpDetails(#ModelAttribute("employee") Employee emp) {
if (emp != null)
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
Please tell me what to write in else part.I was trying for that but i am not getting

Make employeeId as a required param to serve the request by this RequestMapping then you don't need to write else part because Employee model will never be null in that case. It must have at least employeeId.
Note: Make it POST request.
Example:
#RequestMapping(value = "/insert", params = "employeeId", method = RequestMethod.POST)
public String insertEmpDetails(#ModelAttribute("employee") Employee emp) {
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
In other way you can validate the model and redirect to form page back with validation error messages.
Sample:
#RequestMapping(value = "/insert", params = "employeeId", method = RequestMethod.POST)
public String insertEmpDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult result, ModelMap model) {
if (result.hasErrors()){
model.addAttribute("error", "Your custom error messages");
return "<<back to form page without redirection>>";
}else {
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
}
Read more about Spring - Validation, Data Binding, and Type Conversion
Read a post on Spring MVC : How to perform validation ?

Related

ASP.NET: Access temp data in ViewBag

I am beginner in ASP.NET and trying to get data in ViewBagby using temp data in controller. I got it in user.Username and user.Email but not getting in ViewBag.Name and ViewBag.Email respectively. My code is given below please guide me how can i get it in ViewBag?
QuestionsContoller.cs
public class temp {
public string username { get; set; }
public string email { get; set; }
}
public ActionResult Question() {
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Question(User user) {
temp temp_user = new temp();
temp_user.email = user.Email;
temp_user.username = user.Username;
return RedirectToAction("Answers" , temp_user);
}
public ActionResult Answers(temp temp_user) {
User user = new Models.User();
user.Username = temp_user.username;
user.Email = temp_user.email;
ViewBag.Name = user.Username;
ViewBag.Email = user.Email;
return View(user);
}
You cannot redirect with a payload. A redirect is an empty-bodied response with typically a 302 status code and a Location header indicating the URL that should be requested next. The client, upon receiving this type of response, will generally then go ahead and make a new request for that URL. Importantly, the client will not know or care to pass any additional data along with this request, so you cannot enforce that something like your temp object is included.
If you need to persist that data between requests, you can add it to TempData:
TempData["temp_user"] = temp_user;
And then fetch it in the action you redirect to via:
var temp_user = TempData["temp_user"] as temp;
Alternatively (and preferably), you'd simply redirect with the user id in tow, and then simply look up the user again. The use of sessions (which TempData is) should be avoided as much as possible.
return RedirectToAction("Answers", new { userId = user.Id });

ModelandView doesnt work

I created registration Controller. Everything works fine, user is create in database but then end service program doesnt go to successRegister view. I dont know why. If I return like String successRegister everything is ok.
#RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView registerUserAccount(#RequestBody #Valid User accountDto,
BindingResult result, WebRequest request, Errors errors) {
if (result.hasErrors()) {
return new ModelAndView("successRegister", "User", accountDto);
}
User registered = userService.register(accountDto);
if (registered == null) {
result.rejectValue("email", "message.regError");
}
try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent
(registered, request.getLocale(), appUrl));
} catch (Exception me) {
return new ModelAndView("successRegister", "User", accountDto);
}
return new ModelAndView("successRegister");
}
Problem was with AJAX. I changed location after success and then ModelAndView was not return.
Your problem is with this
produces = MediaType.APPLICATION_JSON_VALUE
You says produces a JSON response but thats not true, you want to return a ModelAndView, so try to remove that attribute

Issue with mvc:annotation-driven and #PathVariable

Not sure what I am doing wrong here but when I DO NOT define the mvc:annotation-driven in my servlet, the value returned from the #PathVariable is not getting displayed in my jsp page and when I do define the annotation-driven, all other links e.g. home gets broken and I get the The specified HTTP method is not allowed for the requested resource (Request method GET not supported).
#Controller("HealthCheckController")
#RequestMapping("/healthCheckSummary")
public class HealthCheckController {
private Log log = LogFactory.getLog(GolSimpleMappingExceptionResolver.class);
private HealthCheckService healthCheckService = null;
private IEappDataAccessFacade dataAccessFacade;
#RequestMapping(value = "/{username}/{password}", method = RequestMethod.GET)
public String getEappStatus(#PathVariable String username, #PathVariable String password, Model model){
String dbConnectivityStatus = getDatabaseConnectivityStatus() ? "online" : "offline";
if (!username.equals("lola") || !password.equals("123")) {
// wrong credentials were provided
log.error("The login credentials in the header are not valid." + username + password);
throw new RuntimeException( "Unable to continue, the login credentials in the header are not valid." + username + password);
}
model.addAttribute("healthCheckSummary", dbConnectivityStatus);
return "healthCheckSummary";
}
public HealthCheckService getHealthCheckService()
{
return healthCheckService;
}
public boolean getDatabaseConnectivityStatus() {
String result = “OK”;
if (result != null) {
return true;
}
return false;
}
}
Oh and in the application context we have defined the
<tx:annotation-driven />
JSP page
<%# page language="java"%>
Welcome ${username} - ${password}
Eapp is currently ${healthCheckSummary}
Two things:
You never put your username and password #PathVariables in the model. Your jsp page has no way of knowing that they even existed as you lose any reference to them after the code leaves getEappStatus. Add the following to your handler method:
model.addAttribute("username", username);
model.addAttribute("password", password);
and see if that works.
You might want to add <mvc:annotation-driven/> just to avoid some surprises when you use some spring-mvc annotations. This isn't strictly necessary, but might save you some head scratching when some #RequestBody doesn't work.

How to handle a POST request to a URL that contains route parameters?

I'm working on an ASP.NET MVC4 web app, and I have a controller method for handling a GET request with an id in the URL, like so ...
[PortalAuthorization]
public ActionResult View(int id)
{
// get the individual ftp log
PortalFTPLog log = PortalFTPLogs.Get(id);
if (log == null)
{
TempData["Error"] = "The provided ftp log id does not exist.";
return RedirectToAction("Index");
}
// get the available matters to tie uploads to
ViewBag.matters = PortalMatters.Get();
return View(log);
}
In my view for this controller method, I have a form so that they can update it, that I want to POST back to the same URL. A URL like foo.com\items\1. Thats what the function above handles.
How do I make a function that handles a POST request for a function that requires a parameter, though? IN previous POST handlers I create a FormsCollection param, but when I add it to the param list for this function, the id param is null.
[HttpPost]
[PortalAuthorization]
public ActionResult View(FormCollection collection, int id)
{
PortalFTPLog log = PortalFTPLogs.Get(id);
if (log == null)
{
TempData["Error"] = "The provided ftp log id does not exist.";
return RedirectToAction("Index");
}
// update the matter id and save to database
log.Matter = Convert.ToInt32(collection.Get("matter"));
log.Save();
TempData["Notice"] = "The FTP log meta data has been updated.";
return RedirectToAction("View", new { id = id });
}
You need to provide RouteValues in Html.BeginForm on your View:
#using (Html.BeginForm(new {id = someIntIdValue}))
{
// Your form code
}

RedirectToAction usage in asp.net mvc

I want to post some questions about ASP.Net MVC. I am not familiar with web developing, But I was assigned to the web part of a project. We are doing the following: first, we create get & set properties for the person data:
public class Person
{
public int personID {get;set;}
public string personName {get;set;}
public string nric {get;set;}
}
and after login, we put the data in a class Person object and we use RedirectToAction like this:
return RedirectToAction("profile","person",new { personID = Person.personID});
It's working normally, but the parameter are shown in the URL. How can I hide them and also
can I hide the action name? Guide me the right way with some examples, please.
The parameter are shown in the URL because that is what the third parameter to RedirectToAction is - the route values.
The default route is {controller}/{action}/{id}
So this code:
return RedirectToAction("profile","person",new { personID = Person.personID});
Will produce the following URL/route:
/Person/Profile/123
If you want a cleaner route, like this (for example):
/people/123
Create a new route:
routes.MapRoute("PersonCleanRoute",
"people/{id}",
new {controller = "Person", action = "Profile"});
And your URL should be clean, like the above.
Alternatively, you may not like to use ID at all, you can use some other unique identifier - like a nickname.
So the URL could be like this:
people/rpm1984
To do that, just change your route:
routes.MapRoute("PersonCleanRoute",
"people/{nickname}",
new {controller = "Person", action = "Profile"});
And your action method:
public ActionResult Profile(string nickname)
{
}
And your RedirectToAction code:
return RedirectToAction("profile","person",new { nickname = Person.nickname});
Is that what your after?
If you don't want the parameter to be shown in the address bar you will need to persist it somewhere on the server between the redirects. A good place to achieve this is TempData. Here's an example:
public ActionResult Index()
{
TempData["nickname"] = Person.nickname;
return RedirectToAction("profile", "person");
}
And now on the Profile action you are redirecting to fetch it from TempData:
public ActionResult Profile()
{
var nickname = TempData["nickname"] as string;
if (nickname == null)
{
// nickname was not found in TempData.
// this usually means that the user directly
// navigated to /person/profile without passing
// through the other action which would store
// the nickname in TempData
throw new HttpException(404);
}
return View();
}
Under the covers TempData uses Session for storage but it will be automatically evicted after the redirect, so the value could be used only once which is what you need: store, redirect, fetch.
this may be solution of problem when TempData gone after refresh the page :-
when first time you get TempData in action method set it in a ViewData & write check as below:
public ActionResult Index()
{
TempData["nickname"] = Person.nickname;
return RedirectToAction("profile", "person");
}
now on the Profile action :
public ActionResult Profile()
{
var nickname = TempData["nickname"] as string;
if(nickname !=null)
ViewData["nickname"]=nickname;
if (nickname == null && ViewData["nickname"]==null)
{
throw new HttpException(404);
}
else
{
if(nickname == null)
nickname=ViewData["nickname"];
}
return View();
}
Temp data is capable of handling single subsequent request. Hence, value gone after refresh the page. To mitigate this issue, we can use Session variable also in this case. Try below:
public ActionResult Index(Person _person)
{
Session["personNickName"] = _person.nickName;
return RedirectToAction("profile", "person");
}
And in "profile" actionmethod:
public ActionResult profile()
{
Person nickName=(Person)Session["personNickName"];
if(nickName !=null)
{
//Do the logic with the nickName
}
}

Resources