简体   繁体   中英

Spring Java Web: REST API

I have a problem posting Data to Spring Rest Application from PostMan. Whenever send data I get this error (HTTP Status 404: The requested resource is not available.[ **邮递员** ] [1] )

There is no indication that there is an error in my code from the console. So I do not understand why I still cannot post the data. I have Rechecked everything

controller

    @Controller
public class CommerceController {

    private static final Logger logger = LoggerFactory.getLogger(CommerceController.class);
    private ProductService productService;

    private UserService userService;

    @Autowired
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }
    /*//Map to store the product but later use database
    Map<Integer, Product>prodData= new HashMap<Integer, Product>();*/

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
    public
    @ResponseBody
    List home() {
        System.out.println("This is the usermodel check it out: "+"Get REQUEST");
        productService.runtest();
        return productService.allProducts();
    }


    @RequestMapping("/products")
    public List getProducts() {
        productService.runtest();
        return productService.allProducts();
    }



    //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.POST, headers = "Content-Type:application/x-www-form-urlencoded")
    public  ResponseEntity<Void> createUser(@RequestBody UserModel user, UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getName());

        if (userService.isExist(user.getUsername())) {
            System.out.println("A User with name " + user.getName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        userService.createUser(user);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }



    /*public @ResponseBody Product home(){
        logger.info("Starting getDammyProduct");
        product.setName("SAMSUNG TV");
        product.setId(1);
        product.setCreatedDate(new Date());

        return product;

    }*/
}

enter code here

My web.xml

</welcome-file-list>
  <servlet>
    <description></description>
    <display-name>commerce</display-name>
    <servlet-name>commerce</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>commerce</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
 <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Calling the context listeners -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        classpath:com/javasoft/beans/config/dao-context.xml
        classpath:com/javasoft/beans/config/security-context.xml
        classpath:com/javasoft/beans/config/service-context.xml
        </param-value>
    </context-param>


</web-app>

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>
  <groupId>com.javasoft.smartshoppers</groupId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <artifactId>Commerce</artifactId>
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.6</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.9.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>4.1.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.webflow</groupId>
        <artifactId>spring-webflow</artifactId>
        <version>2.4.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.3.3.RELEASE</version>
    </dependency>
  </dependencies>

</project>

UserModel

    @Document(collection = "users")
public class UserModel implements UserDetails, Serializable {
    @Id
    private String id;

    private String name;

    private String username;
    private String password;
    private String email;


    /*Spring Security UserDetails*/
    private List<Role> authorities;
    private boolean accountNonExpired = true;
    private boolean accountNonLocked = true;
    private boolean credentialsNonExpired = true;
    private boolean enable = false;

/*Empty constructor*/
    public UserModel() {
    }
    /*Constructor with fields */

    public UserModel(String name, String username, String password, String email, List<Role> authorities, boolean accountNonExpired, boolean accountNonLocked, boolean credentialsNonExpired, boolean enable) {
        this.name = name;
        this.username = username;
        this.password = password;
        this.email = email;
        this.authorities = authorities;
        this.accountNonExpired = accountNonExpired;
        this.accountNonLocked = accountNonLocked;
        this.credentialsNonExpired = credentialsNonExpired;
        this.enable = enable;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

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

    @Override
    public List<Role> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(List<Role> authorities) {
        this.authorities = authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    public void setAccountNonExpired(boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    public void setAccountNonLocked(boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }


    public void setCredentialsNonExpired(boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }



    public void setEnable(boolean enable) {
        this.enable = enable;
    }
    @Override
    public boolean isEnabled() {
        return enable;
    }

}

The Get request are successful however While posting I getting 404 error. I have logged the post method and I have cornfirmed that its is not bieng called. Could someone kindly point out where I may be doing it all wrong or have omitted something ?

try to change

@RequestMapping(value = "/user/", method = RequestMethod.POST, headers = "Content-Type:application/x-www-form-urlencoded")

to

@RequestMapping(value = "/user", method = RequestMethod.POST, headers = "Content-Type:application/x-www-form-urlencoded")

or set

<servlet-mapping>
    <servlet-name>commerce</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

to

<servlet-mapping>
    <servlet-name>commerce</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
  1. The URL is case sensitive. Since what you have in your web.xml is lower case commerce , then that is what should be in your URL.

  2. You should also drop the trailing slash on users as others have said.

  3. If the error persists, you can open the application home page from tomcat or your IDE to be sure what format your URL is supposed to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM