Using Jparepository's FindAll method with ModelAndView - java

My UserController class:
package org.peronalitymeet.controller;
import org.peronalitymeet.entity.User;
import org.peronalitymeet.entity.request.AddUserRequest;
import org.peronalitymeet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.List;
#RestController
public class UserController {
private UserRepository userRepository;
#Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(value="/users", method = RequestMethod.GET)
public List<User> findAllUsers(){
return userRepository.findAll();
}
#RequestMapping(value="/signup", method = RequestMethod.POST)
public void addUser(#RequestBody AddUserRequest addUserRequest){
User user = new User();
user.setFirstname(addUserRequest.getFirstname());
user.setSurname(addUserRequest.getSurname());
userRepository.save(user);
}
}
My problem is that now if i open the localhost:8080/users URL,
i will get all my users within JSON format. Previously i followed a Spring mvc tutorial, and there they used ModelAndView method to automatically open a jsp page if an URL was called.
Is there any way to use FindAll Users() and at the same time open a jsp or html page and list the result of the method within that?

#RestController is a meta-annotation that tells Spring to return the text that it gets back as-is to the user. It's equivalent to adding #ResponseBody #Controller to your class.
If you want to do something with a JSP, your class should look something like what I have below. I am only changing the /users endpoint, but the idea would apply everywhere.
package org.peronalitymeet.controller;
import org.peronalitymeet.entity.User;
import org.peronalitymeet.entity.request.AddUserRequest;
import org.peronalitymeet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
#Controller
public class UserController {
private UserRepository userRepository;
#Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(value="/users", method = RequestMethod.GET)
public ModelAndView findAllUsers(ModelAndView mav){
List<User> users = userRepository.findAll();
mav.addObject("users", users);
mav.setViewName("users");
return mav;
}
#ResponseBody
#RequestMapping(value="/signup", method = RequestMethod.POST)
public void addUser(#RequestBody AddUserRequest addUserRequest){
User user = new User();
user.setFirstname(addUserRequest.getFirstname());
user.setSurname(addUserRequest.getSurname());
userRepository.save(user);
}
}
Then set up your view page called users.jsp to display the items in the users variable and you should be set.

Related

Spring boot does not generate the json and shows me the white page

I've done a simple list with sql server, but it doesn't show me the result, it just shows me the white page.
I have no error in the console. Will the sql server 2017 be? please any help?
connection to sql server 2017
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=DB_PRUEBA_V1;integratedSecurity=true
spring.jpa.show-sql=true
#spring.jpa.hibernate.ddl-auto=update
server.port=8090
package app
package app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ProyectoV2Application {
public static void main(String[] args) {
SpringApplication.run(ProyectoV2Application.class, args);
}
}
package model
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "TB_USERS")
public class Users implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "COD_USER")
private int codUser;
#Column(name = "NOM_USER")
private String nomUser;
#Column(name = "EMA_USER")
private String emUser;
public int getCodUser() {
return codUser;
}
public void setCodUser(int codUser) {
this.codUser = codUser;
}
public String getNomUser() {
return nomUser;
}
public void setNomUser(String nomUser) {
this.nomUser = nomUser;
}
public String getEmUser() {
return emUser;
}
public void setEmUser(String emUser) {
this.emUser = emUser;
}
}
package repository
package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import model.Users;
#Repository
public interface UserDAO extends JpaRepository<Users, Integer>{
}
service
package service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import model.Users;
import repository.UserDAO;
#Service
public class UserService {
#Autowired
private UserDAO dao;
public List<Users> lista(){
return dao.findAll();
}
}
package controller
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import model.Users;
import service.UserService;
#RestController
#RequestMapping(value = "/CrudUsers")
public class UserController {
#Autowired
private UserService us;
#ResponseBody
#GetMapping(path = "/lista", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Users> lista(){
return us.lista();
}
}
Whitelabel Error Page
Because you created each class in different package like below,
app --> ProyectoV2Application
model --> Users
repository --> UserDAO
service --> UserService
controller --> UserController
But spring boot scans the classes that are either in root package or in sub package of root package, so move all these classes into sub packages of root package
app --> ProyectoV2Application
app.model --> Users
app.repository --> UserDAO
app.service --> UserService
app.controller --> UserController

MockMvc empty response/return

I just created a simple integration test with MockMvc for a controller. All works well, but there is no response provided even the controller method returns something.
Here is the Controller:
import depmgmt.service.deposit.HouseService;
import depmgmt.service.dto.deposit.HouseDTO;
import depmgmt.serviceweb.common.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
#RequestMapping("/rest/house")
public class HouseRestController extends BaseController {
private HouseService houseService;
#Autowired
public HouseRestController(HouseService houseService) {
this.houseService = houseService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public List<HouseDTO> getHouses(#RequestParam(value = "page", defaultValue = "1") int page,
#RequestParam(value = "size", defaultValue = "50") int size) {
validatePageRequest(page, size);
return houseService.getHouseList(page, size);
}
}
Here is the test controller:
import com.fasterxml.jackson.databind.ObjectMapper;
import depmgmt.service.deposit.HouseService;
import depmgmt.service.dto.deposit.HouseDTO;
import depmgmt.serviceweb.config.SpringServiceWebConfig;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes = {SpringServiceWebConfig.class})
#WebMvcTest(controllers = HouseRestController.class)
public class HouseRestControllerTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper objectMapper;
#MockBean
private HouseService houseService;
#Test
public void shouldGetHouses() throws Exception {
//given
List<HouseDTO> houseDTOS = new ArrayList<>();
HouseDTO houseDTO = HouseDTO.builder().country(null).city("City").owner(null).name("MyHouse").id(1l).address("HouseAddress").build();
houseDTOS.add(houseDTO);
when(houseService.getHouseList(1, 1)).thenReturn(houseDTOS);
//when
MvcResult mvcResult = mockMvc.perform(get("/rest/house/")
.contentType("application/json")
.param("page", "1")
.param("size", "1")).andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
}
When I execute the test the controller method is called successfully and it returns what it should:
HouseDTO houseDTO = HouseDTO.builder().country(null).city("City").owner(null).name("MyHouse").id(1l).address("HouseAddress").build();
houseDTOS.add(houseDTO);
when(houseService.getHouseList(1, 1)).thenReturn(houseDTOS);
However in the test Controller the: mvcResult.getResponse().getContentAsString() returns empty string:
What is wrong in the test?
The mistake what that there is no #ResponseBody on the method.
So either #RestController on the Class or #Controller on the class and #ResponseBody on the method.

Getting error 404 not found in postman while passing url through postman

When i pass this url http://localhost:8080/app/users using post request I am getting error 404 not found in postman....
I tried using some changes in my code but giving same error
Here is my controller class:
package com.controller;
import com.entity.User;
import com.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#RestController
#RequestMapping("/app")
public class UserController
{
#Autowired
private UserRepository userRepository;
#PostMapping("/users")
public User create(#RequestBody User user)
{
return userRepository.save(user);
}
#GetMapping("/users1")
public List<User> findAll()
{
return userRepository.findAll();
}
#DeleteMapping("/users/{user_id}")
public List<User> delete(#PathVariable("user_id") Long userId)
{
userRepository.deleteById(userId);
return userRepository.findAll();
}
#GetMapping("/users/{user_id}")
public Optional<User> findByUserId(#PathVariable("user_id") Long userId)
{
return userRepository.findById(userId);
}
}
[Directory structure:][1]
When i pass url through postman the data should get inserted in the database but it gives me error 404 not found

RequestMapping ; java Spring

I want make simple web service using java spring restful web service .
I Use request Mapping annotation in controller class but when i run project there is no mapping there .
Here is controller Class :
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import guru.webservice.domain.Customer;
import guru.webservice.services.CustomerService;
#RestController
#RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
public static final String BASE_URL = "api/v1/customers";
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping
List<Customer> getAllCustomers() {
return customerService.findAllCustomer();
}
#GetMapping("/{id}")
public Customer getCustomerById(#PathVariable Long id) {
return customerService.findCustomerById(id);
}
}
To let Spring scan and configure #Controller annotated classes, you need to configure component scanning on packages where controllers are stored.
i.e: /src/main/java/guru/webservices/spring/config/AppConfig.java
AppConfig.java:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc //THIS
#ComponentScan(basePackages = "guru.services") //THIS
public class AppConfig {
}
Also:
#Autowired
private CustomerService customerService;
And then:
#GetMapping("/{id}")
public ResponseEntity getCustomerById(#PathVariable("id") Long id) {
Customer customer = customerDAO.get(id);
if (customer == null) {
return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(customer, HttpStatus.OK);
}

Why Spring BindingResult or validator do not show any errors?

I am trying to validate the Spring Bean containing email but neither the validator nor the BindingResult do not show any error when email in the request Bean comes as empty string.
Please, see the following code:
Bean:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springmodules.validation.bean.conf.loader.annotation.handler.Email;
import org.springmodules.validation.bean.conf.loader.annotation.handler.NotEmpty;
#Component("grouponRedemptionFormBean")
#Scope("prototype")
public class GrouponRedemptionBean {
#NotEmpty(message = "Please enter your email addresss.")
#Email(message = "Please correct your email.")
private String email;
…
}
Controller:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class GrouponVoucherRedemptionController {
#Autowired
#Qualifier("defaultBeanValidator")
private Validator validator;
#RequestMapping(value="/groupon-redemption.ep", method=RequestMethod.POST)
public String PostGrouponRedemption(#Valid #ModelAttribute GrouponRedemptionBean grouponRedemptionBean, BindingResult bindingResult,
HttpServletRequest request, HttpServletResponse response, Model model){
Errors errors = new BeanPropertyBindingResult(grouponRedemptionBean, "grouponRedemptionFormBean");
validator.validate(grouponRedemptionBean, errors);
if(errors.hasErrors()) {
bindingResult.addAllErrors(errors);
}
if (bindingResult.hasErrors()) {
return GROUPON_REDEMPTION_VIEW;
}
...
XML configuration:
<mvc:annotation-driven />
You have wrong argument order - BindingResult must be immediately after the model object (GrouponRedemptionBean in your case). See the documentation:
The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more than one model object and Spring will create a separate BindingResult instance for each of them so the following sample won't work:
Invalid ordering of BindingResult and #ModelAttribute.
#RequestMapping(method = RequestMethod.POST)
public String processSubmit(#ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... }
Note, that there is a Model parameter in between Pet and BindingResult. To get this working you have to reorder the parameters as follows:
#RequestMapping(method = RequestMethod.POST)
public String processSubmit(#ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }
You can use
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Or this
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

Categories