I need to get userPrincipal inside a piece of Javascript code. My app currently uses Dojo on the client side and servlets on the server side. I am not using JSF, nor JSP (and if possible I would try to avoid using it only for this purpose), nor JQuery (I would avoid mixing JQuery with Dojo).
I have read this interesting post Mixing JSF EL in a JavaScript file . Following the idea #1, I have written a Bean but I am not sure on how to embed the call to the Bean in my (quite long) js file.
If you don't use JSF or JSP or anything similar, just bare servlets, I recommend creating a servlet which takes the userPrincipal name from the HttpServletRequest (or any other place) and returns it in JSON format. Then you can do an AJAX call to the servlet and find out what you need. I don't know Dojo too well, but I believe you can insert this AJAX call in your event chains pretty easily.
I don't recommend mixing managed beans with plain-old servlets.
If AJAX is not an option for you because of its asynchronous nature, you cand create a servlet that serves text/javascript content which offers the principal's name in the form of javascript code and then add a script tag to your page.
Related
I'm trying to do a single page application using servlets and jsp pages.
For the moment I have the first page, which is simple to do: a servlet that forwards to the corresponding jsp.
How should the implementation look when navigating to the second page?
I guess it should be an ajax call, the servlet would populate the necessary data, but how to display the second page jsp?
JSP is a server side ui technology. A Servlet listens to specific urls and redirects to JSPs pages. The JSP is compiled to a class (another servlet in fact), invoked (data will be added and inline scripts will run) and the output, whith is HTML, is send to the client (browser). To get to a different page its neccessary to query the server (servlet) for another url, resulting in another html page.
To create an SPA you need a client side technology like JavaScript. Your query the server for a single html page. The page, made of HTML and JavaScript, for example, (could even be the output of a single JSP, dont get confused) is send to the client (browser) and the JS is run. This is nomaly backed up by a framework like AngularJS, EmberJS or Backbone. Once the page is set up, the links within the page are anchors (http://example.com/#/mySecondPage), so clicking them will invoke the framework again (Ajax, querying the server for new data), but will stay on the same page. Some contents of the page might then be replaced by new content.
If it is a true SPA then you would just have a single JSP and handle all your functionality (after your initial page load) using Ajax.
Have you looked at using a client-side framework such as Angular to help you with this?
Depending on how rich your SPA is, you could either use the same servlet or multiple servlets to serve each page.
Unless you are doing this for a course or tutorial and have some constraints on how to achieve it, you will very probably save yourself a lot of time if you couple something like Angular with a server-side framework like Spring instead of coding servlets. As a suggestion have a look at Spring with Angular.
In SPA the browser only loads the document once (or a few, once per sub-application), and further communication to the server is done usually via AJAX or Websockets.
I recommend you to model your application as a thin server architecture, that is, a client application running in the browser (HTML, CSS, Javascript) consuming a web service API provided by the server.
The following are some points worth knowing;
Client-side:
Only presentation logic
Represent state by URL hash. This enables bookmarking, hyperlinking and browsing history. Your client app should listen to changes in the URL hash and act in consequence. This technique is called "routing" and it is implemented by all Javascript frameworks.
Client application is packaged server-side such it can be downloaded in a single request (in .html, .jsp, servlet, .jsp + multiple .jspf, ...)
Consumes services provided by the server via AJAX or Websockets
Server:
Offers client application to download
Provides a clean, stateless API to be consumed by the client application, better returning JSON (data) than HTML (presentation logic) (Why is it a bad practice to return generated HTML instead of JSON? Or is it?)
Use a REST or JSON-RPC frameworks to create the API. There is a lot of debate on what to choose (see here or here). In my opinion the only advantage of REST over RPC is that since REST has become a "de facto" standard its interoperability is higher, so my recommendation for SPA applications is using JSON-RPC, because your code is the only client of the API.
There are lots of alternatives for both client and server frameworks.
Javascript: AngularJS, EmberJS or Backbone,...
REST: Spring, Jersey, Restlet,..
JSON-RPC: https://en.wikipedia.org/wiki/JSON-RPC#Implementations
Regarding JSON-RPC, you might want to take a look to Brutusin-RPC, a JEE microframework I have created :)
If you are using an Ajax request, then you need to tell the browser that redirect to the second page. Example:
response.sendRedirect("second_page.jsp");
In your servlet, you need to differentiate a request to the first page, from a request that need to be redirected to the second page. You can use parameters, or session values, for example.
if (request.getParameter("page2") != null) {
response.sendRedirect("second_page.jsp");
} else {
.... // include here the normal logic of your Servlet for page 1
}
Then, you can invoke your servlet with or wihout the parameter page2, to go to page 1 (without parameter), or page 2 (with parameter).
I have a jsp page(calendar) with lots of JSTL tags in it.
I set the attributes in my servlet and get them in my jsp page thanks to JSTL, EL.
When I press nextweek, I open a xmlhttp which sends a GET to my servlet(Ajax).
All my attributes renew so i want to get them again in my jsp page.
I do not want to dispatch the servlet to my jsp page because of performance latency.
I don't want to fetch servlet results because they are attributes.
I just want to refresh my JSTL & EL so they will get the new values (without refreshing the page).
Is this an illogical way of thinking? but anyway, how can I refresh my JSTL,EL, scriptlets so the new values will appear?
I just want to refresh my JSTL & EL so they will get the new values (without refreching the page)
This is impossible. Note that EL and JSTL run on server side in view build time, so once they're applied when generating the server response, they can't be updated in the page until the server generates new content using the view (basically, your JSP with JSTL, EL and other components)1.
You should look into AJAX requests to your servlet (or the controllers you're using) and probably handling a JSON response to resolve the behavior of your JSP page.
More info:
How to use Servlets and Ajax?
1 Scriptlets also fall in server side category but I omit them since you should not use them for being highly discouraged to use in modern Java web development. More info How to avoid Java code in JSP files?
HttpServlets, JSP, JSTL, EL, and scriptlets are all server side components, ie. get executed on the server to produce an HTTP response. Javascript and AJAX are client side components, ie. work on the returned HTTP response.
You cannot refresh my JSTL & EL on the client side because they simply do not exist.
A possible (and common) solution is to have the request you make with AJAX produce a JSON response which you use to populate/replace HTML elements, where your EL had previously been used to set a value.
I have created a servlet called dbConnect(return type Connection). In which i wrote the code to connect to the database. Now I am calling the dbConnect(<%Connection con=dbConnect.getConnection()%>) into the JSP file. Since JSP file will be in the client side is there any possibility that an hacker can hack the connection??
The larger question is whether or not this is a good thing to do.
My preference would be no scriptlet code in JSPs whatsoever. If you must write JSPs, I'd recommend using JSTL tags and a servlet to handle requests. Let a servlet sit between the JSP and the database and intercede on its behalf with the database. You can do authentication, input validation, binding, and routing in the servlet and let the JSP do what it was meant to do: display only.
If this JSP is intended for anything other than a single toy application, I'd recommend that you dig into model-2 web MVC using JSPs and servlets.
JSP files aren't on the client side. A JSP is compiled into a servlet so anything you feel safe doing in a servlet is just as safe in a JSP page. That code snippet inside of <% %> is turned into plain old java code. Your HTML is turned into a string that's spit out from the servlet back to the client.
So yes, it's fine.
Is it possible to embed html with java
test.html
<input id="buttonId" type="button" class="button-click"
value="" onClick="checkSucess(2)" onload="counts(count)">
test.js
checkSucess = function(firstVal) {
// Jquery Ajax with url,params and response
doPost('test.java',
'first=' + firstVal,
function(response) {
});
test.java
Here get the 'first' value from ajax request, and further processing.
I believe you're looking for JavaServer Pages (.jsp), a starting point for implementing server-side logic using Java. (You can GET/POST to a jsp.)
Reference
JSP + Ajax Example
JavaServer Pages Technology
JSP Tutorial
Well, Java on the server side doesn't work quite like PHP. i.e. you can't simply drop your java files in your htdocs directory and trigger it by filename directly. Firstly you'll need an app server like tomcat or jetty (instead of just a webserver like apache httpd). Secondly, you'll need to create a Servlet (simplest case) and write your java code there and trigger it using the server request url. Google "servlets" and you should be able to pick it from there..
No, you can't do like that, you have to use AJAX request to interact with java from your html or javascript. For that you have to use servlet and pass the servlet URL to doPost function.
doPost('url to servlet',
'first=' + firstVal,
function(response) {
});
Since this is your first java project, you should do some reading to come up to speed with java. Here are some good tutorials:
Core Servlets, Intermediate Servlets
Apache Tomcat 6 - Apache is a nice tool for learning servlets; it is easy to install and run.
Core Servlets; Advanced Servlets - This may be more than you need.
Applets are Java, and the only (usual) way for Java in the browser.
You can communicate with Applets from Javascript/JQuery code. Applets have ending .class (.java is source code, you can't communicate with it).
In the case you want to communicate with serverside Java, you need servlets there. Then send requests to the url of the servlets.
No. Besides using Java Applets - which are actually just plugins - there is no way to embed Java into HTML.
That being said, It is possible to generate HTML using Java Server Pages.
It is also possible to use an HTML page in conjunction with JavaScript to interact with Java via subsequent HTTP Requests made using AJAX. These requests are initiated on the client browser, and received and fulfilled by a server capable of executing Java Server Pages (JPS).
Example:
An HTML page is loadad with some JavaScript that requests some url upon completion of DOM loading.
The request is received by some server which then responds to the request.
The client browser receives the response and provides it to JavaScript to be dealt with.
JavaScript reads the response, and uses it in some way (like "refreshing" some information on the page).
This question is about a proper architecture using JSP as a controller for ExtJS.
I am fairly new to server side development but I am pretty familiar with ExtJS 4 and getting better with Java and SQL daily.
I am trying to create a JSP controller to write the data from stores in ExtJS. I have MSSQL database and Tomcat running on the server.
I successfully created a JSP (sqlData.jsp) that reads from the database and returns JSON data. I pass a query name to this JSP, it then looks up what the query is from a "query" table (columns: [query_id],[query_name],[query]). It then runs the query and returns the data in a JSON format - this is working fine to get data into ExtJS from a database.
To use this backend set-up I usually configure the store like this:
var store = Ext.create('Ext.data.Store', {
model: 'aModel',
proxy: {
type: 'ajax',
url: 'sqlData.jsp?queryName=aQueryName',
reader: 'json'
},
autoLoad: true
});
Somehow, I need this sqlData.jsp to also handle a store.save() call from the ExtJS framework. Which means the JSP needs to receive a POST request and then do an update based on a pile of JSON data (ExtJS sends read request as GET and write methods like store.save() are POST).
My plan was to add something in the Java to recognize whether it is a POST or GET request. Then, if it is a POST request, I would send it to a different Java method in the JSP to parse the JSON and write it to the database.
Of course I would have to change my "query" table to have another column for update/insert statements linked to the same queryName (i.e.: [query_id],[query_name],[select_query],[update_query]).
Does this backend implementation make any sense?
Anyone else use JSP and ExtJS to achieve this smoother?
I noticed that there is an api config option I can set in my proxy to specify different URLs for the different operations (READ, WRITE, DELETE, etc). Should I make a separate JSP and direct all write requests using this config instead?
Would it be wiser to add a writer: 'json' config on the proxy so that it parses before POSTING? I figured I would have to parse it in the JSP either way so I didn't think I should.
Any pointers will be much appreciated.
since your backend is Java, I would really recommend using Spring 3.0 MVC to code your backend.
JSP is not a good option for the stuff you are doing because:
the functions you write in there are not unit testable.
the functions you write in there are not reusable.
the code you write in JSP are functional in nature, not object oriented, you can't inject the services you need into your JSP.
Spring 3.0 MVC has really good synergy with ExtJS 4, namely the RESTful URL's and content negotiation.
This example shows how to integrate the two things together. http://java.dzone.com/articles/extjs-4-file-upload-spring-mvc
I would skip jsp and just go directly to servlets. i.e. implement the logic in the servlets for both returning json, and handling things like POST, PUT, etc.....
jsps are meant to be views. But in your case, your view layer is its own application running in the client. You only need the data.
The Servlet API puts allows you to handle requests, get the http method, and stream data to the response.
My advice is go with an MVC server side framework. My favorite is Grails which lets you work with JSON objects directly for both input and output. Its also super simple to with grails to read and write data to the database.