Spring-Data项目未能接收我的Get/Post请求,显示“404未找到”。

huangapple go评论77阅读模式
英文:

Spring-Data Project is not receiving my Get/Post "404 not found"

问题

I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this **ERROR**:

D:\>curl -G  localhost:8080/demo/first?=Biagio
{"timestamp":"2020-10-04T22:46:35.996+00:00","status":404,"error":"Not Found","message":"","path":"/demo/first"}

And to each of my POST / Add requests like this **ERROR**:

D:\>curl localhost:8080/demo/add -d name=Giovanni -d email=giovanni@gmail.com -d surname=Jackie
{"timestamp":"2020-10-04T22:40:51.928+00:00","status":404,"error":"Not Found","message":"","path":"/demo/add"}

Below I enter the interested parties of my project to try to get something out of it, because I have been stuck for days now

AccessingDataMysqlApplication.java

package com.example.accessingdatamysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class AccessingDataMysqlApplication {
  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMysqlApplication.class, args);
  }
}

MainController.java

package com.example.accessingdatamysql.rest;

import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;

@RestController
@RequestMapping("/demo")
public class MainController {
  @Autowired
  private UserService userService;
  
  @Transactional
  @PostMapping(path="/demo/add")
  public String addNewUser(@PathVariable("name") String name, @PathVariable("email") String email,
  @PathVariable("surname") String surname) {
    UserDto n = new UserDto();
    n.setName(name);
    n.setSurname(surname);
    n.setEmail(email);
    userService.create(n);
    return "User Saved in DB";
  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  @GetMapping("/demo/first")
  public ResponseEntity<UserDto> fetchUser(@PathVariable("name") String name) {
    System.out.println(name);
    try {
      UserDto namefound = userService.findFirstByName(name);
      System.out.println("Name found");
      ResponseEntity<UserDto> user = new ResponseEntity<UserDto>(namefound, HttpStatus.OK);
      return user;
    } catch(NoResultException ne) {
      System.out.println("User not found");
      return new ResponseEntity("User not found with name : " + name, HttpStatus.NOT_FOUND);
    }
  }
}

UserService.java

package com.example.accessingdatamysql.service;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;

@Service
public interface UserService {
  UserDto findFirstByName(String name);
  void create(UserDto user);
}

UserServiceImpl.java

package com.example.accessingdatamysql.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;

@Service
public class UserServiceImpl implements UserService {
  @Autowired
  private UserRepository userRepository;
  @Autowired
  UserMapper mapper;

  @Override
  public UserDto findFirstByName(String name) {
    UserEntity entity = userRepository.findFirstByName(name);
    return mapper.toDtoMapper(entity);
  }

  @Override
  public void create(UserDto user) {
    UserEntity entity = mapper.toEntityMapper(user);
    userRepository.create(entity);
  }
}

UserMapper.java

package com.example.accessingdatamysql.util;

import org.mapstruct.Mapper;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;

@Mapper(componentModel = "spring")
public interface UserMapper {
  UserEntity toEntityMapper (UserDto user);
  UserDto toDtoMapper (UserEntity userEntity);
}

UserRepository.java

package com.example.accessingdatamysql.repo;

import org.springframework.stereotype.Repository;
import com.example.accessingdatamysql.model.UserEntity;

@Repository
public interface UserRepository {
  UserEntity findFirstByName(String name);
  void create(UserEntity entity);
}

UserRepositoryImpl.java

package com.example.accessingdatamysql.service;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;

@Component
public class UserRepositoryImpl implements UserRepository {
  private final EntityManager em;
  
  public UserRepositoryImpl(EntityManager entityManager) {
    this.em = entityManager;
  }

  @Override
  public UserEntity findFirstByName(String name) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<UserEntity> criteria = builder.createQuery(UserEntity.class);
    Root<UserEntity> root = criteria.from(UserEntity.class);
    criteria.select(root).where(builder.equal(root.get("name"), name));
    criteria.orderBy(builder.asc(root.get("timestamp")));
    TypedQuery<UserEntity> query = em.createQuery(criteria).setMaxResults(1);
    return query.getSingleResult();
  }

  @Override
  public void create(UserEntity entity) {
    em.persist(entity);
  }
}

UserDto.java

package com.example.accessingdatamysql.model;

import java.io.Serializable;
import java.sql.Timestamp;

public class UserDto implements Serializable {
  private static final long serialVersionUID = -7621330660870602403L;
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Timestamp getTimestamp() {
    return timestamp;
  }

  public void setTimestamp(Timestamp timestamp) {
    this.timestamp = timestamp;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getSurname() {
    return surname;
  }

  public void setSurname(String surname) {
    this.surname = surname;
  }

  private Timestamp timestamp;
  private String email;
  private String surname;
}

请注意,代码中可能存在格式问题,因为我无法在纯文本环境中执行格式化。另外,翻译可能会导致代码格式略有不同。如果需要进一步的帮助,请随时提问。

英文:

I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this ERROR:

D:\&gt;curl -G  localhost:8080/demo/first?=Biagio
{&quot;timestamp&quot;:&quot;2020-10-04T22:46:35.996+00:00&quot;,&quot;status&quot;:404,&quot;error&quot;:&quot;Not Found&quot;,&quot;message&quot;:&quot;&quot;,&quot;path&quot;:&quot;/demo/first&quot;}

And to each of my POST / Add requests like this ERROR:

D:\&gt;curl localhost:8080/demo/add -d name=Giovanni -d email=giovanni@gmail.com -d surname=Jackie
{&quot;timestamp&quot;:&quot;2020-10-04T22:40:51.928+00:00&quot;,&quot;status&quot;:404,&quot;error&quot;:&quot;Not Found&quot;,&quot;message&quot;:&quot;&quot;,&quot;path&quot;:&quot;/demo/add&quot;}

Below I enter the interested parties of my project to try to get something out of it, because I have been stuck for days now

AccessingDataMysqlApplication.java

package com.example.accessingdatamysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
}

MainController.java

package com.example.accessingdatamysql.rest;
import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;
@RestController
@RequestMapping(&quot;/demo&quot;)
public class MainController {
@Autowired
private UserService userService;
@Transactional
//@RequestMapping(value = &quot;/add/&quot;, method = RequestMethod.POST)
@PostMapping(path=&quot;/demo/add&quot;)
public String addNewUser(@PathVariable(&quot;name&quot;) String name, @PathVariable(&quot;email&quot;) String email,
@PathVariable(&quot;surname&quot;) String surname) {
UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return &quot;User Saved in DB&quot;;
}
@SuppressWarnings({ &quot;rawtypes&quot;, &quot;unchecked&quot; })
//@RequestMapping(value = &quot;/fetchUser/{name}&quot;, method = RequestMethod.GET)
@GetMapping(&quot;/demo/first&quot;)
public ResponseEntity&lt;UserDto&gt; fetchUser(@PathVariable(&quot;name&quot;) String name) {
System.out.println(name);
try {
UserDto namefound = userService.findFirstByName(name);
System.out.println(&quot;Name found&quot;);
ResponseEntity&lt;UserDto&gt; user = new ResponseEntity&lt;UserDto&gt;(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println(&quot;User not found&quot;);
return new ResponseEntity(&quot;User not found with name : &quot; + name, HttpStatus.NOT_FOUND);
}
}
}

UserService.java

package com.example.accessingdatamysql.service;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
@Service
public interface UserService {
UserDto findFirstByName(String name);
void create(UserDto user);
}

UserServiceImpl.java

package com.example.accessingdatamysql.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
UserMapper mapper;
@Override
public UserDto findFirstByName(String name) {
UserEntity entity = userRepository.findFirstByName(name);
return mapper.toDtoMapper(entity);
}
@Override
public void create(UserDto user) {
UserEntity entity = mapper.toEntityMapper(user);
userRepository.create(entity);
}
}

UserMapper.java

package com.example.accessingdatamysql.util;
import org.mapstruct.Mapper;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
@Mapper(componentModel = &quot;spring&quot;)
public interface UserMapper {	
public UserEntity toEntityMapper (UserDto user);	
public UserDto toDtoMapper (UserEntity userEntity);
}

UserRepository.java

package com.example.accessingdatamysql.repo;
import org.springframework.stereotype.Repository;
import com.example.accessingdatamysql.model.UserEntity;
@Repository
public interface UserRepository {
UserEntity findFirstByName(String name);
void create(UserEntity entity);
}

UserRepositoryImpl.java

package com.example.accessingdatamysql.service;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
@Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
@Override
public UserEntity findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery&lt;UserEntity&gt; criteria = builder.createQuery(UserEntity.class);
Root&lt;UserEntity&gt; root = criteria.from(UserEntity.class);
criteria.select(root).where(builder.equal(root.get(&quot;name&quot;), name));
criteria.orderBy(builder.asc(root.get(&quot;timestamp&quot;)));
TypedQuery&lt;UserEntity&gt; query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
@Override
//	per la creazione//
public void create(UserEntity entity) {
em.persist(entity);
}
}

UserDto.java

package com.example.accessingdatamysql.model;
import java.io.Serializable;
import java.sql.Timestamp;
public class UserDto implements Serializable {
/**
* 
*/
private static final long serialVersionUID = -7621330660870602403L;
/**
* 
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
private Timestamp timestamp;
private String email;
private String surname;
}

If you need I can also insert User.java and the pom, but the pom has no problems as the dependencies are all correct.

答案1

得分: 4

你在GET和POST方法的路径描述中多了一个demo,你应该把它移除:

@GetMapping("/demo/first")

@PostMapping(path = "/demo/first")

应该改为:

@GetMapping("/first")

@PostMapping(path = "/first")

这是因为你在类级别的RequestMapping注解中已经定义了demo

英文:

You have an additional demo in your path descriptions for GET and POST methods, you should remove it:

@GetMapping(&quot;/demo/first&quot;)
@PostMapping(path = &quot;/demo/first&quot;)

It should be :

@GetMapping(&quot;/first&quot;)
@PostMapping(path = &quot;/first&quot;)

This because you have already defined demo in the RequestMapping annotation in the class level.

huangapple
  • 本文由 发表于 2020年10月5日 06:56:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64200645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定