I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else facing similar confusion.
My problem involves using a String in Java that originates from client-side JS. While my JS alerts are working correctly, the JSON object in my Servlet appears to be either null or empty. I simply need to pass one string to my servlet in order to execute SQL queries, but I am encountering difficulties in doing so.
Thank you!
HTML File
<div class="jumbotron" id="jumboframe">
<h1>Enter your URL below</h1>
<input class="txtUrl" type="text" id="txtUrl" value="...." onfocus="if(this.value == '....') { this.value = ''; }"/>
<p><a class="btn btn-lg submitButton" href="testpage.html" onclick="getURL()" role="button">Start searching!</a></p>
</div>
<script>
function getURL() {
var urlString = document.getElementById("txtUrl").value;
var params = {url: urlString};
$.ajax({
type: "POST",
url: "testpage.html",
contentType: "application/json",
dataType: "text", // "JSON" here doesn't call alerts below
data: {
'url': urlString
},
success: function(data) {
alert("did it!");
alert(JSON.stringify(params));
alert(JSON.stringify(data));
}
});
}
</script>
Java Servlet
public class JavaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
StringBuilder builder = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
out.println(builder.toString());
String url = request.getParameter("url");
Map<String, String[]> map = request.getParameterMap();
out.println(map.toString());
out.println(url);
web.xml
<servlet>
<servlet-name>JavaServlet</servlet-name>
<servlet-class>path.to.my.JavaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaServlet</servlet-name>
<url-pattern>/testpage.html</url-pattern>
</servlet-mapping>
Once again, thank you.