首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何解决:“出现意外错误(type=Not Found,status=404)”

如何解决:“出现意外错误(type=Not Found,status=404)”
EN

Stack Overflow用户
提问于 2019-11-14 04:18:10
回答 4查看 1.8K关注 0票数 0

我正在使用这个控制器启动一个spring boot应用程序。

代码语言:javascript
运行
复制
@RestController
@RequestMapping({"/api"})
public class ProduitImmobilierController {

    Logger logger = LoggerFactory.getLogger(ProduitImmobilierController.class);

    @Autowired
    private ProduitImmobilierService produitImmobilierService;

    @RequestMapping(value = "/produitimmobilier/all/{pageSize}/{page}",
    method = RequestMethod.GET,
    produces = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE},
    consumes = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody List<ProduitImmobilierDTO> findAll(@PathVariable("pageSize") int pageSize, @PathVariable("page") int page){
        logger.info("CONTROLLER PRODUITIMMOBILIERSERVICE CA PASSE");
        return produitImmobilierService.findAll(pageSize, page);
    }

我检查应用程序是否正在监听端口8080我尝试在firefox上使用此URL访问此控制器

http://localhost:8080/api/produitimmobilier/all/5/1

我得到了这个错误

代码语言:javascript
运行
复制
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Nov 13 20:48:53 CET 2019
There was an unexpected error (type=Not Found, status=404).
No message available

这是项目树

我怎么解决它呢?

我添加了pom.xml

代码语言:javascript
运行
复制
<?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 https://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>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demoImmobilierBack</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demoImmobilierBack</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.hql</groupId>
            <artifactId>hibernate-hql-parser</artifactId>
            <version>1.5.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>   
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
<!--            <version>1.4.194</version> -->
        </dependency>   
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>       
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

当我使用以下url点击应用程序时:http://localhost:8080/api/produitimmobilier/all/5/1

代码语言:javascript
运行
复制
2019-11-14 12:20:58.770  INFO 2998 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-11-14 12:20:58.770  INFO 2998 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-11-14 12:20:58.787  INFO 2998 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 17 ms
EN

回答 4

Stack Overflow用户

发布于 2019-11-14 15:46:33

尝试:

代码语言:javascript
运行
复制
@RestController
@RequestMapping("/api")
    public class ProduitImmobilierController {
        ...
        ...
        ... 
    }
票数 0
EN

Stack Overflow用户

发布于 2019-11-15 04:38:16

我更改了包含main方法的类,添加了@ComponentScan,如下所示

代码语言:javascript
运行
复制
package com.example.demoImmobilierBack;

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

@SpringBootApplication
@ComponentScan({"com.example.demoImmobilierBack.service","com.example.demoImmobilierBack", "com.example.demoImmobilierBack.controller", "com.example.demoImmobilierBack.repository"})
public class DemoImmobilierBackApplication {

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

当我点击url时:

代码语言:javascript
运行
复制
http://localhost:8080/api/produitimmobilier/all/5/1

并且我收到了以下错误

代码语言:javascript
运行
复制
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Nov 14 21:11:26 CET 2019
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation

我读到了这篇关于错误406的文章

代码语言:javascript
运行
复制
The 406 Not Acceptable is an HTTP response status code indicating that the client has requested a response using Accept- headers that the server is unable to fulfill. This is typically a result of the user agent (i.e. browser) specifying an acceptable character set (via Accept-Charset), language (via Accept-Language), and so forth that should be responded with, and the server being unable to provide such a response.

我在firefox上工作,并尝试使用User-Agent Switcher更改用户代理,以获得正确的响应,即json响应,但没有成功

我有另一个问题。当我试图在我的应用程序中添加另一个具有另一个服务的控制器时,即

代码语言:javascript
运行
复制
package com.example.demoImmobilierBack.controller;

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

import com.example.demoImmobilierBack.dto.UserDTO;
import com.example.demoImmobilierBack.dto.UserDTOWithMesssage;
import com.example.demoImmobilierBack.service.UserService;

@RestController
@RequestMapping({"/api/user"})
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login",
    method = RequestMethod.POST,
    produces = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE},
    consumes = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody UserDTOWithMesssage login(@RequestBody UserDTO userDTO){
        UserDTOWithMesssage userDTOWithMesssage = new UserDTOWithMesssage();
        String message = userService.checkIfUserExistsAndGoodCredential(userDTO);
        if (message.isEmpty()) {
            userDTO = userService.findByEmailAndPassword(userDTO.getEmail(), userDTO.getPassword());
            userDTO.setPassword("");
        } else {
            userDTOWithMesssage.setMessage(message);
        }
        return userDTOWithMesssage;
    }

    @RequestMapping(value = "/save",
    method = RequestMethod.POST,
    produces = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE},
    consumes = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody UserDTOWithMesssage save(@RequestBody UserDTO userDTO){
        UserDTOWithMesssage userDTOWithMesssage = new UserDTOWithMesssage();
        String message = userService.checkEmailAndPasswordAndPasswordConfirm(userDTO);
        if (message.isEmpty()) {
            UserDTO userDTOSaved = userService.save(userDTO);
            userDTOWithMesssage.setUserDTO(userDTOSaved);
            userDTOWithMesssage.setMessage(message);
        } else {
            userDTOWithMesssage.setUserDTO(userDTO);
            userDTOWithMesssage.setMessage("");         
        }
        return userDTOWithMesssage;
    }
}

当我启动应用程序时,我得到了以下错误,就好像无法扫描UserService一样

代码语言:javascript
运行
复制
***************************
APPLICATION FAILED TO START
***************************

Description:

Field userService in com.example.demoImmobilierBack.controller.UserController required a bean of type 'com.example.demoImmobilierBack.service.UserService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.example.demoImmobilierBack.service.UserService' in your configuration.

下面是树形层次结构

票数 0
EN

Stack Overflow用户

发布于 2019-11-16 17:15:35

是的,实际上,当我输入以下内容时,它是有效的

@SpringBootApplication(scanBasePackages = "com.example.demoImmobilierBack")

但我仍然对UserService有意见。这就是界面

代码语言:javascript
运行
复制
package com.example.demoImmobilierBack.service;

import com.example.demoImmobilierBack.dto.UserDTO;
import com.example.demoImmobilierBack.model.User;

public interface UserService {

    UserDTO findByEmailAndPassword(String email, String password);

    UserDTO save(UserDTO userDTO);

    String checkIfUserExistsAndGoodCredential(UserDTO userDTO);

    UserDTO convertUserToUserDTO(User user);

    User convertUserDTOToUser(UserDTO userDTO);

    String checkEmailAndPasswordAndPasswordConfirm(UserDTO userDTO);
}

下面是实现

代码语言:javascript
运行
复制
package com.example.demoImmobilierBack.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;

import com.example.demoImmobilierBack.dto.ProduitImmobilierDTO;
import com.example.demoImmobilierBack.dto.UserDTO;
import com.example.demoImmobilierBack.model.ProduitImmobilier;
import com.example.demoImmobilierBack.model.User;
import com.example.demoImmobilierBack.repository.ProduitImmobilierRepository;
import com.example.demoImmobilierBack.repository.UserRepository;

public class UserServiceImpl implements UserService{

    public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
            Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

    public static final Pattern VALID_PASSWORD_REGEX = 
            Pattern.compile("(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&].{8,}");

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ProduitImmobilierService produitImmobilierService;

    public UserDTO findByEmailAndPassword(String email, String password) {
        User user = userRepository.findByEmailAndPassword(email, password);
        return convertUserToUserDTO(user);
    }

    public UserDTO save(UserDTO userDTO) {
        User user = userRepository.save(convertUserDTOToUser(userDTO));
        return convertUserToUserDTO(user);
    }

    public String checkEmailAndPasswordAndPasswordConfirm(UserDTO userDTO) {
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(userDTO.getEmail());
        if (!matcher.find()) {
            return "L'email que vous avez fourni: " + userDTO.getEmail() + " n'est pas valide";
        }
        User user = userRepository.findByEmail(userDTO.getEmail());
        if (user != null) {
            return "L'utilisateur avec l'email suivant " + userDTO.getEmail() + " existe déjà";
        }
        matcher = VALID_PASSWORD_REGEX .matcher(userDTO.getPassword());
        if (!matcher.find()) {
            return "Le mot de passe que vous avez fourni: " + userDTO.getPassword() + " n'est pas valide. Il doit contenir au moins 8 caractères, un caractère minuscule, un caractère majuscule, un chiffre et un caractère spécial.";
        }
        if (!userDTO.getPassword().equals(userDTO.getPasswordConfirm())) {
            return "Le mot de passe que vous avez fourni: " + userDTO.getPassword() + " ne correspond pas à la confirmation du mot de passe  " + userDTO.getPasswordConfirm();
        }
        return "";
    }

    public String checkIfUserExistsAndGoodCredential(UserDTO userDTO) {
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(userDTO.getEmail());
        if (!matcher.find()) {
            return "L'email que vous avez fourni: " + userDTO.getEmail() + " n'est pas valide";
        }
        User user = userRepository.findByEmail(userDTO.getEmail());
        if (user == null) {
            return "L'utilisateur avec l'email suivant " + userDTO.getEmail() + " n'existe pas";
        }
        matcher = VALID_PASSWORD_REGEX .matcher(userDTO.getPassword());
        if (!matcher.find()) {
            return "Le mot de passe que vous avez fourni: " + userDTO.getPassword() + " n'est pas valide. Il doit contenir au moins 8 caractères, un caractère minuscule, un caractère majuscule, un chiffre et un caractère spécial.";
        }
        user = userRepository.findByEmailAndPassword(userDTO.getEmail(), userDTO.getPassword());
        if (user == null) {
            return "L'utilisateur avec l'email suivant " + userDTO.getEmail() + " et le mot de passe suivant " + userDTO.getPassword() + "n'existe pas";
        }   
        return "";
    }

    public UserDTO convertUserToUserDTO(User user) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setGender(user.getGender());
        userDTO.setLastName(user.getLastName());
        userDTO.setEmail(user.getEmail());
        userDTO.setPassword(user.getPassword());
        userDTO.setMobileTelephone(user.getFixedTelephone());
        userDTO.setFixedTelephone(user.getFixedTelephone());
        userDTO.setAdress(user.getAdress());
        userDTO.setPostalCode(user.getPostalCode());
        userDTO.setTown(user.getTown());
        userDTO.setProfession(user.getProfession());
        userDTO.setProfile(user.getProfile());
        userDTO.setMaritalSituation(user.getMaritalSituation());
        userDTO.setChildrenNumber(user.getChildrenNumber());
        userDTO.setDependant(user.getDependant());
        userDTO.setOwnedOrRentedAccommodation(user.getOwnedOrRentedAccommodation());
        userDTO.setMonthlyNetSalary(user.getMonthlyNetSalary());
        userDTO.setRentAmount(user.getRentAmount());
        userDTO.setIsBankLoan(user.getIsBankLoan());
        userDTO.setCapitalContribution(user.getCapitalContribution());
        userDTO.setCreditAmount(user.getCreditAmount());
        userDTO.setMonthlyPayment(user.getMonthlyPayment());
        userDTO.setCreditTerminationDate(user.getCreditTerminationDate());
        userDTO.setSIRETNumber(user.getSIRETNumber());

        Set<ProduitImmobilier> setProduitImmobiliers = user.getRealEstateProperty();
        List<ProduitImmobilierDTO> setProduitImmobilierDTOs = new ArrayList<>();

        setProduitImmobiliers.forEach(p ->{ ProduitImmobilierDTO pDTO = produitImmobilierService.convertProduitImmobilierToProduitImmobilierDTO(p, setProduitImmobiliers.size()); setProduitImmobilierDTOs.add(pDTO);});

        Comparator<ProduitImmobilierDTO> compareByIdDesc = new Comparator<ProduitImmobilierDTO>() {
            @Override
            public int compare(ProduitImmobilierDTO o1, ProduitImmobilierDTO o2) {
                return o2.getId().compareTo(o1.getId());
            }
        };
        Collections.sort(setProduitImmobilierDTOs, compareByIdDesc);
        userDTO.setRealEstateProperty(setProduitImmobilierDTOs);
        return userDTO;
    }

    public User convertUserDTOToUser(UserDTO userDTO) {
        User user = new User();
        user.setId(userDTO.getId());
        user.setGender(userDTO.getGender());
        user.setLastName(userDTO.getLastName());
        user.setEmail(userDTO.getEmail());
        user.setPassword(userDTO.getPassword());
        user.setMobileTelephone(userDTO.getFixedTelephone());
        user.setFixedTelephone(userDTO.getFixedTelephone());
        user.setAdress(userDTO.getAdress());
        user.setPostalCode(userDTO.getPostalCode());
        user.setTown(userDTO.getTown());
        user.setProfession(userDTO.getProfession());
        user.setProfile(userDTO.getProfile());
        user.setMaritalSituation(userDTO.getMaritalSituation());
        user.setChildrenNumber(userDTO.getChildrenNumber());
        user.setDependant(userDTO.getDependant());
        user.setOwnedOrRentedAccommodation(userDTO.getOwnedOrRentedAccommodation());
        user.setMonthlyNetSalary(userDTO.getMonthlyNetSalary());
        user.setRentAmount(userDTO.getRentAmount());
        user.setIsBankLoan((userDTO.getIsBankLoan().equals(new Byte((byte) 0))) ? false : userDTO.getIsBankLoan().equals(new Byte((byte) 1)) ? true : null  );
        user.setCapitalContribution(userDTO.getCapitalContribution());
        user.setCreditAmount(userDTO.getCreditAmount());
        user.setMonthlyPayment(userDTO.getMonthlyPayment());
        user.setCreditTerminationDate(new Date(userDTO.getCreditTerminationDate()));
        user.setSIRETNumber(userDTO.getSIRETNumber());
        return user;
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58844957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档