发布和获取未映射到Spring启动-状态:404

时间:2019-01-09 09:39:20

标签: java mysql spring-boot jpa

我有一个简单的应用程序来测试Spring Boot。 下面是配置,并根据Spring文档设置了软件包。 应用程序启动中没有错误。在Eclipse中使用Spring Boot。 仍然控制器未映射到服务器,并且当我执行Post或Get时说:

{
    "timestamp": 1547026379146,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/postdata"
}

存储库:

package com.abc.nice.repo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.abc.nice.entity.Messages;



@Repository
public interface MessagesRepository extends JpaRepository<Messages, Long> {

}

实体:

package com.abc.nice.entity;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import javax.persistence.Column;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;



@Entity
@Table(name = "Messages")
public class Messages{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;


@Size(max = 100)
private String toNumber; 


@Size(max = 250)
private String hsm; 

@Size(max = 250)
private String template; 

@Size(max = 250)
private String parameters; 



public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getTo() {
    return toNumber;
}

public void setTo(String toNumber) {
    this.toNumber = toNumber;
}

public String getHsm() {
    return hsm;
}

public void setHsm(String hsm) {
    this.hsm = hsm;
}

public String getTemplate() {
    return template;
}

public void setTemplate(String template) {
    this.template = template;
}

public String getParameters() {
    return parameters;
}

public void setParameters(String parameters) {
    this.parameters = parameters;
}



}

控制器:

package com.abc.nice.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.RestController;
import org.springframework.web.client.RestTemplate;

import com.abc.nice.entity.Messages;
import com.abc.nice.repo.MessagesRepository;

@RestController
public class ControllerRest {

    @Autowired
    private Messages msgDao;
    private MessagesRepository msgRepo;


    RestTemplate restTemplate;

    @GetMapping({ "/StatusData" })
    public List<Messages> index() {
        return this.msgRepo.findAll();
    }

    @PostMapping(path = {"/postdata"})
    public ResponseEntity<Messages> createBody(@RequestBody Map<String, String> body) {
        this.msgDao = new Messages();
        this.msgDao.setTemplate((String) body.get("template"));
        this.msgDao.setParameters((String) body.get("parameters"));
        this.msgDao.setHsm((String) body.get("hsm"));
        this.msgDao.setTo((String) body.get("to"));

        return new ResponseEntity<Messages>(this.msgRepo.save(this.msgDao), HttpStatus.OK);
    }

}

MainClass:

package com.abc.nice;

import org.hibernate.HibernateException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;








@SpringBootApplication
//@EntityScan("com.abc.nice.entity")
@ComponentScan({"com.abc.nice.entity","com.abc.nice.controller"})
@EnableJpaRepositories({"com.abc.nice.repo"})
//@EnableAutoConfiguration


public class TestApplication extends SpringBootServletInitializer {


    public static void main(String[] args) {


        SpringApplication.run(TestApplication .class, args);



    }

}

启动日志:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.9.RELEASE)

2019-01-09 17:33:27.724  INFO 19732 --- [           main] com.abc.nice.TestApplication : Starting TestApplication on abcD02 with PID 19732 (C:\Users\abcd\Desktop\test\target\classes started by abcD in C:\Users\abcd\Desktop\test)
2019-01-09 17:33:27.728  INFO 19732 --- [           main] com.abc.nice.TestApplication : No active profile set, falling back to default profiles: default
2019-01-09 17:33:27.827  INFO 19732 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:33:29.489  INFO 19732 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-01-09 17:33:29.506  INFO 19732 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-01-09 17:33:29.507  INFO 19732 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2019-01-09 17:33:29.746  INFO 19732 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-01-09 17:33:29.746  INFO 19732 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1922 ms
2019-01-09 17:33:30.005  INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-01-09 17:33:30.009  INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-01-09 17:33:30.009  INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-01-09 17:33:30.009  INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-01-09 17:33:30.009  INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-01-09 17:33:30.598  INFO 19732 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-01-09 17:33:30.610  INFO 19732 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-01-09 17:33:30.680  INFO 19732 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2019-01-09 17:33:30.682  INFO 19732 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-01-09 17:33:30.683  INFO 19732 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2019-01-09 17:33:30.749  INFO 19732 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-01-09 17:33:30.864  INFO 19732 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-01-09 17:33:31.033  INFO 19732 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update
2019-01-09 17:33:31.058  INFO 19732 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-01-09 17:33:31.388  INFO 19732 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:33:31.454  INFO 19732 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-01-09 17:33:31.455  INFO 19732 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-01-09 17:33:31.489  INFO 19732 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.489  INFO 19732 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.527  INFO 19732 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.866  INFO 19732 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-01-09 17:33:31.937  INFO 19732 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-01-09 17:33:31.942  INFO 19732 --- [           main] com.abc.nice.WhatsapptestApplication     : Started WhatsapptestApplication in 4.532 seconds (JVM running for 6.213)
2019-01-09 17:39:45.612  INFO 19732 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2019-01-09 17:39:45.613  INFO 19732 --- [on(2)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:39:45.616  INFO 19732 --- [on(2)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2019-01-09 17:39:45.617  INFO 19732 --- [on(2)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

Application.properties:

#spring.datasource.type=org.apache.commons.dbcp.BasicDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/ptpreconn?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.data.jpa.repositories.enabled=true
#spring.jpa.database-platform=org.hibernate.dialect.MYSQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

server.port=${PORT:8080}

3 个答案:

答案 0 :(得分:1)

请附上来自您正在使用的带有HTTP动词的开发人员工具以及该请求的确切响应。我担心@GetMapping-为什么在花括号中? 关于后期映射,也许您应该描述消费和产生部分映射? 例如

@PostMapping(path = "/members", consumes = "application/json", produces = "application/json")

在没有这些部分的情况下,我从未使用过@PostMapping注释。

更新:

在Main class更改控制器中删除了不必要的组件扫描后,如下:

@RestController
public class ControllerRest {

    @Autowired
    private MessagesRepository msgRepo;

    RestTemplate restTemplate;

    @GetMapping({ "/StatusData" })
    public List<Messages> index() {
        return this.msgRepo.findAll();
    }

    @PostMapping(path = {"/postdata"})
    public ResponseEntity<Messages> createBody(@RequestBody Map<String, String> body) {
        Messages  msgDao = new Messages();
        msgDao.setTemplate((String) body.get("template"));
        msgDao.setParameters((String) body.get("parameters"));
        msgDao.setHsm((String) body.get("hsm"));
        msgDao.setTo((String) body.get("to"));

        return new ResponseEntity<Messages>(this.msgRepo.save(this.HttpStatus.OK);
    }
}

答案 1 :(得分:0)

  1. 将上下文路径添加到application.properties文件或application.yml,无论使用哪种方式。

    server.servlet.contextPath=/springbootapi

  2. 命中端点:POST方法的端点为:

    http://localhost:{PORT} / springbootapi / postdata

  3. 为什么不静态提供端口。我认为端口应为: server.port=8080

答案 2 :(得分:0)

我不明白您为什么将@RequestBody与"Map<String,String>".一起使用

尝试此代码:

@Autowired
private MessagesRepository msgRepo;

 @PostMapping("/postdata")
public ResponseEntity<Object> createBody(@RequestBody Message message) {
    Message saveMessage= msgRepo.save(message);

URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
        .buildAndExpand(saveMessage.getId()).toUri();

return ResponseEntity.created(location).build();
}