I'm having some trouble getting a JSON String from my servlet, throu my JSP page to my JavaScript and imported into a Vakata/JStree.
This how my current code looks like.
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Du är nu i DoGet MarketDataServlet");
TreeBranchStringBuilder tbsb = new TreeBranchStringBuilder();
request.setAttribute("marketgrouplistJSONString", tbsb.getTreeBranchString(mm.getAllMarketgroups(), im.getAllItems()));
request.getRequestDispatcher("/marketdata.jsp").forward(request, response);
}
JSP/HTML:
<div id="market_tree_branches">
</div>
<div id="hidden"><%= request.getAttribute("marketgrouplistJSONString") %></div>
JavaScript:
var marketnitemsString = $("#hidden").text();
console.log(marketnitemsString)
$('#market_tree_branches').jstree({
'core' : {
'data' : marketnitemsString
}
});
String that's generated from my JSP looks like:
[{"id":2,"text":"Blueprints","parent":"#"},{"id":204,"text":"Ships","parent":"2"},{"id":209,"text":"Ship Equipment","parent":"2"},{"id":211,"text":"Ammunition \u0026 Charges","parent":"2"},{"id":357,"text":"Drones","parent":"2"},{"id":943,"text":"Ship Modifications","parent":"2"},{"id":1041,"text":"Manufacture \u0026 Research","parent":"2"},{"id":1338,"text":"Structures","parent":"2"},{"id":9,"text":"Ship Equipment","parent":"#"},{"id":10,"text":"Turrets \u0026 Bays","parent":"9"}]
This is the error i'm getting in my Chrome Console Log:
Uncaught Error: Syntax error, unrecognized expression:
[{"id":2,"text":"Blueprints","parent":"#"},{"id":204,"text":"Ships","parent":"2"},{"id":209,"text":"Ship Equipment","parent":"2"},{"id":211,"text":"Ammunition \u0026 Charges","parent":"2"}, ........
I'm guessing that something during the process of sending it from the JSP/HTML to the JavaScript variable goes wrong but i cant figure out what, since the JStree cant read it as a variable. If i however copy/paste the entire string from the HTML into the 'data': it works fine.
Your best bet would to be use an AJAX call from the JavasScript code directly to the servlet. There's absolutely no reason to have the JSP get in the middle there. You can just do something like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Du är nu i DoGet MarketDataServlet");
TreeBranchStringBuilder tbsb = new TreeBranchStringBuilder();
String json = bsb.getTreeBranchString(mm.getAllMarketgroups(), im.getAllItems());
response.setContentType("application/json");
response.getWriter().println(json);
}
For the JavaScript side, it depends entirely on what JavaScript framework you want to use. JQuery is the easiest starting point for this.
I'm not sure why you have to pass through a hidden element:
var marketnitemsString = <%= request.getAttribute("marketgrouplistJSONString") %>;
$('#market_tree_branches').jstree({
'core' : {
'data' : marketnitemsString
}
});
Since the <% %> is executed before the js is parsed, the text it produces is then interpreted as standard JS by the client and as long as it is semantically correct, it will do what's supposed to (store an array in the variable).
This is pretty much similar to code that I actually use so I'm fairly sure it works even if I cannot test it at the moment.
Also, if your data is an array, I'm not sure that the core.data element could accept it in form of a string:
http://www.jstree.com/api/#/?f=$.jstree.defaults.core.data
so that could be the origin of the problem with your code.
Related
I want to include header and footer template in my servlet, like this in PHP in a PHP controller :
public doSomething()
{
include "header.html";
//generate doSomething content in HTML and echo it
include "footer.html";
}
PS : It's an example, i don't do directly like this in PHP ;)
In this way, I want to avoid like this in all JSP files (the includes) :
<jsp:include page="header.html" />
<%-- Display doSomething informations -->
<jsp:include page="footer.html" />
So exactly, I want :
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
//Include the header.html
this.getServletContext().getRequestDispatcher( "/WEB-INF/Example.jsp" ).forward( request, response );
//Include the footer.html
}
Here, I want to include footer and header to do not do this into JSP.
So RP anwsert this question in the comments,, but to give this question an actual anwser i copied his into here:
"One option is read them into string and set them as request attributes and use those attributes in jsp or write those strings in to response and call request dispatcher's include method." - RP
I have a JSP page with two buttons. One is On and other one is OFF.
If I click on ON button in JSP, On click some predefined string will have to send to IP address.
How can we call Java program from JSP on click button?
Just give the individual button elements an unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
</form>
with
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
if (request.getParameter("button1") != null)
{
myClass.function1();
}
else
{
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
You can call it using Ajax . AJAX request will invoke any java program you want by sending the request to the server. see this for more info.
There are also other possible options you can use DWR for secure transactions.
See here for jquery ajax post . Also here is good example for using it with servlets.
Hope this helps !!
side-note: If you need any specific help , please post us the code which you are trying
I'm on a jsp page and I am doing an ajax call to a servlet which in return provides full html code to be displayed on page. It works fine but looks cluttered in servlet file to have multiple printWriter.write(...) lines with html code in it. It becomes hard to maintain as I have to create a large html code via servlet. Is there any other proper/better way to do this? I have cmobination of write html lines and logic in servlet and it will be hard to separate them.
The ajax call in jsp page:
$.ajax({
type: 'POST',
url: 'myServlet',
data: requestData,
dataType: "text",
}).done(function(responseData) {
$(divId).html(responseData);
});
Some code from servlet class:
.....
String username = user.getName();
if (username != null && !username.trim().isEmpty())
username = username.substring(0, username.indexOf(" "));
else
username = "";
printWriter.write("<span id=\"username_"+i+"\" style=\"display: none;\">"+ username +"</span>");
printWriter.write("<form action=\"\" method=\"post\" name=\"userClickForm_"+i +"\" id=\"userClickForm_"+i +"\">");
printWriter.write(" <input type=\"hidden\" name=\"userId\" value=\""+userId +"\"/>");
printWriter.write("</form>");
......
The main reason of mixing html code and business logic is I have to provide div id based on conditions and loop structure.
You should use some form of template or transformation technology. Since you're using jQuery and JSPs this can be either a server-side JSP or a client-side jQuery template plugin.
Early JSP MVC patterns take this form:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// read inputs
String foo = request.getParameter("foo");
// perform business logic
SomeResults results = new SomeDataSource().lookupDatabase(foo);
// place results into scope
request.setAttribute("results", results);
// dispatch to JSP to render results
request.getRequestDispatcher("result.jsp")
.forward(request, response);
}
This approach can be used with an AJAX call.
Alternatively, you can respond with JSON or XML data and parse this in the JavaScript, then use a JavaScript template engine to do something similar to the logic performed in the JSP.
You can avoid that by using MVC framework like STRUTS or SPRING.
Use xml rather than html on servlet and on jsp use success attribute of ajax call using jquery.... In my case its working, bt i have used type as 'GET'.
$.ajax({
url: ,
data: ,
type: ,
dataType: 'xml',
async: true,
success:function(xmlDoc)
{
var message = xmlDoc.getElementsByTagName("message");
message = message[0].firstChild.data;
}
});
And in Servlet use::
res.getWriter().write("<response><message>abcdefg</message></response>");
You should use JSP's. It will be on different pair of servlet/jsp request, not the request initiating ajax call.
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 1 year ago.
I am trying to create a web application using the MVC design pattern. For the GUI part I would like to use JavaScript. And for the controller Java Servlets.
Now I have never really worked with JavaScript, so I'm having a hard time figuring out how to call a Java Servlet from JavaScript and how to get the response from the Servlet.
Can anybody help me out?
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World! in the JavaScript alert.
You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
The code here will use AJAX to print text to an HTML5 document dynamically
(Ajax code is similar to book Internet & WWW (Deitel)):
Javascript code:
var asyncRequest;
function start(){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open('GET', '/Test', true); // /Test is url to Servlet!
asyncRequest.send(null);
}
catch(exception)
{
alert("Request failed");
}
}
function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
{
var text = document.getElementById("text"); // text is an id of a
text.innerHTML = asyncRequest.responseText; // div in HTML document
}
}
window.addEventListener("load", start(), false);
Servlet java code:
public class Test extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException{
resp.setContentType("text/plain");
resp.getWriter().println("Servlet wrote this! (Test.java)");
}
}
HTML document
<div id = "text"></div>
EDIT
I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):
document.location = 'path/to/servlet';
Where your servlet-mapping in web.xml looks something like this:
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});
I've developed an HTML page that sends information to a Servlet. In the Servlet, I am using the methods doGet() and doPost():
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("realname");
String password = req.getParameter("mypassword");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("realname");
String password = req.getParameter("mypassword");
}
In the html page code that calls the Servlet is:
<form action="identification" method="post" enctype="multipart/form-data">
User Name: <input type="text" name="realname">
Password: <input type="password" name="mypassword">
<input type="submit" value="Identification">
</form>
When I use method = "get" in the Servlet, I get the value of id and password, however when using method = "post", id and password are set to null. Why don't I get the values in this case?
Another thing I'd like to know is how to use the data generated or validated by the Servlet. For example, if the Servlet shown above authenticates the user, I'd like to print the user id in my HTML page. I should be able to send the string 'id' as a response and use this info in my HTML page. Is it possible?
Introduction
You should use doGet() when you want to intercept on HTTP GET requests. You should use doPost() when you want to intercept on HTTP POST requests. That's all. Do not port the one to the other or vice versa (such as in Netbeans' unfortunate auto-generated processRequest() method). This makes no utter sense.
GET
Usually, HTTP GET requests are idempotent. I.e. you get exactly the same result everytime you execute the request (leaving authorization/authentication and the time-sensitive nature of the page —search results, last news, etc— outside consideration). We can talk about a bookmarkable request. Clicking a link, clicking a bookmark, entering raw URL in browser address bar, etcetera will all fire a HTTP GET request. If a Servlet is listening on the URL in question, then its doGet() method will be called. It's usually used to preprocess a request. I.e. doing some business stuff before presenting the HTML output from a JSP, such as gathering data for display in a table.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
Note that the JSP file is explicitly placed in /WEB-INF folder in order to prevent endusers being able to access it directly without invoking the preprocessing servlet (and thus end up getting confused by seeing an empty table).
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>detail</td>
</tr>
</c:forEach>
</table>
Also view/edit detail links as shown in last column above are usually idempotent.
#WebServlet("/product")
public class ProductServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product product = productService.find(request.getParameter("id"));
request.setAttribute("product", product); // Will be available as ${product} in JSP
request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
}
}
<dl>
<dt>ID</dt>
<dd>${product.id}</dd>
<dt>Name</dt>
<dd>${product.name}</dd>
<dt>Description</dt>
<dd>${product.description}</dd>
<dt>Price</dt>
<dd>${product.price}</dd>
<dt>Image</dt>
<dd><img src="productImage?id=${product.id}" /></dd>
</dl>
POST
HTTP POST requests are not idempotent. If the enduser has submitted a POST form on an URL beforehand, which hasn't performed a redirect, then the URL is not necessarily bookmarkable. The submitted form data is not reflected in the URL. Copypasting the URL into a new browser window/tab may not necessarily yield exactly the same result as after the form submit. Such an URL is then not bookmarkable. If a Servlet is listening on the URL in question, then its doPost() will be called. It's usually used to postprocess a request. I.e. gathering data from a submitted HTML form and doing some business stuff with it (conversion, validation, saving in DB, etcetera). Finally usually the result is presented as HTML from the forwarded JSP page.
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="login">
<span class="error">${error}</span>
</form>
...which can be used in combination with this piece of Servlet:
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
#EJB
private UserService userService;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("home");
}
else {
request.setAttribute("error", "Unknown user, please try again");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
You see, if the User is found in DB (i.e. username and password are valid), then the User will be put in session scope (i.e. "logged in") and the servlet will redirect to some main page (this example goes to http://example.com/contextname/home), else it will set an error message and forward the request back to the same JSP page so that the message get displayed by ${error}.
You can if necessary also "hide" the login.jsp in /WEB-INF/login.jsp so that the users can only access it by the servlet. This keeps the URL clean http://example.com/contextname/login. All you need to do is to add a doGet() to the servlet like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
(and update the same line in doPost() accordingly)
That said, I am not sure if it is just playing around and shooting in the dark, but the code which you posted doesn't look good (such as using compareTo() instead of equals() and digging in the parameternames instead of just using getParameter() and the id and password seems to be declared as servlet instance variables — which is NOT threadsafe). So I would strongly recommend to learn a bit more about basic Java SE API using the Oracle tutorials (check the chapter "Trails Covering the Basics") and how to use JSP/Servlets the right way using those tutorials.
See also:
Our servlets wiki page
Java EE web development, where do I start and what skills do I need?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Update: as per the update of your question (which is pretty major, you should not remove parts of your original question, this would make the answers worthless .. rather add the information in a new block) , it turns out that you're unnecessarily setting form's encoding type to multipart/form-data. This will send the request parameters in a different composition than the (default) application/x-www-form-urlencoded which sends the request parameters as a query string (e.g. name1=value1&name2=value2&name3=value3). You only need multipart/form-data whenever you have a <input type="file"> element in the form to upload files which may be non-character data (binary data). This is not the case in your case, so just remove it and it will work as expected. If you ever need to upload files, then you'll have to set the encoding type so and parse the request body yourself. Usually you use the Apache Commons FileUpload there for, but if you're already on fresh new Servlet 3.0 API, then you can just use builtin facilities starting with HttpServletRequest#getPart(). See also this answer for a concrete example: How to upload files to server using JSP/Servlet?
Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.
The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.
The GET method is used in one of two ways:
When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc.
When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&"
Example:
GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>
The name=value form data will be stored in an environment variable called QUERY_STRING.
This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)
The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.
Example:
POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla
When using the post method, the QUERY_STRING environment variable will be empty.
Advantages/Disadvantages of GET vs. POST
Advantages of the GET method:
Slightly faster
Parameters can be entered via a form or by appending them after the URL
Page can be bookmarked with its parameters
Disadvantages of the GET method:
Can only send 4K worth of data. (You should not use it when using a textarea field)
Parameters are visible at the end of the URL
Advantages of the POST method:
Parameters are not visible at the end of the URL. (Use for sensitive data)
Can send more that 4K worth of data to server
Disadvantages of the POST method:
Can cannot be bookmarked with its data
The servlet container's implementation of HttpServlet.service() method will automatically forward to doGet() or doPost() as necessary, so you shouldn't need to override the service method.
Could it be that you are passing the data through get, not post?
<form method="get" ..>
..
</form>
If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted.
On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.
Examples from my html:
<body>
<form action="StartProcessUrl" method="post">
.....
.....
Examples from my java servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String surname = request.getParameter("txtSurname");
String firstname = request.getParameter("txtForename");
String rqNo = request.getParameter("txtRQ6");
String nhsNo = request.getParameter("txtNHSNo");
String attachment1 = request.getParameter("base64textarea1");
String attachment2 = request.getParameter("base64textarea2");
.........
.........