简体   繁体   中英

Will coding an AJAX response in Java as a JSP rather than a Servlet cause problems?

I am using JQuery to make some AJAX calls to my tomcat7 server, for example like this:

$.get("ajax.jsp", {param1: val}, function(data, status) { ... }

Is there any problem with coding an AJAX response in Java purely as a JSP rather than as a servlet with doGet() ? In my case, I am returning HTML and not JSON and I am using JSP's ability to intermix Java with HTML to return what I want.

The reason I ask is that all the examples and other stackoverflow answers I've seen related to coding AJAX in Java advise doing this as a Servlet. Will I get into trouble coding this as a JSP?

Yes you will get into trouble. Trouble debugging and maintaining this mish mash of server side and client side code, and it being in unexpected places.

The server should return a view, or in this case it should return the model as json, from a @responsebody annotated controller method.

There is no problem at all to implements the response handlers in jsp and to write all your code and html and mix them. but from design decision and best practices in maintainability, simplicity, clearity and security are to separate your code in different modules each of them responsible for specific job, in web application it is a good idea to separate your java business logic code from pages that render and care of data.

The best design pattern for this issue is the model view controller (MVC design pattern).

imagine in the future if you change your rendering framework. Imagine if you work in a team consists of java developer, web graphics design, database developer, how does you split your tasks with others.

Keep in mind that a good understanding in design patterns and MVC will give you a way to learn and use a good frameworks like Spring, Spring MVC, struts2, JSF, Javaee, ....,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM