Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringREST-没有json结果,只显示404错误_Java_Spring_Rest - Fatal编程技术网

Java SpringREST-没有json结果,只显示404错误

Java SpringREST-没有json结果,只显示404错误,java,spring,rest,Java,Spring,Rest,在测试rest URL是否正常工作时,只有404错误显示..需要将数据插入数据库,但显示“请求失败”消息 控制器 package com.astu.controller; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.s

在测试rest URL是否正常工作时,只有404错误显示..需要将数据插入数据库,但显示“请求失败”消息

控制器

    package com.astu.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.astu.model.UserRelationship;
import com.astu.model.User;
import com.astu.modelVO.UserDetails;
import com.astu.modelVO.UserRegistration;
import com.astu.services.UserService;
import com.astu.utils.Result;

@RestController
public class UserRestController {

    @Autowired
    private UserService userService;

    private Result result;

    @SuppressWarnings("unused")
    private final static Logger LOGGER = Logger
            .getLogger(UserRestController.class.getName());

    // @RequestMapping("/hello/{player}")
    // public UserDeatils message(@PathVariable String player) {
    //
    // UserDeatils msg = new UserDeatils();
    // msg.setUsername("test");
    // msg.setPassword("test");
    // return msg;
    // }

    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
    public Result getUsers() {
        List<User> users = new ArrayList<User>();
        result = new Result();
        try {
            users = userService.getAllUsers();
            result.setErrorcode(200);
            result.setStatus("ok");
            result.setMessage("done");
            result.setObj(users);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // @RequestMapping("/getUsername/{name}")
    // public String getUsername (@PathVariable String name)
    // {
    // String value = null;
    // value = userDAO.getUsername(name);
    // return value;
    // }

    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public Result getAuthentication(@RequestBody UserDetails user) {
        result = new Result();
        try {
            if (userService.getAuthentication(user)) {
                result.setObj(true);
            } else
                result.setObj(false);
            result.setErrorcode(200);
            result.setStatus("OK");
            result.setMessage("done");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result registerUser(@RequestBody User user) {
        result = new Result();
        try {
            if (user.getRole().getRoleId() == 3 ) {
                user = userService.registerUser(user);
                result.setObj(user.getAccessKey());
                result.setMessage("done");
                result.setErrorcode(200);
                result.setStatus("ok");
            } else {
                result.setErrorcode(201);
                result.setStatus("Unauthorised User...!");
                result.setMessage("You dont have rights to perform this operation");
                result.setObj(null);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/getRelationship")
    public Result getRelationship() {
        result = new Result();
        List<UserRelationship> rel = new ArrayList<UserRelationship>();
        try {
            rel = userService.getRelationShip();
            result.setErrorcode(200);
            result.setStatus("ok");
            result.setMessage("done");
            result.setObj(rel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

//  @RequestMapping(value = "/addDependency", method = RequestMethod.POST)
//  public Result addDependency(@RequestBody List<UserRelationship> rel) {
//      result = new Result();
//      try {
//          if (userService.addDependency(rel)) {
//              result.setObj(true);
//              result.setMessage("done");
//          } else {
//              result.setObj(false);
//              result.setMessage("Something went wrong please try after sometime");
//          }
//          result.setErrorcode(200);
//          result.setStatus("ok");
//
//      } catch (Exception e) {
//          e.printStackTrace();
//      }
//      return result;
//  }

    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public Result registerParentOrDependent(@RequestBody UserRegistration user, @RequestHeader("access-key") String key) {
        result = new Result();
        try {
            if (key != null && !key.isEmpty())
            {   
                if (userService.authenticateKey(key))
                {
                    userService.registerParentOrDependent(user);
                    result.setObj(true);
                    result.setMessage("done");
                    result.setErrorcode(200);
                    result.setStatus("ok");
                }
                else
                {
                    result.setMessage("Unauthorised User");
                    result.setErrorcode(201);
                    result.setStatus("failed");
                    result.setObj("failed");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
a初始化

package com.astu.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;


import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class AstuInitialization implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

         AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
            ctx.register(AstuConfiguration.class);
            ctx.setServletContext(container);

            ServletRegistration.Dynamic servlet = container.addServlet(
                    "dispatcher", new DispatcherServlet(ctx));

            servlet.setLoadOnStartup(1);
            servlet.addMapping("/");

            container.addListener(new ContextLoaderListener(ctx));
    }

}
下面是

application.properties

#Hibernate Configuration
#hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.format_sql=true
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sql=true

#MessageSource
message.source.basename=i18n/messages
message.source.use.code.as.default.message=true

#EntityManager
#Declares the base package of the entity classes
entitymanager.packages.to.scan=com.astu.model
我很感激你对这个问题的关心,你还需要看什么请告诉我

注册文件-HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <!-- Title and other stuffs -->
  <title>Register - MacAdmin</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="author" content="">

  <!-- Stylesheets -->
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="css/font-awesome.min.css">
  <link href="css/style.css" rel="stylesheet">

  <script src="js/respond.min.js"></script>
  <!--[if lt IE 9]>
  <script src="js/html5shiv.js"></script>
  <![endif]-->


</head>

<body>

<div class="admin-form">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <!-- Widget starts -->
            <div class="widget wred">
              <div class="widget-head">
                <i class="fa fa-lock"></i> Register 
              </div>
              <div class="widget-content">
                <div class="padd">

                  <form class="form-horizontal">
                    <!-- Registration form starts -->
                                    <!--First  Name -->
                                        <div class="form-group">
                                            <label class="control-label col-lg-3" for="name">First Name</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="firstname">
                                            </div>
                                          </div> 
                                      <!--Last Name -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="name">Last Name</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="lastname">
                                            </div>
                                          </div>   
                                          <!-- Email -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="email">Email</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="email">
                                            </div>
                                          </div>
                                          <!-- Select box -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3">Role Type</label>
                                            <div class="col-lg-4">                               
                                                <select id="role" class="form-control">
                                                <option>&nbsp;</option>
                                              <option value = "1">PARENT</option>
<!--                                            <option value = "2">DEPENDENT</option> -->
                                                    <option value = "3">DEVELOPER</option>
                                                </select>  
                                            </div>
                                          </div>                                           
                                          <!-- Username -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="username">Username</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="username">
                                            </div>
                                          </div>
                                          <!-- Password -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="email">Password</label>
                                            <div class="col-lg-9">
                                              <input type="password" class="form-control" id="password">
                                            </div>
                                          </div>
                                          <!-- Accept box and button s-->
                                          <div class="form-group">
                                            <div class="col-lg-9 col-lg-offset-3">
                                              <div class="checkbox">
                                              <label>
                                                <input type="checkbox"> Accept Terms &amp; Conditions
                                              </label>
                                              </div>
                                              <br />
                                              <button type="button" id="register-dev" class="btn btn-sm btn-info">Register</button>
                                              <button type="reset" class="btn btn-sm btn-default">Reset</button>
                                            </div>
                                          </div>
                  </form>

                </div>
              </div>
                <div class="widget-foot">
                  Already Registred? <a href="login.html">Login</a>
                </div>
            </div>  
      </div>
    </div>
  </div> 
</div>



<!-- JS -->
<script src="js/jquery.js"></script>
<script src="js/ajax-handler.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

尝试使用
http://localhost:///getUsers
我对url使用相同的模式,但没有运行rest服务…请显示您的组件扫描部分。你是如何让spring知道你的控制器的?你的控制器包被扫描了吗?我无法弄清楚,可能是因为我对spring的东西不熟悉,我怀疑它没有,否则它会让所有其余的URL工作..你能帮我找到一个解决方案如何完成。。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <!-- Title and other stuffs -->
  <title>Register - MacAdmin</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="author" content="">

  <!-- Stylesheets -->
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="css/font-awesome.min.css">
  <link href="css/style.css" rel="stylesheet">

  <script src="js/respond.min.js"></script>
  <!--[if lt IE 9]>
  <script src="js/html5shiv.js"></script>
  <![endif]-->


</head>

<body>

<div class="admin-form">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <!-- Widget starts -->
            <div class="widget wred">
              <div class="widget-head">
                <i class="fa fa-lock"></i> Register 
              </div>
              <div class="widget-content">
                <div class="padd">

                  <form class="form-horizontal">
                    <!-- Registration form starts -->
                                    <!--First  Name -->
                                        <div class="form-group">
                                            <label class="control-label col-lg-3" for="name">First Name</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="firstname">
                                            </div>
                                          </div> 
                                      <!--Last Name -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="name">Last Name</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="lastname">
                                            </div>
                                          </div>   
                                          <!-- Email -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="email">Email</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="email">
                                            </div>
                                          </div>
                                          <!-- Select box -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3">Role Type</label>
                                            <div class="col-lg-4">                               
                                                <select id="role" class="form-control">
                                                <option>&nbsp;</option>
                                              <option value = "1">PARENT</option>
<!--                                            <option value = "2">DEPENDENT</option> -->
                                                    <option value = "3">DEVELOPER</option>
                                                </select>  
                                            </div>
                                          </div>                                           
                                          <!-- Username -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="username">Username</label>
                                            <div class="col-lg-9">
                                              <input type="text" class="form-control" id="username">
                                            </div>
                                          </div>
                                          <!-- Password -->
                                          <div class="form-group">
                                            <label class="control-label col-lg-3" for="email">Password</label>
                                            <div class="col-lg-9">
                                              <input type="password" class="form-control" id="password">
                                            </div>
                                          </div>
                                          <!-- Accept box and button s-->
                                          <div class="form-group">
                                            <div class="col-lg-9 col-lg-offset-3">
                                              <div class="checkbox">
                                              <label>
                                                <input type="checkbox"> Accept Terms &amp; Conditions
                                              </label>
                                              </div>
                                              <br />
                                              <button type="button" id="register-dev" class="btn btn-sm btn-info">Register</button>
                                              <button type="reset" class="btn btn-sm btn-default">Reset</button>
                                            </div>
                                          </div>
                  </form>

                </div>
              </div>
                <div class="widget-foot">
                  Already Registred? <a href="login.html">Login</a>
                </div>
            </div>  
      </div>
    </div>
  </div> 
</div>



<!-- JS -->
<script src="js/jquery.js"></script>
<script src="js/ajax-handler.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
package com.astu.model;
// Generated 2 Feb, 2015 8:13:24 PM by Hibernate Tools 4.3.1

import static javax.persistence.GenerationType.IDENTITY;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

/**
 * UserTb generated by hbm2java
 */
@Entity
@Table(name = "user_tb", catalog = "astu", uniqueConstraints = {
        @UniqueConstraint(columnNames = "email_id"),
        @UniqueConstraint(columnNames = "username"),
        @UniqueConstraint(columnNames = "access_key")})
public class User implements java.io.Serializable {

    private Integer userId;
    private Role role;
    private String firstName;
    private String lastName;
    private String emailId;
    private String username;
    private String password;
    private Date createdDate;
    private Integer status;
    private String accessKey;
    private Set<UserRelationship> userRelationshipTbsForFkRelParentId = new HashSet<UserRelationship>(
            0);
    private Set<UserRelationship> userRelationshipTbsForFkRelDependentId = new HashSet<UserRelationship>(
            0);

    public User() {
    }

    public User(Role role, String firstName, String emailId,
            String username, String password, Date createdDate) {
        this.role = role;
        this.firstName = firstName;
        this.emailId = emailId;
        this.username = username;
        this.password = password;
        this.createdDate = createdDate;
    }

    public User(Role role, String firstName, String lastName,
            String emailId, String username, String password, Date createdDate,
            Integer status, String accesskey,
            Set<UserRelationship> userRelationshipTbsForFkRelParentId,
            Set<UserRelationship> userRelationshipTbsForFkRelDependentId) {
        this.role = role;
        this.firstName = firstName;
        this.lastName = lastName;
        this.emailId = emailId;
        this.username = username;
        this.password = password;
        this.createdDate = createdDate;
        this.status = status;
        this.accessKey = accesskey;
        this.userRelationshipTbsForFkRelParentId = userRelationshipTbsForFkRelParentId;
        this.userRelationshipTbsForFkRelDependentId = userRelationshipTbsForFkRelDependentId;
    }

    @Column(name = "access_key", unique = true, length = 45)
    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "user_id", unique = true, nullable = false)
    public Integer getUserId() {
        return this.userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    @ManyToOne
    @JoinColumn(name = "fk_role_id", nullable = false)
    @Fetch(FetchMode.JOIN)
    public Role getRole() {
        return this.role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    @Column(name = "first_name", nullable = false, length = 30)
    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Column(name = "last_name", length = 25)
    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Column(name = "email_id", unique = true, nullable = false, length = 65)
    public String getEmailId() {
        return this.emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    @Column(name = "username", unique = true, nullable = false, length = 45)
    public String getUsername() {
        return this.username;
    }

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

    @Column(name = "password", nullable = false, length = 100)
    public String getPassword() {
        return this.password;
    }

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

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_date",  length = 19)
    public Date getCreatedDate() {
        return this.createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    @Column(name = "status")
    public Integer getStatus() {
        return this.status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

//  @OneToMany(mappedBy = "userTbByFkRelParentId")
//  @Fetch(FetchMode.JOIN)
//  public Set<UserRelationship> getUserRelationshipTbsForFkRelParentId() {
//      return this.userRelationshipTbsForFkRelParentId;
//  }

    public void setUserRelationshipTbsForFkRelParentId(
            Set<UserRelationship> userRelationshipTbsForFkRelParentId) {
        this.userRelationshipTbsForFkRelParentId = userRelationshipTbsForFkRelParentId;
    }

//  @OneToMany(mappedBy = "userTbByFkRelDependentId")
//  @Fetch(FetchMode.JOIN)
//  public Set<UserRelationship> getUserRelationshipTbsForFkRelDependentId() {
//      return this.userRelationshipTbsForFkRelDependentId;
//  }

    public void setUserRelationshipTbsForFkRelDependentId(
            Set<UserRelationship> userRelationshipTbsForFkRelDependentId) {
        this.userRelationshipTbsForFkRelDependentId = userRelationshipTbsForFkRelDependentId;
    }


}
@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public Result registerParentOrDependent(@RequestBody UserRegistration user, @RequestHeader("access-key") String key) {
        result = new Result();
        try {
            if (key != null && !key.isEmpty())
            {   
                if (userService.authenticateKey(key))
                {
                    userService.registerParentOrDependent(user);
                    result.setObj(true);
                    result.setMessage("done");
                    result.setErrorcode(200);
                    result.setStatus("ok");
                }
                else
                {
                    result.setMessage("Unauthorised User");
                    result.setErrorcode(201);
                    result.setStatus("failed");
                    result.setObj("failed");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }