0

我在弹簧控制器中有休息方法,如下所示:

@RequestMapping(value="/register/{userName}" ,method=RequestMethod.GET)
@ResponseBody
public String getUserName(HttpServletRequest request,@PathVariable String userName ){
    System.out.println("User Name : "+userName);
    return "available";

}

在 jquery 中,我编写了 ajax 调用,例如:

$(document).ready(function(){

        $('#userName').blur(function(){
            var methodURL = "http://localhost:8085/ums/register/"+$('#userName').val();

            $.ajax({
                type : "get",
                URL : methodURL,
                data : $('#userName').val(),
                success : function(data){
                    alert(data);
                    $('#available').show();
                    }
                })
            });
});

在 web.xml 我有:

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

在 spring-servlet.xml 我有如下视图解析器:

<context:component-scan base-package="com.users.controller" />
    <context:annotation-config />
        <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<!-- <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />-->
<property name="defaultContentType" value="text/html" />
</bean>
<bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2" />
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

当我在服务器中运行它时,它不会进入控制器。请让我知道此代码的问题。

请任何人对此提供帮助。

问候, 施鲁蒂

4

3 回答 3

1

由于您的方法定义中有 @RequestMapping(value="register/{userName}" ,因此您的 jquery 调用必须遵循相同的语法。

var methodURL = "http://localhost:8085/users/register/"+$('#userName').val()+".html";

但是您的 RequestMapping 值也有问题,它应该以 / 开头

@RequestMapping(value="/register/{userName}"

我也怀疑你最后需要“.html”

于 2013-04-15T14:07:41.423 回答
0

将此行添加到您的 spring-servlet.xml。它将启用 Web MVC 特定的注释,例如@Controller@RequestMapping

<mvc:annotation-driven />

带注释的控制器示例

假设带有上下文的 url 是http://localhost:8080/webapp并且您想要一个像 url 这样的 api 调用/users/register/johnDoe。(johnDoe 是用户名)

您的控制器类将如下所示。

@Controller
@RequestMapping(value="/users")
class UserController {

@ResponseBody
@RequestMapping(value="/register/{username}", method=RequestMethod.GET)
    public String registerUser(@PathVariable String username) {
        return username;
    }
}
于 2013-04-17T05:59:26.547 回答
0

请找到我在 Spring Framework 中调用 REST Web 服务的解决方案。

    /**
     * REST API Implementation Using REST Controller
     * */
    @RestController
    public class RestReqCntrl {

        @Autowired
        private UserService userService;    

        @Autowired
        private PayrollService payrollService;  


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

        @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
        public ResponseEntity<User> registerUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) throws Exception {
            System.out.println("Creating User " + user.getFirstName());

            boolean flag = userService.registerUser(user);

             if (flag)
             {
                 user.setStatusCode(1);
                 user.setStatusDesc("PASS");
             }else{
                 user.setStatusCode(0);
                 user.setStatusDesc("FAIL");

             }

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

        //-------------------Authenticating the User--------------------------------------------------------

        @RequestMapping(value = "/authuser", method = RequestMethod.POST)
        public ResponseEntity<User> authuser(@RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
            System.out.println("Creating User " + user.getFirstName());

            boolean flag = userService.authUser(user);

             if (flag)
             {
                 user.setStatusCode(1);
                 user.setStatusDesc("PASS");
             }else{
                 user.setStatusCode(0);
                 user.setStatusDesc("FAIL");

             }

            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
            return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
        }   

        //-------------------Create a Company--------------------------------------------------------
        @RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
        public ResponseEntity<String> registerCompany(@RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
            System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
            String result ="";
            boolean flag = payrollService.registerCompany(comypanyDTO);

             if (flag)
             {
                 result="Pass";
             }else{
                 result="Fail";

             }

            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
            return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
        }   


        //-------------------Create a Employee--------------------------------------------------------
        @RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
        public ResponseEntity<String> registerEmployee(@RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
            System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
            String result ="";
            boolean flag = payrollService.registerEmpbyComp(employeeDTO);

             if (flag)
             {
                 result="Pass";
             }else{
                 result="Fail";

             }

            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
            return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
        }   

        //-------------------Get Company Deatils--------------------------------------------------------
        @RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
        public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
            System.out.println("getCompanies getCompanies ");
            List<ComypanyDTO> comypanyDTOs =null;
            comypanyDTOs = payrollService.getCompanies();
            //Setting the Respective Employees
            for(ComypanyDTO dto :comypanyDTOs){

                dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
            return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
        }   
    }

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="USER_TABLE")
public class User implements Serializable {

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String firstName;
    private String lastName;
    private String email;
    private String userId;
    private String password;
    private String userType;
    private String address;
    @Transient
    private int statusCode;
    @Transient
    private String statusDesc;


    public User(){

    }

    public User(String firstName, String lastName, String email, String userId, String password, String userType,
            String address) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.userId = userId;
        this.password = password;
        this.userType = userType;
        this.address = address;
    }

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

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

    public String getEmail() {
        return email;
    }

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

    public String getUserId() {
        return userId;
    }

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

    public String getPassword() {
        return password;
    }

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


    /**
     * @return the userType
     */
    public String getUserType() {
        return userType;
    }


    /**
     * @param userType the userType to set
     */
    public void setUserType(String userType) {
        this.userType = userType;
    }


    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }


    /**
     * @param address the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * @return the statusCode
     */
    public int getStatusCode() {
        return statusCode;
    }

    /**
     * @param statusCode the statusCode to set
     */
    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    /**
     * @return the statusDesc
     */
    public String getStatusDesc() {
        return statusDesc;
    }

    /**
     * @param statusDesc the statusDesc to set
     */
    public void setStatusDesc(String statusDesc) {
        this.statusDesc = statusDesc;
    }        
}
于 2015-12-07T19:56:55.410 回答