My related Request handling code as following
#RequestMapping(value = "/customer" , method = RequestMethod.GET)
public String customer(ModelMap modelMap , #RequestParam Integer age) {
modelMap.addAttribute("requestKey", "Hola!");
modelMap.addAttribute("age", age);
return "cust";
}
#RequestMapping(value = "/request" , method = RequestMethod.GET)
public String welcome(ModelMap modelMap , #RequestParam(value = "age" , required = false)Integer age) {
modelMap.addAttribute("requestKey", "Hola!");
modelMap.addAttribute("age", age);
return "request";
}
#RequestMapping(value = "/request" , method = RequestMethod.POST)
public String responseBody(ModelMap modelMap , final #RequestBody Student student){
modelMap.addAttribute("name", student.getName());
modelMap.addAttribute("lastname", student.getLastname());
modelMap.addAttribute("age", student.getAge());
return "request";
}
cust.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Customer</title>
</head>
<body>
<p>${age}</p>
</body>
</html>
request.jsp
<html>
<head>
<title>RequestBody</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
$.ajax({
url: "customer",
type: "get",
data: {
name: "Okan",
lastname: "Pehlivan",
age:22 },
dataType: "json"
});
};
</script>
</head>
<body>
<p>${requestKey}</p>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
I want to get request using ajax, and i have some parameters, (name=Okan e.g). I want to show any patameter on the cust.jsp. When i debug the code for welcome() metod, age assigned the my age. I mapped this value with its key "age". request.jsp file is not changed.
Ajax call will not change the view. It will return the parameters on same page in success : function(response) {} . If you wants to change the view, you need make non ajax GET call on a separate method and pass inline parameters like:
Controller:
#RequestMapping(value = "/customer/{name}/{lastname}/{age}" , method = RequestMethod.GET)
public String customer(#PathVariable(value = "name") String name, #PathVariable(value = "lastname") String lastname, #PathVariable(value = "age") String age) {
//code here
return "cust";
}
JSP
window.open("/customer/Okan/Pehlivan/22 ","_self");
It will return on cust.jsp
The request jsp is not changed because you are not changing it anywhere on the page after the AJAX call.
You do make a request but are not using the response.
Add a success function to your ajax call and then read the data there.
For example :
$.ajax({
url, data , dataType and method as is with an addition of the following :
success : function(responseText){
Set responseText to your <p>
}
});
For showing the age in cust.jsp, the request parameter needs to be passed while calling the url. something like : http://host-path/context-path/customer?age=69
Autoboxing should take care of int to Integer conversion for request parameter, if you see an exception try using int instead.
Some info that might be of help :
When using ${varName} in jsp / javascript, you need the model to
already have that data.
Consider using tags to control the out put of dynamic
variables, they may help.
When making ajax calls to request for data, process the response in a
handler and continue your logic from there.
HTH.
Related
when press submit button, #dbresult will display value in select option and textarea.
error message in Console:
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException
Warn: Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'querycontent' is not present]
query.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<title>Query DB</title>
</head>
<body>
db:
<select name="dbname" id="dbname">
<option value="ibop_test">ibop_test</option>
<option value="ibop">ibop</option>
</select>
<br>
<textarea class="boxsizingBorder" id="sqlstr"></textarea>
<br>
<button onclick="showresult()">submit</button>
<div id="dbresult"></div>
</body>
<script type="text/javascript">
function showresult() {
document.getElementById("dbresult").innerHTML = "querying...";
var dbname = document.getElementById('dbname').value;
var sqlstr = document.getElementById('sqlstr').value;
var querycontent = JSON.stringify({
"dbname" : dbname,
"sqlstr" : sqlstr
});
console.log(querycontent); //In Chrome's developer tools window, we will see the logs
$
.ajax({
type : 'POST',
url : 'showresult',
contentType : 'application/json',
data : querycontent,
dataType : 'html',
success : function(msg) {
document.getElementById("dbresult").innerHTML = msg;
},
error : function() {
document.getElementById("dbresult").innerHTML = "querying failed!";
}
})
}
</script>
</html>
DBQueryController.java
#Controller
public class DBQueryController {
#RequestMapping(value = "/showresult", method = RequestMethod.POST)
public #ResponseBody String showResult(#RequestParam String querycontent){
String message = "db query result content.</br>";
return message;
}
}
Since you are sending data in body in your AJAX call, hence #RequestParam will not work. You needs to use #RequestBody instead like following:
#Controller
public class DBQueryController {
#RequestMapping(value = "/showresult", method = RequestMethod.POST)
public #ResponseBody String showResult(#RequestBody Map<String, String> querycontent){
String message = "db query result content.</br>";
return message;
}
}
Or simply you can create a POJO class DBQuery like following and use it in controller.
public class DBQuery {
private String dbname;
private String sqlstr;
// Getters and setters
}
#Controller
public class DBQueryController {
#RequestMapping(value = "/showresult", method = RequestMethod.POST)
public #ResponseBody String showResult(#RequestBody DBQuery querycontent){
String message = "db query result content.</br>";
return message;
}
}
Coming back to error, since you are not passing querycontent in request as parameter that's why it its throwing
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'querycontent' is not present]
I am having a few input fields in my jsp page that get a Cyrillic input which I am then upon pressing a button trying to send to this java method using ajax. The strings in the java method end up being gibberish.
The fields in the jsp page:
<div class="span1">
<form:label cssClass="control-label" path="">
<spring:message code="web.messages.someMessage" />
</form:label>
<form:input cssClass="input-block-level" path="" id="articleId" />
</div>
<div class="span1">
<label> </label>
<button type="button" id="search-btn" class="btn" >
<spring:message code="web.messages.buttonMessage" />
</button>
</div>
The ajax in the script:
$("#search-btn").on("click", function(e) {
e.preventDefault();
showDialog("${pageContext.request.contextPath}");
});
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
if (article) {
article = "?article=" + article;
}
$.ajax({
type : "GET",
url : "${pageContext.request.contextPath}/sync/getFilter"
+ article,
success : function(data) {
onClickTable();
}
});
}
This is part of the java method, where the value turns into gibberish:
#RequestMapping(value = "/getFilter", method = RequestMethod.GET)
public #ResponseBody ModelAndView getFilter(HttpServletRequest request) {
String article = (String) request.getParameter("article");
.
.
Fixed the problem by putting the information in a JSON and sending it like that.
The changed made:
The ajax in the script part of the jsp:
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
var data = {
"article": $('#articleId').val().replace(/\s+/g, ""),
// other keys and values
"lastKey": $('#lastValueId').val().replace(/\s+/g, "")
}
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/sync/getFilter",
data: data,
success : function(data) {
onClickTable();
}
});
}
The java method handling the data:
#RequestMapping(value = "/getFilter", method = RequestMethod.POST)
public #ResponseBody ModelAndView getFilter(SomeObject receivedData) {
String article = receivedData.getArticle();
// rest of the method
Where SomeObject is an object containing the values that we receive in the data with proper set and get methods for them.
I have my index.html that has a certain view, and I want to update this view (without redirecting or reloading the page) by calling a java method, that consumes a web service and retrieves data. I want to display the data in my index.html. I tried using a servlet but it redirects to another url and that is not what I want to do.
Is there a way to call a java or display attributes of a java class within my index.html?
I would use jquery and do ajax calls back to the server. Once the ajax call is finished, you can then update your index.html file using javascript and not have to reload the page.
You can use servlet, but you have to use Ajax to make asynchronous calls to the servlet without reloading the full page.
$.ajax({
type:"post",
url: "redirector?operacion=515&id_orden="+id_orden+"&id_acto="+id_acto,
dataType: "text",
success: function(response){
//Do the stuffs you need with the response here.
},
error: function(response,error){
console.log(response);
console.log(error);
}
});
This is an example of ajax call with jquery where "redirector" is the name of my servlet and on my servlet this is the code that I have:
case 515:
PrintWriter writer = response.getWriter();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try {
Integer id_acto = Integer.parseInt(request.getParameter("id_acto"));
String resultado = consultasBBDD.consultarNivelesPorActo(id_acto);
writer.print(resultado);
} catch (Exception e) {
System.out.println("Error recuperando niveles de exigencia");
}
writer.flush();
writer.close();
break;
On the dataType attribute of the ajax call you have to specify the type of the response. Also remember that on your servlet you cant do the request.getRequestDispatcher(urlToGo); when you make ajax calls.
Hope this help and sorry for my horrible english!
One approach is to expose your Java functionality as a REST service.
Jersey REST end point
#Path("/rest/emp/")
public class EmployeeService {
#GET
#Path("/{param}")
public EmployeDTO getMsg(#PathParam("param") String id) {
return getEmployeeDetails(id);
}
}
EmployeDTO.java
String name;
String id;
String address;
//getters and setters
index.html
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="employee.js"></script>
</head>
<body>
<div>
<p id="eid">The ID is: </p>
<p id="eName">The Employee Name: </p>
<p id="eAddress">The Employee Address:</p>
</div>
</body>
</html>
employee.js
$(document).ready(function() {
$.ajax({
url: "/rest/emp/10" (Your Rest end point URL)
}).then(function(data) {
$('#eid').append(data.id);
$('#eName').append(data.name);
$('#eAddress').append(data.address);
});
});
I have a JSP page (client-side)
<form action="http://localhost:8080/REST-WS/rest/token" method="POST">
<label for="email">Email</label>
<input name="email" />
<br/>
<label for="password">Password</label>
<input name="password" />
<br/>
<input type="submit" value="Submit" />
</form>
It points to a function in REST Web Service (server-side)
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Code verify(#FormParam("email") String email,
#FormParam("password") String password,
#Context HttpServletResponse servletResponse) throws IOException {
Code code = generateRandomCode(email,password);
return token;
}
The problem is I want to give response to the client side containing the random-generated code from the server side.
First, it will be redirected to another JSP page and then the client side can receive the random-generated code from server.
How do I do it?
The problem is that you can't send arbitrary Java objects in a redirect. You can however add the data into query parameters. For example
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(#FormParam("name") String name,
#FormParam("email") String email) {
String message = "Hello " + name + ". Your email is " + email;
URI uri = UriBuilder.fromPath("/index.jsp")
.queryParam("message", message)
.build();
return Response.seeOther(uri).build();
}
Here, you are building a URI from the location of the jsp page, and adding a query parameter to the end of the URI. So the redirect will go to
http://localhost:8080/index.jsp?message=<the message>
From the index.jsp page you can get the parameter with request.getParameter("message"). For example
<h1><%= request.getParameter("message") %></h1>
Another option to work with JSP and Jersey is to implement MVC, which Jersey provides support for. You can check out this answer, though the examples use Maven (to get all the required jars). If you are interested and don't know how to use Maven, let me know and I'll see if I can help you get all the jars you need.
UPDATE
Ajax Example.
Easiest Javascript library to get started with (if you have no experience) is jQuery. I won't really give much explanation about the code, that's kinda out of scope. I would go through some tutorials (W3Schools has some good getting started guides), and there are answers all over SO that can answer your questions.
Here's a complete working html page. Just change var url = "/api/submit"; to whatever endpoint you are sending the request to.
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function(){
var url = "/api/submit";
$("#submitBtn").click(function(e) {
e.preventDefault();
var formData = $("#nameForm").serialize();
$.ajax({
url: url,
data: formData,
dataType: "json",
type: "POST",
success: function(data) {
var message = data.message;
var date = data.date;
var h1 = $("<h1>").text(message);
var h3 = $("<h3>").text(date);
$("#content").empty()
.append(h1).append(h3);
},
error: function(jqxhr, status, errorMsg) {
alert(status + ": " + errorMsg);
}
});
});
});
</script>
</head>
<body>
<div id="content">
<form id="nameForm">
First Name: <input type="text" name="fname"/><br/>
Last Name : <input type="text" name="lname"/><br/>
<button id="submitBtn">Submit</button>
</form>
</div>
</body>
</html>
Here is the test resource class
#Path("submit")
public class FormResource {
public static class Model {
public String message;
public String date;
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Model post(#FormParam("fname") String fname,
#FormParam("lname") String lname) {
String message = "Hello " + fname + " " + lname;
Model model = new Model();
model.message = message;
model.date = new Date().toString();
return model;
}
}
You will need to make sure you have a JSON provider to handle the JSON Pojo serialization or it won't work (the Model won't be able to serizalize to JSON).
I am using Spring MVC with the Jackson Processor. When a JSON request is sent to the server as a POST request, the #RequestBody is being deserialized into the object that I need. The problem comes when the GET request is sent, it actually displays Http 500 Internal Server error. The exception that is thrown is:
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2022)
org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1974)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal (MappingJacksonHttpMessageConverter.java:135)
org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments (HandlerMethodInvoker.java:346)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
No emtpy strings are sent and the correct JSON is sent to the server. I am not sure why this is happening. Below is my code:
JSP - index.jsp
<%#page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
userId = form.find('input[name="userId"]').val(),
dat = JSON.stringify({ "userId" : userId });
$.ajax({
url : url,
type : "GET",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/user/find" method="GET">
<input type="text" name="userId" value="user1">
<input type="submit" value="Submit">
</form>
</body>
</html>
As soon as I change the request type to POST in the JSP and the controller method everything seems to work correctly.
package com.web;
#Controller
#RequestMapping("/user/*")
public class UserController {
#RequestMapping(value = "find", method = RequestMethod.GET, headers = {"content-type=application/json"})
public #ResponseBody UserResponse save(#RequestBody User user) throws Exception {
UserResponse userResponse = new UserResponse();
System.out.println("UserId :" + " " + user.getUserId());
return userResponse;
}
beans.xml
<context:component-scan base-package="com.web"/>
<mvc:annotation-driven/>
<context:annotation-config/>
User.java
public class User implements Serializable {
private String userId;
public User() {
}
// Getters and setters
}
When a GET request is sent the broswer usually displays %%user%%. This is only an example. Does the Jackson processor will still read GET requests?
I don't know where the problem is. I hope you can help.
I read the following description on what the data parameter does in jQuey.ajax() does at http://api.jquery.com/jQuery.ajax/:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. ....
So it is appended to the URL and there is no request body. That is a behaviour consistent with the GET semantics, if you want to post data use POST.