Spring rest - 没有json结果,只显示404错误

时间:2015-02-15 00:17:16

标签: java spring rest

有些人可以通过以下代码查看我做错了什么来帮助我,在测试其他网址是否正常工作时,只显示404错误..需要将数据插入数据库但显示&的消息#39;请求失败' ..

控制器

    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;
    }

}

AstuConfiguration.java

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.astu")
    @ImportResource("classpath:applicationContext.xml")
    @PropertySource("classpath:application.properties")
    public class AstueConfiguration {

    private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";
    private static final String VIEW_RESOLVER_SUFFIX = ".jsp";

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

    private static final String PROPERTY_NAME_MESSAGESOURCE_BASENAME = "message.source.basename";
    private static final String PROPERTY_NAME_MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE = "message.source.use.code.as.default.message";

    @Resource
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        BoneCPDataSource dataSource = new BoneCPDataSource();

        dataSource.setDriverClass(environment
                .getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setJdbcUrl(environment
                .getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(environment
                .getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(environment
                .getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public JpaTransactionManager transactionManager()
            throws ClassNotFoundException {
        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setEntityManagerFactory(entityManagerFactoryBean()
                .getObject());

        return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
            throws ClassNotFoundException {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean
                .setPackagesToScan(environment
                        .getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        entityManagerFactoryBean
                .setPersistenceProviderClass(HibernatePersistence.class);

        Properties jpaProterties = new Properties();
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment
                .getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment
                .getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment
                .getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
        jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment
                .getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

        entityManagerFactoryBean.setJpaProperties(jpaProterties);

        return entityManagerFactoryBean;
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        messageSource.setBasename(environment
                .getRequiredProperty(PROPERTY_NAME_MESSAGESOURCE_BASENAME));
        messageSource
                .setUseCodeAsDefaultMessage(Boolean.parseBoolean(environment
                        .getRequiredProperty(PROPERTY_NAME_MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE)));

        return messageSource;
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
        viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);

        return viewResolver;
    }

    @Bean
    public Helper helper() {
        Helper helper = new Helper();
        return helper;
    }
}

AstuInitialization

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>

User.java

我认为参数是匹配的但是m发布用户要由你评估,以防万一丢失的东西..

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;
    }


}

@RequestBody

for rest url / registerUser

@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;
    }

0 个答案:

没有答案