0

I am having rest method in spring controller like below:

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

}

In jquery I have writeen ajax call like:

$(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();
                    }
                })
            });
});

In web.xml I have:

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

In spring-servlet.xml I have the view resolver like below:

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

When I am running this in server, it is not going to controller. Please let me know the problem with this code.

Please can any one help on this.

Regards, Shruti

2
  • Did you try browsing to your rest service through a regular browser? Just for making sure if the problem is on the server or client side. Commented Apr 15, 2013 at 14:06
  • you also had an error in your RequestMapping definition, see my answer below. Commented Apr 15, 2013 at 14:28

3 Answers 3

1

Since you have the @RequestMapping(value="register/{userName}" on your method definition, your jquery call must follow the same syntax.

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

But you have also a problem in your RequestMapping value, it should start with /

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

Also I doubt that you need the ".html" at the end

Sign up to request clarification or add additional context in comments.

2 Comments

I have done as you said. I put ' localhost:8085/users/register/…' but it is not working. Please let me know if you need any more information @Serkan Arıkuşu
Hi @Serkan, as you said, I have edited the question with the changes.Please have a look and let me know where I am doing wrong. I am pretty new to this Spring MVC.
0

Add this line to your spring-servlet.xml. It will enable the Web MVC specific annotations like @Controller and @RequestMapping

<mvc:annotation-driven />

Example of an annotated controller

Assuming the url with context is http://localhost:8080/webapp and you want an api call like url /users/register/johnDoe. (johnDoe being the username)

You controller class would look something like the following.

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

@ResponseBody
@RequestMapping(value="/register/{username}", method=RequestMethod.GET)
    public String registerUser(@PathVariable String username) {
        return username;
    }
}

3 Comments

Thanks @Bart for your reply. I have added <mvc:annotation-driven/>. When I am placing localhost:8085/users/register/abc in the browser then in debugger mode it is going to my method but it is not returning anything. From web application when I am doing ajax call it is not going to the controller only.
Did you annotate the controller class with @Controller?
By the way the URL in your question says /ums not /users and your request mapping only answers to /register. I'll put up an example.
0

Please find my solution for calling REST web-services in Spring Framework.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.