1

I am developing a webservice using rest API. I want to get what the user types in the URL.For example, if a user requests "http://localhost:8080/employee?ename=john" then I want to get "john" so that I can use the value for further checking. How can I get that variable?

3 Answers3

1
@Controller
@RequestMapping("/employee")
public class Employee {

  @RequestMapping(value="", method=RequestMethod.GET)
  public String disp(HttpServletRequest request, @RequestParam(value="ename", required=false) String ename) {
    // used
    System.out.println(ename); // voted
    // or
    request.getParameter("ename");
  }
}

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html

syaku
  • 102
  • 1
  • 5
  • Thanks for the respond. I am sure that this should be a silly question. But can you tell me how should I read this method in my main method? –  Nov 23 '17 at 09:07
0

If only one param is sending you can use @RequestParam as mentioned in other answers. But if you have so many data to post from UI to controller then use @RequestBody annotation and create a model class with all params you are sending. Then all data send will be automatically bind to the model. See below code.

Say your url is like this http://localhost:8080/employee?ename=john&lastname=peter&address=someValue

Model Class

    class UIMapper{

    private String ename;
    private String lastname;
    private String address;

//Create getters and setters here

    }

Your controller class

    class AController{


        @RequestMapping(value = { "/webserviceInsert" })
            public String webserviceInsert(@RequestBody UIMapper uiObj) {


        String eName=uiObj.getEname();//Assume you have created getters and setters

return "success";   
        }



        }

Thus the whole thing you will get in an object which will be easy to transfer from controller to servcie or dao layer.

Vipin CP
  • 3,642
  • 3
  • 33
  • 55
0
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;


@RestController
public class Employee {

@RequestMapping("/employee")
public String employeeDislpay(@RequestParam(value="ename") String ename) {

   System.out.println(ename);

 }
}

http://spring.io/guides/gs/rest-service/

Manikanta P
  • 2,777
  • 2
  • 19
  • 22