1

Trying to find the best way to make a quasi java-javascript web application. I want to write a java servlet (for the controller and backend) with a jQuery front end. What's the best approach to having these two communicate with each other? I'm used to coding in both but never worked on them together.

Can anybody help me out? I suppose a start would be having a Java Servlet call from jQuery code and getting a response back from the servlet.

Thanks!

2 Answers 2

2

Create REST backend using one of JAX-RS implementations (Jersey, RESTeasy etc.). Writing web service with plain old Servlet API is tedious.

You can start learning JAX-RS from here.

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

Comments

1

Take a look at jQuery's ajax function. Here is a simple example:

// Servlet
@SuppressWarnings("serial")
public class AjaxHandler extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {

        resp.setContentType("text/plain");
        resp.getWriter().print("Hello jQuery!");
    }
}

// View.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
    <script>    
        $(document).ready(function() {
            $.ajax({
                url : '/AjaxHandler', // servlet mapping ("web.xml")
                success : function(responseText) {
                    $('#ajaxHandlerResponse').text(responseText);
                }
            });
        });
    </script>
    Servlet's message: <span id="ajaxHandlerResponse"></span>
</body>
</html>

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.