I am using swagger in Java rest service.model class not populating #apimodel and #apimodelproperty. When I use of high swagger spring MVC version it populating. But, I am getting error like this version does not contain Documention config. How to reslove this problem.swagger spring MVC?
0.5.3 version pom.xml
Spring.xml
This bean contain inside of spring XML file.
<bean id="documentationConfig"
class="com.mangofactory.swagger.configuration.DocumentationConfig" />
controller HomeController.java
package com.example.anand.controller;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
#Api(value = "main controller", description = "Endpoint for TEST Managemenent")
#Controller
#RequestMapping("/newfinalmvc")
public class HomeController {
#RequestMapping(value = "/addnew", method = RequestMethod.POST)
#ApiOperation(value = "Addnew ", notes = "Add new Controller")
public #ResponseBody Object addNew(#RequestBody hello hel) {
String getName = hel.getName();
System.out.println(getName);
hello h1 = new hello();
h1.setName(getName);
return h1;
}
}
Model class which helps to setter and getter
#Apimodel and #Apimodelproperty annotion not dispalying in model class level
public class hello {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Why am I facing this problem?
Related
I am new to spring and spring boot. I tried to build a project by following
an example I found here : http://www.javaguides.net/2018/09/spring-mvc-using-spring-boot2-jsp-jpa-hibernate5-mysql-example.html.
Here is my Application:
package com.SportyShoe;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#ComponentScan(basePackages = "com.SportyShoe")
#SpringBootApplication
#EntityScan("com.SportyShoe.*")
#EnableJpaRepositories
public class SportyShoeApplication {
public static void main(String[] args) {
SpringApplication.run(SportyShoeApplication.class, args);
}
}
Here is my Entity:
package com.SportyShoe.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Shoe")
public class Shoe {
#Id
#Column(name="id")
private String id;
#Column(name="colour")
private String colour;
#Column(name="gender")
private String gender;
#Column(name="category")
private String category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Here is my Repository:
package com.SportyShoe.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.SportyShoe.Entity.Shoe;
#Repository
public interface ShoeRepositories extends JpaRepository<Shoe, Integer>{
}
Here is my Controller:
package com.SportyShoe.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.SportyShoe.repositories.ShoeRepositories;
#Controller
public class ShoeController {
#Autowired
ShoeRepositories shoeRepo;
#RequestMapping("/shoes")
public String shoeList(Model model) {
model.addAttribute("shoes", shoeRepo.findAll());
return "shoes";
}
}
Here is my application.properties:
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
logging.level.org.springframework=INFO
################### DataSource Configuration ##########################
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/Sporty_Shoes
spring.datasource.username=root
spring.datasource.password=MPword#123
################### Hibernate Configuration ##########################
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
When I reached this point in the example, it was written that running the Application will create the table in the database but all I got was an error as mentioned in the title.
What should do now to make it work?
I guess this comment is the key.
When I used 2.7.2 instead of 3.0.0(SnapShot) which I originally used
it started working.
Reading the documentation we realize the Spring Boot JPA module part of the Spring Boot 3 release turned to work with Jakarta Persistence API (JPA) rather than with javax.persistence.api. Because of this even configuring properly the Spring JPA annotations like #EntityScan it does not find the entities.
When upgrading Spring Boot up to version 3, the Persistence API artifact must be also migrated.
For more context about this change, it's well explained in this other SO thread.
Hope it helps anyone else!
The main problem was the version of Spring boot I used.
When I used 2.7.2 instead of 3.0.0(SnapShot) which I originally used it started working.
You have String ID in your Shoe class, but you've created an repository interface of JpaRepository<Shoe, Integer> instead of JpaRepository<Shoe, String>. So I suggest to define Integer ID in your Shoe class to match the repository.
Also the problem may be in a package definition - the javadoc suggests to use base package name like "com.SportyShoe", instead of "com.SportyShoe.*".
Also you may try to use type-safe entity scan like this:
#EntityScan(basePackageClasses = Shoe.class)
or like this if you have multiple entities:
#EntityScan(basePackageClasses = {Shoe.class, Lace.class})
Also try to remove #EntityScan, #ComponentScan and #EnableJpaRepositories - spring-boot tries to find entities and components in and under the package where you have #SpringBootApplication annotation by default (and jpa repositories, if you have a dependency on the classpath). These annotation may be used for extra configuration.
See information on this in the reference documentation.
I have a configuration YAML (application.yml) file which contains location data:
locations:
countries:
PL: Poland
DE: Germany
UK: UK
RU: Russia
I would like to load it so it will be available in the html select field.
I have created a following class:
package eu.test.springdemo.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Map;
#ConfigurationProperties(prefix = "locations")
public class CountryOptions {
private Map<String, String> countries;
public Map<String, String> getCountries() {
return countries;
}
public void setCountries(Map<String, String> countries) {
this.countries = countries;
}
}
Then I inject CountryOptions to Controller by #Autowire. However the list of countries is empty in controller.
Configuration of app is provided by class containing following annotations:
#Configuration
#EnableWebMvc
#EnableConfigurationProperties(CountryOptions.class)
#ComponentScan(basePackages="eu.test.springdemo")
public class DemoAppConfig implements WebMvcConfigurer {
Controller code
package eu.test.springdemo.mvc;
import eu.test.springdemo.model.CountryOptions;
import eu.test.springdemo.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("/")
public class HelloController {
#Autowired
CountryOptions countryOptions;
#GetMapping("/")
public String showPage() {
return "main-menu";
}
#GetMapping("/showForm")
public String showForm(Model model) {
model.addAttribute("student", new Student());
model.addAttribute("countries", countryOptions.getCountries());
return "helloworld-form";
}
}
So - any ideas why list of countries is not created from yaml file?
#ConfigurationProperties is a Spring Boot feature and will not be bound to the application.yml if you aren't using it. The best solution is usually to convert to Boot.
I have a HTML page that is launched from a java controller after a post and I want to attach a query string value in the url ex: (localhost:8000/gdata?id=11). Can this be done? Here is my controller code:
package com.sa.example;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestParam;
import com.sentinel.advisor.GData;
import com.sentinel.advisor.GDataJdbcRepository;
#Controller
public class GDataController {
#Autowired
GDataJdbcRepository repository;
#GetMapping("/gdata")
public String gDataForm(Model model) {
return "gData";
}
#PostMapping("/gdata")
public String gDataSubmit(#ModelAttribute GData gData) {
String returnString = repository.insert(gData);
//returnString should be returned in the url as a query string
return "result";
}
}
You can use a redirect (it is best practice to redirect after post regardless see - https://en.wikipedia.org/wiki/Post/Redirect/Get.
Spring's redirect view:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/view/RedirectView.html
Something like:
#Controller
public class GDataController {
#Autowired
GDataJdbcRepository repository;
#GetMapping("/gdata")
public String gDataForm(Model model) {
return "gData";
}
#PostMapping("/gdata")
public RedirectView gDataSubmit(#ModelAttribute GData gData) {
String returnString = repository.insert(gData);
return new RedirectView("/sucess?returnString=" + returnString, true);
}
#GetMapping("/success")
public String getResultPage(#RequestParam("returnString")String returnString){
return "result";
}
}
Im trying to have java respond to a GET request from Postman. When I use Postman to send a GET request to localhost:8080/chat this is the response (I had expected to get an empty list returned as there is no data present yet:
{
"timestamp": "2018-04-02T20:00:26.413+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/chat"
}
I have 2 packages in my application. They are com.dogo and com.dogochat.chat. The file in com.dogo is DogoApplication.java. This is the code:
package com.dogo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DogoApplication {
public static void main(String[] args) {
SpringApplication.run(DogoApplication.class, args);
}
}
The second package is called com.dogochat.chat. There are 3 files (2 classes and 1 interface). The file names are Message.java, MessageController.java, and MessageRepository.java.
This is the code in Message.java:
package com.dogochat.chat;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="message")
public class Message {
#Id
#GeneratedValue
private Integer id;
private String name;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
This is the code in MessageController.java:
package com.dogochat.chat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/chat")
public class MessageController {
#Autowired
MessageRepository dao;
#GetMapping("/get")
public List<Message> getMessages(){
List<Message> foundMessages = dao.findAll();
return foundMessages;
}
#PostMapping("/post")
public ResponseEntity<Message> postMessage(#RequestBody Message message)
{
// saving to DB using instance of the repo interface
Message createdMessage = dao.save(message);
// RespEntity crafts response to include correct status codes.
return ResponseEntity.ok(createdMessage);
}
}
This is the code in MessageRepository.java (although I dont think this is needed for this small test)
package com.dogochat.chat;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MessageRepository extends JpaRepository<Message, Integer>{
}
Any help/suggestions are greatly appreciated.
Thanks.
I know I am pretty late for the response, but better late than never.
This is a very common mistake for new Spring boot developers and I have also faced this issue several times.
The reason for this is the package under which you have your main() method.
In your case your MessageController, Message and your MessageRepository is under the package com.dogochat.chat, but then your main() method is under com.dogo which is completely a different package.
#SpringBootApplication internally runs #ComponentScan and if parent package and child packages are different, it cannot run and scan and throws the above error.
To avoid this confusion, follow this package structure.
Hope this helps. Happy coding !
Check to see if your #SpringBootApplication class is on top of all your packages or at least in the same package. It seems like your URL path is not visible.
Also, in your PostMan, you have to configure your headers the content-type=application/json.
For a more readable code (just my point of view), you should have something like this :
package com.dogochat.chat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/chat")
public class MessageController {
#Autowired
MessageRepository dao;
#GetMapping("/get")
public List<Message> getMessages(){
List<Message> foundMessages = dao.findAll();
return foundMessages;
}
#PostMapping("/post")
public ResponseEntity<Message> postMessage(#RequestBody Message message)
{
// saving to DB using instance of the repo interface
Message createdMessage = dao.save(message);
// RespEntity crafts response to include correct status codes.
return ResponseEntity.ok(createdMessage);
}
}
For example,
package com.spring.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(final Model model) {
model.addAttribute("msg", "SUCCESS");
return "hello";
}
}
I want to test model's attribute and its value from home() using JUnit. I can change return type to ModelAndView to make it possible, but I'd like to use String because it is simpler. It's not must though.
Is there anyway to check model without changing home()'s return type? Or it can't be helped?
You can use Spring MVC Test:
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(model().attribute("msg", equalTo("SUCCESS"))) //or your condition
And here is fully illustrated example
You can use Mockito for that.
Example:
#RunWith(MockitoJUnitRunner.class)
public HomeControllerTest {
private HomeController homeController;
#Mock
private Model model;
#Before
public void before(){
homeController = new HomeController();
}
public void testSomething(){
String returnValue = homeController.home(model);
verify(model, times(1)).addAttribute("msg", "SUCCESS");
assertEquals("hello", returnValue);
}
}