i am new to Spring MVC, i have created spring 3.2 project using maven in eclipse. i am implementing AbstractAnnotationConfigDispatcherServletInitializer class for java based configuration.
i have following plugins and dependencies in pom.xml
<build>
<plugins>
<!--source level should be 1.6 (which is not Maven default) for java EE
6 projects, so let's change it -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<!-- When using xml-less approach, you need to disable Maven's warning
about missing web.xml -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!--We need servlet API for compiling the classes. Not needed in runtime
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--adding spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<!-- Add Taglib support -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
Initializer class is as......
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebappConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebappConfig class is as......
#Configuration
#ComponentScan(basePackages={"com.sandip.controllers"})
#EnableWebMvc
public class WebappConfig extends WebMvcConfigurerAdapter{
//add view Resolver, Tell SpingMVC where to find view scripts
#Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
and finally i have a HomeController as..........
#Controller
public class HomeContoller {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
}
}
when i run this my project with jetty after maven build it display the following output in browser.....
springZeroXml is my project name there is no errro in console, please help ..........
I did lot of googleing and find out i need to override the addViewControllers method of WebMvcConfigurerAdapter class in WebAppConfig. and code is..........
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
Related
I spent a lot of time to debug this problem, but I could not find a solution. So then I used a workaround but I want to share the problem in order to help someone in the same situation.
The application, in a nutshell, is a TeamCity plugin, which communicates with nexus repository.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>some-plugin</artifactId>
<groupId>com.something</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>some-plugin-server</artifactId>
<packaging>jar</packaging>
<properties>
<jaxb.version>2.3.0</jaxb.version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>server-api</artifactId>
<version>${teamcity-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>server-web-api</artifactId>
<version>${teamcity-version}</version>
<type>war</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>tests-support</artifactId>
<version>${teamcity-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
There is mentiond parent but it contains nothing more than repositories and pluginRepositories settings.
Annotations above my java classes:
#XmlRootElement(name = "versioning")
#XmlAccessorType(XmlAccessType.FIELD)
public class Versioning implements Serializable {
private static final long serialVersionUID = 2L;
private String latest;
private String release;
#XmlElementWrapper(name="versions")
#XmlElement(name = "version")
private List<String> versions;
public String getLatest() {
return latest;
}
public void setLatest(String latest) {
this.latest = latest;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public List<String> getVersions() {
return versions;
}
public void setVersions(List<String> versions) {
this.versions = versions;
}
}
#XmlRootElement(name = "metadata")
#XmlAccessorType(XmlAccessType.FIELD)
public class MetaData implements Serializable {
private static final long serialVersionUID = 1L;
#XmlElement(name = "versioning")
private Versioning versioning;
public Versioning getVersioning() {
return versioning;
}
public void setVersioning(Versioning versioning) {
this.versioning = versioning;
}
}
The classes represents metadata.xml from nexus. From pom.xml there is no clear that teamcity dependencies adding spring 4 into my project:
Spring configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="constructor">
<bean id="versionService" class="com.aliter.teamcity.service.impl.VersionServiceImpl" autowire="byName"/>
<bean id="appController" class="com.aliter.teamcity.AppController"/>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
</beans>
In the VersionServiceImpl.class, there is a method sending request into nexus:
private MetaData getMetaData(String url) {
HttpEntity<String> request = new HttpEntity<>(getAuthorization());
try {
ResponseEntity<MetaData> metaDataResponseEntity = restTemplate.exchange(url, HttpMethod.GET, request, MetaData.class);
return metaDataResponseEntity.getBody();
} catch (RestClientException e) {
LOGGER.error("Metadata xml cannot be obtained.", e);
return null;
}
}
private HttpHeaders getAuthorization() {
String plainCreds = "username:password";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_XHTML_XML, MediaType.TEXT_HTML));
headers.add("Authorization", "Basic " + base64Creds);
return headers;
}
I got the exception: RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.aliter.teamcity.model.MetaData] and content type [application/xml]
RestTemplate explicitly by this: private static final boolean jaxb2Present =
ClassUtils.isPresent("javax.xml.bind.Binder", RestTemplate.class.getClassLoader()); registers Jaxb2RootElementHttpMessageConverter, it was there I checked that. I did debug and stopped when spring Http response handler trying to recognize through Jaxb2RootElementHttpMessageConverter JAXB annotations above my classes and from method:
#Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return (clazz.isAnnotationPresent(XmlRootElement.class) || clazz.isAnnotationPresent(XmlType.class)) &&
canRead(mediaType);
}
It returns that annotations are not present above the classes, but they are even there. I used JDK 8.
I am using Glassfish 5.0 with a Java Web App built in Maven framework. I have set up the Connection Pool and it is connected when you ping it.
I have placed the persistent.xml file in
src/main/java/META-INF
with the config:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ramsoPU" transaction-type="JTA">
<jta-data-source>jdbc/ramsovarvet</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
However, when trying to instantiate the EntityManager I get the error message 'Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null'
I have checked that the peristent.xml is in the classpath in the war file. it is in:
WEB-INF/classes/META-INF/persistence.xml
The JNDI name is correct, as I set it up in the server context.
Below is the code where I instantiate the EM with the persistent unit:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uk.ac.city.douglas.varv.Job.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import uk.ac.city.douglas.varv.Account.domain.Customer;
import uk.ac.city.douglas.varv.Job.domain.Boat;
import uk.ac.city.douglas.varv.Job.domain.BoatVariant;
import uk.ac.city.douglas.varv.Job.domain.BoatVariantEngine;
import uk.ac.city.douglas.varv.Job.domain.Engine;
import uk.ac.city.douglas.varv.Job.domain.Storage;
/**
*
* #author douglaslandvik
*/
#Stateless
public class VarvRepositoryJPQL implements VarvRepository {
#PersistenceContext(unitName="ramsoPU")
private EntityManager em;
#Override
public List<Customer> getAllCustomers(){
TypedQuery query = em.createQuery("SELECT c FROM Customer AS c",Customer.class);
return query.getResultList();
}
#Override
public List<Boat> getAllBoats() {
TypedQuery query = em.createQuery("SELECT b FROM Boat AS b ORDER by b.brand ASC",Boat.class);
return query.getResultList();
}
#Override
public void addEmployee() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void saveBoat(Boat boat) {
em.persist(boat);
}
#Override
public void saveCustomer(Customer customer) {
em.persist(customer);
}
#Override
public void eraseCustomerById(int id) {
Customer customer = em.find(Customer.class, id);
em.remove(customer);
}
#Override
public List<Storage> getAllStorages() {
TypedQuery query = em.createQuery("SELECT s FROM Storage AS s",Storage.class);
return query.getResultList();
}
#Override
public List<Engine> getAllEngines() {
TypedQuery query = em.createQuery("SELECT e FROM Engine AS e",Engine.class);
return query.getResultList();
}
#Override
public List<BoatVariant> getAllBoatVariants() {
TypedQuery query = em.createQuery("SELECT b FROM BoatVariant AS b",BoatVariant.class);
return query.getResultList();
}
#Override
public void saveBoatVariant(BoatVariant boatVariant) {
em.persist(boatVariant);
}
#Override
public List<Boat> getAllBoatsByBrand(String brand) {
TypedQuery query = em.createQuery("SELECT b FROM Boat AS b WHERE b.brand LIKE :brand ORDER BY b.brand", Boat.class);
query.setParameter("brand", brand+"%");
return query.getResultList();
}
#Override
public List<Boat> getAllBoatsByModel(String model) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public List<Boat> getAllBoatsById(int id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public List<String> getAllBoatBrands() {
TypedQuery query = em.createQuery("SELECT DISTINCT b.brand FROM Boat AS b", String.class);
return query.getResultList();
}
#Override
public Boat findBoatById(int id) {
return em.find(Boat.class, id);
}
#Override
public Customer findCustomerById(int id) {
return em.find(Customer.class, id);
}
#Override
public List<Engine> findEnginesByBrand(String brand) {
TypedQuery query = em.createQuery("SELECT e FROM Engine AS e WHERE e.brand LIKE :brand ORDER BY e.brand", Engine.class);
query.setParameter("brand", brand+"%");
return query.getResultList();
}
#Override
public void addEngine(Engine engine) {
em.persist(engine);
}
#Override
public Engine findEngineById(int id) {
return em.find(Engine.class, id);
}
#Override
public void removeEngineById(int id) {
Engine engine = em.find(Engine.class, id);
em.remove(engine);
}
#Override
public List<BoatVariant> findAllBoatVariantByCustomerId(int customerId) {
TypedQuery query = em.createQuery("SELECT bv FROM BoatVariant AS bv WHERE bv.customerId = :customerId ", BoatVariant.class);
query.setParameter("customerId", customerId);
return query.getResultList();
}
//nya jävlar
#Override
public void addBoatVariantEngine(BoatVariantEngine boatVariantEngine) {
em.persist(boatVariantEngine);
}
#Override
public void removeBoatVariantEngineById(BoatVariantEngine boatVariantEngine) {
em.remove(boatVariantEngine);
}
#Override
public List<BoatVariantEngine> findBoatVariantEngineById(int boatId, int customerId, int engineId) {
TypedQuery query = em.createQuery("SELECT bve FROM BoatVariantEngine AS bve WHERE bve.customerId = :customerId AND bve.boatId = :boatId AND bve.engineId = :engineId ", BoatVariantEngine.class);
query.setParameter("customerId", customerId);
query.setParameter("boatId", boatId);
query.setParameter("engineId", engineId);
return query.getResultList();
}
#Override
public BoatVariant findAllBoatVariantByCustomerIdAndBoatId(int customerId, int boatId) {
TypedQuery query = em.createQuery("SELECT bv FROM BoatVariant AS bv WHERE bve.customerId = :customerId AND bve.boatId = :boatId", BoatVariant.class);
query.setParameter("customerId", customerId);
query.setParameter("boatId", boatId);
return (BoatVariant) query.getSingleResult();
}
#Override
public void removeBoatVariant(BoatVariant boatVariant) {
em.remove(boatVariant);
}
}
The pom file is below:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>uk.ac.city.douglas</groupId>
<artifactId>varv</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>varv</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.asayama.gwt.jquery</groupId>
<artifactId>gwt-jquery</artifactId>
<version>0.1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.bluecatcode.mockito</groupId>
<artifactId>mockito-1.10.19-extended</artifactId>
<version>1.0.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>varv</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>varv</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
The name of the persistence unit file must be persistence.xml but in your case the name of the file is persistent.xml, that's why the container can't detect the persistence unit name.
So change the persistence file name to persistence.xml. Also don't forget to call the service class VarvRepositoryJPQL using #EJB for example:
#EJB
VarvRepositoryJPQL varvRepository;
and then call it.
Validation of RequestParam using custom validation annotation #ValidCode doesn't work. But If use #Pattern instead it starts working. What am I doing wrong, please?
The controller:
#Validated
#RestController
public class MyEndpoint {
#RequestMapping(path = "/test", method = GET)
public MyResponse findItems(#ValidCode #RequestParam("code") String code) {
return new MyResponse("A001");
}
}
My validation annotation:
#Retention(RUNTIME)
#Target({FIELD, PARAMETER})
#Pattern(regexp = "^[A-Z0-9]{4}?$")
public #interface ValidCode {
String message() default "{ValidCode.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Web MVC config:
#Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
<relativePath></relativePath>
</parent>
...
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
...
</dependencies>
</project>
BUT if I change controller method following way validation starts working:
#RequestMapping(path = "/test", method = GET)
public MyResponse findItems(#Pattern(regexp="^[A-Z0-9]{2}?$") #RequestParam("code") String code) {
return new MyResponse("A001");
}
Many thanks in advance.
I use Swagger 2 with non-spring-boot and I also can deploy my app on Tomcat and run it successfully. But the controller does not appear in swagger-ui.html, just the empty page with the green swagger title show up. I have spent two days on this issue. Would you give me some advice?
#Controller means the class as bellow:
#Api
#Controller
#RequestMapping("/user")
public class UserController {
protected Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#RequestMapping("/showInfos")
public #ResponseBody Object showUserInfos(){
logger.info("-----------------------showUserInfos-----------------------");
List<UserInfo> userInfos = userService.getUsers();
return userInfos;
}
my spring-mvc.xml configuration as follows:
<mvc:annotation-driven/>
<!#Controller inject bean -->
<context:component-scan base-package="com.roy.demo , version" />
<!-- Enables swgger ui -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
<!-- Include a swagger configuration -->
<bean name="/applicationSwaggerConfig" class="com.roy.demo.config.ApplicationSwaggerConfig" />
also my swagger configuration class is as follows:
#EnableSwagger2
public class ApplicationSwaggerConfig {
private static final Logger LOGGER = Logger.getLogger(ApplicationSwaggerConfig.class);
#Bean
public Docket api() {
LOGGER.info("################################ into Docket api() #####################################");
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.roy.demo.controller"))
.paths(PathSelectors.any())
.build();
}
}
my maven pom.xml swagger2 dependency as follows:
<!-- Swagger 2.0 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
Bellow is the result when i enter the endpoint url:http://localhost:8080/Spring_SpringMVC_Mybatis/swagger-ui.html
I also new to Swagger but Below code I used for my swagger configuration and it works well for me.I done the configuration in class.
Configuration class.
#Configuration
#EnableWebMvc
#EnableSwagger2
#ComponentScan(basePackages = "com.*")
#PropertySource(value = { "classpath:log4j.properties" })
public class SpringConfig extends WebMvcConfigurerAdapter {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()).directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
#SuppressWarnings("deprecation")
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"API",
"API for xxxx",
"API TOS",
"Terms of service",
"xxx",
"License of API",
"");
return apiInfo;
}
}
Maven Dependency:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
Controller Class
#RestController
#Api(value="users", description="Endpoint for user management")
public class Controller {
}
endpointurl:
https://localhost:8080/AppName/swagger-ui.html
clear your browser cache and try again.
or use incognito tab
It worked well for me
It happened to me that one of the controllers was not displayed. The problem was the kotlin class has not declared any package. Declaring a package in the controller fixed the problem.
First note that I am a total beginner regarding this. I started spring maven web project and wrote 3 classes (posted below).
I put the project to be run on my tomcat server (from eclipse) and when I start it i can access localhost:8080 (tomcat default page is shown), but when i try to access localhost:8080/greeting i get 404 error, what am I doing wrong? I'll also post my pom.xml
Thank you
Greeting:
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
GreetingController:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
Application:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
</parent>
<artifactId>WebTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.2.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
If you deploy your application into a standalone Tomcat instance and it is not deployed as the ROOT application, you have to add the name of the application in your URL. You can check the Tomcat log for the exact name. If you named your project "helloworld", then Eclipse usually deploys the project with that name as application name, so you should call your application with the URL http://localhost:8080/helloworld/greeting
Unless you really need to deploy your application to an external Tomcat server, you can solve your problem by just running your application's main method directly. Spring Boot will start an embedded Tomcat instance for you.
If you need to be able to deploy your application to an external Tomcat server, then you need to change your Application class a little bit so that it'll start up correctly. You need to extend SpringBootServletInitializer and override the configure method:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
This is covered in the traditional deployment section of the Spring Boot reference documentation.