NewAccountDAOImpl
it is getting particular record id, username and password
according to that it should retrieve the records
#Transactional
#Modifying
public boolean checkLogin(int id, String username, String password){
System.out.println("In Check login"+ id);
System.out.println("In Check login"+ username);
System.out.println("In Check login"+ password);
Session session = sessionFactory.openSession();
boolean userFound = false;
//Query using Hibernate Query Language
//tring SQL_QUERY =" from NewAccount as n where n.id=? and n.username=? and password=?";
String SQL_Query=" from NewAccount where id=:id";
Query query = session.createQuery(SQL_Query);
query.setParameter("id",id).uniqueResult();
//query.setParameter(0,id);
//query.setParameter(1,username);
//query.setParameter(2,password);
List list = query.list();
if ((list != null) && (list.size() > 0)) {
userFound= true;
}
session.close();
return userFound;
}
controller class
getting information from bankbalance form like id,username, password.
i added them to checkLogin method parameters it returns boolean valeue
#RequestMapping(value = "/balanceSave", method = RequestMethod.GET)
public ModelAndView saveBk(ModelAndView model, HttpServletRequest req,
HttpServletResponse res, #ModelAttribute NewAccount newaccount) {
int id=Integer.parseInt(req.getParameter("id"));
String username=req.getParameter("username");
String password=req.getParameter("password");
boolean userExists = newaccountService.checkLogin( id, username, password);
if(userExists ){
model.addObject("newaccount", newaccount);
return new ModelAndView("redirect:viewBalanceMoney");
}
return new ModelAndView("BalanceForm");
}
here i am sending list data to a jsp page viewbalanc
// view newaccount balance money
#RequestMapping(value = "/viewBalanceMoney", method = RequestMethod.GET)
public ModelAndView viewBalanceMoney(ModelAndView model) {
// public NewAccount getNewAccount(int newaccountid);
List<NewAccount> listnewaccount = newaccountService.getAllNewAccounts();
model.addObject("listnewaccount", listnewaccount);
model.setViewName("viewBalanc");
return model;
}
image1 shows balance form
it send input to the controller method
image 2 shows retrieved records, but i need particular id record information
image2
enter image description here
You can do this using #PathVariable and invoke the method for that accountId.
#RequestMapping(value = "/viewBalanceMoney/{newAccountId}", method = RequestMethod.GET)
public ModelAndView viewBalanceMoney(#PathVariable("newAccountId") Integer newaccountid,
ModelAndView model) {
//write code for fetching data for newaccountid
}
Related
I couldn't figure out what to put to the title, but I have the following code:
#Controller
public class WorkdayAddController {
#Autowired
private WorkdayRepository workdayRepository;
#Autowired
private VehicleRepository vehicleRepository;
#RequestMapping(value = "addworkday")
public String addWorkday(Model model){
model.addAttribute("workdayaddform", new WorkdayAddForm());
model.addAttribute("vehicles", vehicleRepository.findAll());
return "addworkday";
}
#RequestMapping(value = "saveworkday", method = RequestMethod.POST)
public String save(#Valid #ModelAttribute("workdayaddform") WorkdayAddForm workdayaddform, BindingResult bindingResult) {
if (!bindingResult.hasErrors()) { // validation errors
Date workdayBegin = workdayaddform.getBeginDate();
Date workdayEnd = workdayaddform.getEndDate();
if (!UtilityClass.dateIsAfterDate(workdayBegin, workdayEnd)) {
bindingResult.rejectValue("beginDate", "err.beginDate", "Aloitusaika ei voi olla lopetusajan jälkeen.");
return "addworkday";
}
Workday workday = new Workday();
Vehicle vehicle = new Vehicle();
workdayRepository.save(workday);
}
else {
return "addworkday";
}
return "redirect:/workdaylist";
}
}
After the 'dateIsAfterDate' check, it should direct one to 'addworkday' again, which it does, but it doesn't add the 'vehicles' model. Is there a way around this? I thought it would somehow just direct it to the above #RequestMapping(value= "addworkday") but this seems to not be the case.
Update:
#RequestMapping(value = "addworkday")
public String addWorkday(Model model, RedirectAttributes redirectAttributes){
System.out.println(redirectAttributes); // {}
System.out.println(model); // output in comment
model.addAttribute("workdayaddform", new WorkdayAddForm()); //I guess I need to add the old workdayform here?
model.addAttribute("vehicles", vehicleRepository.findAll());
return "addworkday";
}
#RequestMapping(value = "saveworkday", method = RequestMethod.POST)
public String save(#Valid #ModelAttribute("workdayaddform") WorkdayAddForm workdayaddform,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) {
if (!bindingResult.hasErrors()) { // validation errors
Date workdayBegin = workdayaddform.getBeginDate();
Date workdayEnd = workdayaddform.getEndDate();
if (!UtilityClass.dateIsAfterDate(workdayBegin, workdayEnd)) {
// Add the vehicle you want to send to the other method.
redirectAttributes.addFlashAttribute("workdayaddform", workdayaddform);
redirectAttributes.addFlashAttribute("vehicle", vehicleRepository.findAll());
redirectAttributes.addFlashAttribute("binding", bindingResult);
return "redirect:/addworkday";
}
You need to use the #RedirectedAttributes annotation in order to send attributes to another method in a controller. Also, you will need to add "redirect:/" to your returned url.
#RequestMapping(value = "saveworkday", method = RequestMethod.POST)
public String save(#Valid #ModelAttribute("workdayaddform") WorkdayAddForm workdayaddform,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) {
if (!bindingResult.hasErrors()) { // validation errors
Date workdayBegin = workdayaddform.getBeginDate();
Date workdayEnd = workdayaddform.getEndDate();
if (!UtilityClass.dateIsAfterDate(workdayBegin, workdayEnd)) {
// Add the vehicle you want to send to the other method.
redirectAttributes.addFlashAttribute("vehicle", vehicle);
redirectAttributes.addFlashAttribute("binding", bindingResult);
return "redirect:/addworkday";
}
// More code.
else {
redirectAttributes.addFlashAttribute("vehicle", new Vehicle());
return "redirect:/addworkday";
}
}
I wasn't sure if you meant, after the in the else or inside the if, so I add them in both places, just to make sure.
when iam trying to fetch the records with this query findByUserIdAndPassword(userId, password); using MongoRepository
but iam getting null all the time any suggestions?
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginValidation(#RequestParam String userId,#RequestParam String password) {
System.out.println("un"+userId);
System.out.println("password"+password);
Optional<TicketUserDto> ticketuser=ticketUserDao.findByUserIdAndPassword(userId, password);
}
Image of code:
I'm very new to Mockito and Junit. I'm working on creating test case for forgot password workflow. Below is the code for controller and test. Could anyone tell me how should I test on bindingresult?
#RequestMapping(value = "/user/public/forgotPassword", method = RequestMethod.POST)
public ModelAndView sendforgetPasswordLink(#ModelAttribute ForgetPasswordBean forgetPasswordBean,BindingResult result, HttpSession session) {
BreadCrumbBuilder.addLinktoBreadCrumb(session, new Link(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword", Constants.GROUP_USER, 0));
Map<String, String> breadCrumbs = HomePageController.setupInitialBreadCrumbs(session);
breadCrumbs.put(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword");
session.setAttribute(SessionAttributes.BREAD_CRUMBS,breadCrumbs);
ModelAndView mav = new ModelAndView();
mav.addObject("displayTitle", Constants.FORGET_PASSWORD_TITLE);
PublicUser user = publicUserService.findPublicUserByEmail(forgetPasswordBean.getEmail().toLowerCase());
if(user == null) {
result.reject("email", "An account does not exist for this email.");
mav.setViewName("publicuser/forgetPassword.jsp");
return mav;
}
String randomId = java.util.UUID.randomUUID().toString();
user.setTempId(randomId);
mailService.sendForgetPasswordLink(user);
publicUserService.savePublicUser(user);
String msg = "Password reset instructions have been sent to your email.";
mav.addObject("msg", msg);
mav.setViewName("message.jsp");
return mav;
}
This is test I created so far
#Test
public void TestForgetPasswordForNoUserFound() throws Exception {
final String input_email = "abc#test.com";
ForgetPasswordBean forgetPasswordBean = new ForgetPasswordBean();
forgetPasswordBean.setEmail(input_email);
PublicUser daoUser = new PublicUser();
daoUser.setEmail(input_email);
when(mockPublicUserService.findPublicUserByEmail(input_email)).thenReturn(null);
when(mockBindingResult.hasErrors()).thenReturn(true);
final ModelAndView modelAndView = controller.sendforgetPasswordLink(forgetPasswordBean, mockBindingResult, mockHttpSession);
ModelMap modelMap = modelAndView.getModelMap();
assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
assertEquals("publicuser/forgetPassword.jsp", modelAndView.getViewName());
assertModelAttributeValue(modelAndView, "displayTitle", Constants.FORGET_PASSWORD_TITLE);
}
What you can do is verify behavior of your BindingResult by checking that the reject method was called.
Basically instead of
assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
You can do the following
Mockito.verify(mockBindingResult).reject("email", "An account does not exist for this email.");
And that way you can verify that the method was called.
I am developing a project using Spring Boot. I've a controller which accepts GET requests.
Currently I'm accepting requests to the following kind of URLs:
http://localhost:8888/user/data/002
but I want to accept requests using query parameters:
http://localhost:8888/user?data=002
Here's the code of my controller:
#RequestMapping(value="/data/{itemid}", method = RequestMethod.GET)
public #ResponseBody
item getitem(#PathVariable("itemid") String itemid) {
item i = itemDao.findOne(itemid);
String itemname = i.getItemname();
String price = i.getPrice();
return i;
}
Use #RequestParam
#RequestMapping(value="user", method = RequestMethod.GET)
public #ResponseBody Item getItem(#RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
While the accepted answer by afraisse is absolutely correct in terms of using #RequestParam, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.
#RequestMapping(value="/data", method = RequestMethod.GET)
public #ResponseBody
Item getItem(#RequestParam("itemid") Optional<Integer> itemid) {
if( itemid.isPresent()){
Item i = itemDao.findOne(itemid.get());
return i;
} else ....
}
To accept both #PathVariable and #RequestParam in the same /user endpoint:
#GetMapping(path = {"/user", "/user/{data}"})
public void user(#PathVariable(required=false,name="data") String data,
#RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
curl 'http://localhost:8080/user/books'
curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'
In Spring boot: 2.1.6, you can use like below:
#GetMapping("/orders")
#ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
public List<OrderResponse> getOrders(
#RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
#RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
#RequestParam(value = "location_id", required = true) String location_id) {
// TODO...
return response;
#ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.
To accept both Path Variable and query Param in the same endpoint:
#RequestMapping(value = "/hello/{name}", method = RequestMethod.POST)
public String sayHi(
#PathVariable("name") String name,
#RequestBody Topic topic,
//#RequestParam(required = false, name = "s") String s,
#RequestParam Map<String, String> req) {
return "Hi "+name +" Topic : "+ topic+" RequestParams : "+req;
}
URL looks like : http://localhost:8080/hello/testUser?city=Pune&Pin=411058&state=Maha
I was interested in this as well and came across some examples on the Spring Boot site.
// get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith"
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
#GetMapping("/system/resource")
// this is for swagger docs
#ApiOperation(value = "Get the resource identified by id and person")
ResponseEntity<?> getSomeResourceWithParameters(#RequestParam String id, #RequestParam("person") String name) {
InterestingResource resource = getMyInterestingResourc(id, name);
logger.info("Request to get an id of "+id+" with a name of person: "+name);
return new ResponseEntity<Object>(resource, HttpStatus.OK);
}
See here also
I have a page which i enter parameters to query a list of records.
When the query button is clicked i get the list when an item form the list is clicked it takes me back to the first page with the record in display.
When i hit another button 'new' to clear the page and return an empty page a parameter is there in the url and it sets the value of an item on the page.The item that is there in the url is the crimeRecNo.
How can i get rid of this i want to return an empty page?
Scenario
I am on a page with the following url :http://adomain/crimeTrack/crime_registration.htm
I click Query which does a POST to another url which displays the list of records :http://adomain/crimeTrack/crimeList.htm
On the above page in 2 above i then select one record which does a POST and takes me to the followig url: http://adomain/crimeTrack/getCrime/6.htm - where 6 is the crimeRecNo.
I am now on the above url and i hit the 'NEW' button to get a blank form with the url in 1 above. When i hit new a POST is done to the controller method in code sample 4 under
This method does a redirect to the url which is mapped to a GET method however the final url looks like this : http://adomain/crimeTrack/%20crime_registration.htm?crimeRecNo=6
The value 6 remains in the crimeRecNo field and the entire form is not cleared.
Under is the controller methods:
1. Initial page request
#RequestMapping(value = "crime_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute Crime crime,BindingResult result, ModelMap m, Model model, SessionStatus status,HttpSession session) throws Exception {
try {
logger.debug("In Crime Registration Controller");
myCriminalList.put("dbcriminalList",
this.citizenManager.getListOfCriminals());
...................
session.setAttribute("page", 0);
return new ModelAndView("crime_registration");
} catch (Exception e) {
logger.debug("Exception In CrimeRegistration Controller : "
+ e.getMessage());
return new ModelAndView("crime_registration");
}
}
2. Query For List of Items
#RequestMapping(value = "crimeList.htm", method = RequestMethod.POST)
public ModelAndView handelCrimeList(#ModelAttribute Crime crime,
BindingResult result, ModelMap m, Model model) throws Exception {
if (crimeManager.getCrimesList(crime).size() <= 0) {
model.addAttribute("dbcriminals", myCriminalList);
........
model.addAttribute("crimeTypeList", crimeTypeManager.getCrimeTypeList(crime.getOffenceCatId()));
model.addAttribute("icon", "ui-icon ui-icon-circle-close");
model.addAttribute("results","Error: Query Caused No Records To Be Retrieved!");
return new ModelAndView("crime_registration");
}
model.addAttribute("crimes", crimeManager.getCrimesList(crime));
return new ModelAndView("crimeList");
}
3. Request For One Item/When item is selected from list
#RequestMapping(value = "getCrime/{crimeRecNo}.htm", method = RequestMethod.POST)
public ModelAndView getCrime(#PathVariable Integer crimeRecNo,
#ModelAttribute Crime crime, BindingResult result, ModelMap m,
Model model, HttpServletRequest request,
HttpServletResponse response, HttpSession session) throws Exception {
try {
model.addAttribute("crime", crimeManager.getCrimeRecord(crimeRecNo));
session.setAttribute("crimeRecNo", crimeRecNo);
//model.addAttribute("victimList", citizenManager.getVictimListByCrimeRecNo(crimeRecNo));
} catch (Exception e) {
logger.error("Exception in CitizenRegistrationController - ModelAndView getCitizen "
+ e);
}
int crimeCatId = crimeManager.getCrimeRecord(crimeRecNo).getOffenceCatId();
logger.info("crime category number is : "+crimeCatId);
myCrimeTypeList.put("crimeTypeList", this.crimeTypeManager.getCrimeTypeList(crimeCatId));
model.addAttribute("dbcriminals", myCriminalList);
.....
session.setAttribute("crimeRecNo", crimeRecNo);
return new ModelAndView("crime_registration");
}
4. Request For NEW Form
#RequestMapping(value = "crime_registration_new.htm", method = RequestMethod.POST)
public String loadNew(HttpServletRequest request,Model model,
HttpServletResponse response,SessionStatus status,HttpSession session) throws Exception {
status.setComplete();
return "redirect: crime_registration.htm";
//return new ModelAndView(new RedirectView("crime_registration.htm"));
}
Adding this to 4 did the trick
#RequestMapping(value = "crime_registration_new.htm", method = RequestMethod.POST)
public String loadNew(HttpServletRequest request,Model model,
HttpServletResponse response,SessionStatus status,HttpSession session) throws Exception {
status.setComplete();
model.addAttribute("crime", new Crime());
return "redirect: crime_registration.htm";
//return new ModelAndView(new RedirectView("crime_registration.htm"));
}