Varun
Varun

Reputation: 4452

How to call controller method from jsp using ajax

I am using spring boot, maven 3.2.5. I am working on simple maven webapp using spring boot following mvc pattern. i am trying to call controller method from jsp suing ajax.

this is my jsp javascript method look like , which call the ajax call to call the controller method.

function listExistingUser()
	{	
	
	alert("listExistingUser");

		$.ajax({
			type : "GET",
			url : '${home}/loginController/listExistingUser',
			dataType : "json",
		    crossDomain:true,
			success : function(data) {
				//console.log(data);
				//alert(data.toString());
				checkValidUser(data);	
			},
			error : function(data) {
					
			}
			});
	} 

Bellow is my controller class.

@Controller
@RequestMapping("/loginController")
public class LoginController {
	
	@Autowired
	LoginService loginService;
	
	@RequestMapping(value = "/listExistingUser", method = RequestMethod.GET)
	 @ResponseBody
	public Object getAuthentication(@ModelAttribute("studentId") int studentId,
			   HttpServletRequest request, HttpServletResponse response)
			   {
				System.out.println("listExistingUser is called in controller");
			   }
}

when I run my application, I am able to access login.jsp from the bellow url http://localhost:9090/seperation-management/pages/login.jsp

when i hit submit button my jsp page javascript method is also getting called that is alert("listExistingUser"); but i am not able to called my controller method.

where I am making mistake. can anyone help me.

Upvotes: 1

Views: 14166

Answers (2)

Priyamal
Priyamal

Reputation: 2969

there's some changes to be made in the contoller method

@RequestMapping(value = "/listExistingUser", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getAuthentication(){
System.out.println("listExistingUser is called in controller");
return new ResponseEntity<Object>(object,HttpStatus.OK); 
}

you dont need to have @modelAttribute annotation since you are not binding any object with the request. and it is a good practise to return ResponseEntity instead of returning an Object.

if you need to get an id from an incoming request like this siteName/listExistingUser/1 then use this method.

@RequestMapping(value = "/listExistingUser/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getAuthentication(@PathVariable("id") int id){}

if you want to get values from a url like this siteName/listExistingUser?id=1 then use this method instead.

@RequestMapping(value = "/listExistingUser", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getAuthentication(@RequestParam("id") int id){}

Upvotes: 2

FuSsA
FuSsA

Reputation: 4297

This example is working in my Application:

JSP:

<script type="text/javascript" charset="utf-8">
        function getDesc() {
            $.getJSON("desclist.json", {
                sel1Id : $('select#COMPSNT_NM').val()
            }, function(data) {
                var html = '';
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + data[i] + '">'
                            + data[i] + '</option>';
                }
                $('select#COMPSNT_DS').html(html);
            });
        }

        $(document).ready(function() {
            $('#COMPSNT_NM').change(function() {
                getDesc();
            });
        });
</script>

Controller:

@RequestMapping(value = "desclist.json")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody List<String> sectionList(@RequestParam(value = "sel1Id", required = true) String sel1Id,
        ModelMap modelMap) {

    List<PARAM_SEQ_2> list = new ArrayList<>();
    List<String> list2 = new ArrayList<>();
    list = paramSeq2Service.findByField2(sel1Id);
    for (PARAM_SEQ_2 prm : list) {
        list2.add(prm.getCOMPSNT_DS());
    }
    return list2;

}

Upvotes: 0

Related Questions