Thyme, Spring: stuck on creating a single item view - java

I have successfully implemented adding a visit and showing a list of all visits, but now I'm stuck on creating a view for a single visit.
My findById function works:
logger.info("Visit id 2 -> {}", repository.findById(2));
Visit id 2 -> DentistVisitDTO[id='0', dentistName='Mait Kuusevaik', visitTime='2018-10-12T12:15']
And when I click on a list item it sucessfully redirects to a url using ID (i.e "/results/1" and so on. Is there a way I can use the ID from the URL and somehow render the item on the page using findById()?
I'm new to Spring and Thyme.
public DentistVisitDTO findById(long id) {
return jdbcTemplate.queryForObject("SELECT * FROM DENTIST_VISIT where id=?", new Object[] { id },
new BeanPropertyRowMapper<DentistVisitDTO>(DentistVisitDTO.class));
}

You can use the #RequestMapping annotation of SpringMVC/SpringWeb to get the id attribute from the URL:
import org.springframework.web.bind.annotation.RequestMapping;
#RequestMapping(value="/results/{id}", method=RequestMethod.GET)
public String detail(#PathVariable(value="id") String id, Model model) {
DentistVisitDTO dentistVisit = repository.findById(id);
System.out.println("GET /results [" + id + "]");
model.addAttribute("dentistVisit", dentistVisit);
return "details";
}

Related

SpringBoot CrudRepository trying to update instead of create new entity

Spring Boot save method is trying to update and returns error like:
org.springframework.dao.IncorrectUpdateSemanticsDataAccessException:
Failed to update entity [com.xx.xx.Account#78a31407]. Id 1 not found
in database.
But my database is completely empty and I want to add new Entity. Here is the screenshots:
And here is the code:
#RequestMapping(path = "/banking/add", method = RequestMethod.POST)
public #ResponseBody ResponseEntity addAccount(#Validated #RequestBody Account account) throws IOException {
if(!account.getType().equals("TL") && !account.getType().equals("Altın") && !account.getType().equals("Dolar")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Account Type: " + account.getType());
}
System.out.println(account.getId());
account.setLastDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
BankingLogger.writeAccountToTheFile(account);
AccountCreateSuccessResponse res = new AccountCreateSuccessResponse("Account Created", account.getId());
this.repository.save(account);
return ResponseEntity.status(HttpStatus.CREATED).body(res);
}
and here is the request json:
{
"id": "1",
"name" : "Doğukan",
"surname" : "Gülyaşar",
"email" : "xxxx#gmail.com",
"tc" : "123123123",
"type" : "Dolar",
"isDeleted": "false"
}
Remove the id from the payload. Create or update logic is triggered by having or not having id. If the id is set beforehand, the entity with specified id is updated, otherwise new entity is created and id will be assigned by the database.

SpringBoot - How do I create a request which can be based on user input and is then picked up by a controller method?

I have managed to send a parameterised request based on the URL entered by the user, however I am not sure how to get the 2nd controller to properly receive the route for the URL field of the Project class object. How do I do this? I don't even know what to search.
//ProjectController
//Creating Project Object
Project project = new Project();
System.out.println("userID: " + userID);
//Getting values using webuser userid (Parameter that passed by model attribute)
WebUser webUser = webUserRepo.findUserById(Long.parseLong(userID));
//Setting values to project object to save
project.setUserID(webUser);
project.setDescription(description);
project.setTargets(targets);
project.setUrl(url);
// Getting date
Date date = new Date();
project.setPublishedOn(date);
//Save Project Object and get that saved Object for system.print
Project savedProject = projectRepo.save(project);
//Print saved Object
System.out.println("saved Project Object : "+ savedProject.toString());
//Set user id in model attribute for return page
model.addAttribute("userID", userID);
model.addAttribute("url", url);
return "/project-dashboard/" + savedProject.getUrl();
//Dashboard Controller:
#GetMapping("project/{url}")
public String serveProject(#PathVariable("url") String url, #RequestParam Long userID, Model model){
System.out.println("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO ADKLLDAL " + userID);
Project project = projectRepo.getById(userID);
System.out.println(project.toString());
model.addAttribute(project);
return "project";
}
Thanks for any help!

Spring MVC annotation #ModelAttribute

i have some question about Spring MVC annotation #ModelAttribute.
In first method named as "addProduct" i create Model model and after call model.addAttribute i can use "product" name in jsp file,for example product.getProductPrice.
But in second method named same as first,i added parameter
" #ModelAttribute("product") Product product ",but why??
If i will delete this annotation, my program works as same as before,please explain me)
Thank you very much,sorry for my English,i am from Ukraine)
#RequestMapping("/admin/productInventory/addProduct")
public String addProduct(Model model) {
Product product = new Product();
// add default for radio button!
product.setProductCategory("Mobile Phone");
product.setProductCondition("New");
product.setProductStatus("active");
model.addAttribute("product", product);
return "addProduct";
}
#RequestMapping(value = "/admin/productInventory/addProduct", method = RequestMethod.POST)
public String addProduct(#ModelAttribute("product") Product product, HttpServletRequest request) {
productDao.addProduct(product);
MultipartFile productImage = product.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
System.out.println(rootDirectory);
// product id as the file name
// !!!! TODO
// path = Paths.get(rootDirectory + "/WEB-INF/resources/image/" +
// product.getProductId() + ".png");
path = Paths.get("F:\\Spring\\eMusicStore\\src\\main\\webapp\\WEB-INF\\resources\\images\\"
+ product.getProductId() + ".png");
if (productImage != null && !productImage.isEmpty()) {
try {
productImage.transferTo(new File(path.toString()));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Product image saving failed", e);
}
}
return "redirect:/admin/productInventory";
}
Purpose #ModelAttribute is bind param/properties from request a model object,
say #ModelAttribute("person") Person person in your method, it will bind properties from object such name, age to Person and construct a object out of it. It does not pass anything to your view, it job finishes once the request submitted. Not carried down to the view of that action.
In contrast, when you have Model model you are explicitly constructing an object with property added to its attribute. It will be carried down to your view unlike what #ModelAttribute does above

Debugging a AngularJS + Spring MVC + Tomcat web application

My days of Java web development now lie about 6 years behind me and despite my hectic new life as a non-technical consultant I want to get back in to the tech world and equip myself with some essential web dev skills.
To get me started, I installed a vagrant box using this tutorial:
https://dzone.com/articles/vagrant
... which worked like a treat and got me my Ubuntu box on my Windows host machine up and running in no time. Also it comes with Java 7 and the Tomcat app server that I'm still quite familiar with from past days. Notwithstanding the fact that there are probably better servers out there to practice on, this one works and I'll use it for my tinkering for now. The example web app that came with the tutorial also works, so I'm confident that my Tomcat is running on the guest machine on port 8080.
The next step was to find a good AngularJS and Spring MVC tutorial. Again, while I know that AngularJS is the latest craze in web dev, Spring MVC may be somewhat outdated (?) but since I'm a Java-boy since I hatched from the Uni-egg I wouldn't mind going with it for now.
The tutorial I found is this one:
http://websystique.com/springmvc/spring-mvc-4-angularjs-example/
I downloaded the project from git and deployed it into my tomcat webapps folder. In the user_service.js file I left the REST_SERVICE_URI as http://localhost:8080/Spring4MVCAngularJSExample/user/ given that Tomcat runs on port 8080 on the host Ubuntu box and I can access the application on my guest machine in the browser at http://192.168.33.10:8080/Spring4MVCAngularJSExample
The problem is that the application (while it's showing up in the browser), does not load the mock-users that are populated in the UserServiceImpl class and that should show up when loading the app. When I check my Firefox console under the JavaScript tab, I get the 'Error while fetching Users' error message from the fetchAllUsers function in the user_controller.js script.
I suspect that the problem here is that the front-end (AngularJS $http service) cannot contact the back-end (Spring service). If there were no users in the back-end and returned 0, I wouldn't get the error but an empty set instead, hence my suspicion of some other problem.
My question is how to debug this web app from here? I have tried to look through the front-end console logs using the FF Developer tool (Debugger) and I must admit I haven't written any JUnit test to actually run a test against the Spring service implementation class.
Thanks for your advice, and let me know if I should provide any more details.
Cheers
AHL
Spring controller:
package com.websystique.springmvc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.websystique.springmvc.model.User;
import com.websystique.springmvc.service.UserService;
#RestController
public class HelloWorldRestController {
#Autowired
UserService userService; //Service which will do all data retrieval/manipulation work
//-------------------Retrieve All Users--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
//-------------------Retrieve Single User--------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(#RequestBody User user, UriComponentsBuilder ucBuilder) {
System.out.println("Creating User " + user.getUsername());
if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getUsername() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
userService.saveUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
//------------------- Update a User --------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUser(#PathVariable("id") long id, #RequestBody User user) {
System.out.println("Updating User " + id);
User currentUser = userService.findById(id);
if (currentUser==null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
currentUser.setUsername(user.getUsername());
currentUser.setAddress(user.getAddress());
currentUser.setEmail(user.getEmail());
userService.updateUser(currentUser);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
//------------------- Delete a User --------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteUser(#PathVariable("id") long id) {
System.out.println("Fetching & Deleting User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("Unable to delete. User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
userService.deleteUserById(id);
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
//------------------- Delete All Users --------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteAllUsers() {
System.out.println("Deleting All Users");
userService.deleteAllUsers();
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
}
IndexController.java:
package com.websystique.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public String getIndexPage() {
return "UserManagement";
}
}
Javascript user_controller.js:
'use strict';
angular.module('myApp').controller('UserController', ['$scope', 'UserService', function($scope, UserService) {
var self = this;
self.user={id:null,username:'',address:'',email:''};
self.users=[];
self.submit = submit;
self.edit = edit;
self.remove = remove;
self.reset = reset;
fetchAllUsers();
function fetchAllUsers(){
UserService.fetchAllUsers()
.then(
function(d) {
self.users = d;
},
function(errResponse){
console.error('Error while fetching Users');
}
);
}
function createUser(user){
UserService.createUser(user)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while creating User');
}
);
}
function updateUser(user, id){
UserService.updateUser(user, id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while updating User');
}
);
}
function deleteUser(id){
UserService.deleteUser(id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while deleting User');
}
);
}
function submit() {
if(self.user.id===null){
console.log('Saving New User', self.user);
createUser(self.user);
}else{
updateUser(self.user, self.user.id);
console.log('User updated with id ', self.user.id);
}
reset();
}
function edit(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id === id) {
self.user = angular.copy(self.users[i]);
break;
}
}
}
function remove(id){
console.log('id to be deleted', id);
if(self.user.id === id) {//clean form if the user to be deleted is shown there.
reset();
}
deleteUser(id);
}
function reset(){
self.user={id:null,username:'',address:'',email:''};
$scope.myForm.$setPristine(); //reset Form
}
}]);
Javascript user_service.js:
'use strict';
angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){
var REST_SERVICE_URI = 'http://localhost:8080/Spring4MVCAngularJSExample/user/';
var factory = {
fetchAllUsers: fetchAllUsers,
createUser: createUser,
updateUser:updateUser,
deleteUser:deleteUser
};
return factory;
function fetchAllUsers() {
var deferred = $q.defer();
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function createUser(user) {
var deferred = $q.defer();
$http.post(REST_SERVICE_URI, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while creating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function updateUser(user, id) {
var deferred = $q.defer();
$http.put(REST_SERVICE_URI+id, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while updating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function deleteUser(id) {
var deferred = $q.defer();
$http.delete(REST_SERVICE_URI+id)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while deleting User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
On the server (the vagrant host machine), I can wget the URL and get my data back from the Spring server:
vagrant#precise32:~$ wget http://localhost:8080/Spring4MVCAngularJSExample/user/--2016-08-26 11:08:24-- http://localhost:8080/Spring4MVCAngularJSExample/user/
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:8080... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/json]
Saving to: `index.html'
[ <=> ] 206 --.-K/s in 0s
2016-08-26 11:08:24 (9.77 MB/s) - `index.html' saved [206]
vagrant#precise32:~$ less index.html
this gives me the expected result set:
[{"id":1,"username":"Sam","address":"NY","email":"sam#abc.com"},{"id":2,"username":"Tomy","address":"ALBAMA","email":"tomy#abc.com"},{"id":3,"username":"Kelly","address":"NEBRASKA","email":"kelly#abc.com"}]
From your spring controller code all your request mappings are expecting user in the url so if you don't have this the spring controllers will not be called. Is you dispatcher servlet set up to except all http requests E.g /
The problem was a simple mistake:
In the user_service.js file, the REST_SERVICE_URI must be set to the address of the host machine:
http://192.168.33.10:8080/Spring4MVCAngularJSExample/user/
So, when deploying this to a (remote) server, I suppose the 192.168.33.10:8080 portion would need to be changed to that server's IP and the respective Tomcat port.
My problem existed (probably) because I was using a virtual box and had (mistakenly) used the host machine's IP instead of the guest machine's IP. Please correct me if I'm wrong, I'm still somewhat confused ....

the map of the model always returns an empty object

Good evening, I have a Spring MVC project on an e-commerce site.
concerning cart management, when I add a product to the cart by clicking the "Ajouter au panier", it adds good, but the problem if I add another product, I show that the second product .
I made "println" and I noticed that "model.asMap (). get (" panier ")" always returns null. what is the problem please?
Here are some screen prints on the console, controller and index.jsp
Controller
#RequestMapping(value = "/ajouterAuPanier")
public String ajouterAuPanier(#RequestParam Long idArticle, #RequestParam int quantite, Model model) {
System.out.println("111111111111111111111111111111111111111111111");
Panier panier = null;
if (model.asMap().get("panier") == null) {
System.out.println("222222222222222222222222222222222222222222222");
panier = new Panier();
System.out.println("333333333333333333333333333333333333333333333");
model.addAttribute("panier", panier);
System.out.println("9999999999999999999999999999999" + panier.getItems().size());
} else System.out.println("555555555555555555555555555555555555555555555");
panier = (Panier) model.asMap().get("panier");
panier.addArticle(metier.getArticle(idArticle), quantite);
model.addAttribute("categories", metier.listCategories());
model.addAttribute("articles", metier.listArticles());
return "index";
}

Categories