Run Servlet Without POST or GET - java

I am new to servlets, and would like to follow the Model2 paradigm by keeping all my "code" in servlets, and html/beans in jsp pages. But, is there a way to run a servlet when I access a jsp page without using a form submission. For example, I have a login page. If the user logs in and then somehow goes back to the login page I want to check for the existance of their session and automatically move them on to their welcome page. This is one real world example, but it seems it would come in handy to run code without having to submit a form for a multitude of reasons.

you dont have to submit a form to invoke a servlet. All you have to do is have the browser hit the url that is mapped to the servlet. That could happen when submitting a form, clicking a link, invoking an xhr, using curl or wget from the command line, etc.
Also, keeping all code in servlets is not good design. Your servlets should handle incoming requests, invoke business logic implemented in separate classes (for good modularity and testing purposes), and return the appropriate response.

If I recall correctly, in Model2, the user never navigates to (JSP) pages - only controllers (servlets). Trying to access a lower layer of code (a servlet) direcltly from a view (the page) is a violation of MVC/Model2.

Related

Can Multiple different Servlets be run Sequentially in a java EE project?

I am having a html page, which takes in the username and password and takes it to the servlet for authenticating. If authenticated, it gets a link to go to another html page, which accepts input for placing a order, this inputs are finally passed to a servlet, which makes the data persistent by storing it in the database,
By far, i can make a html page for username and password and a servlet for authenticating. even the link for going to another html page, which accepts the input of the order details also works, after that, the servlet does not work.
Using Glasfish Server and netbeans for development.
check Servlet Filter : they are invoked before/after a servlet, and are used to handle authentication, caching, etc

How to do a SPA using servlets and jsp?

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).

How to handle no request on servlet

I have a .jsp page where I've coded a form that submits some input to a servlet. The servlet manipulates the input and then sends a message to the same page. This is working fine, however, when I get back to the .jsp page, or in other words, when I get the answer from the servlet, the url that is visible in the browser contains the path to the servlet (e.g http:/index.jsp/servlet_name ), so, when I refresh the page, the browser redirects to the servlet and it get stuck because there was no get/post submission, so doGet() or doPost() are never active.. Is it possible to handle no get/post request in the servlet ? If not, how should I handle this problem ?
Ps: I'm using jquery mobile to build the pages (in the event of a possible solution with this framework)
I think you got it wrong. Even when you refresh, normally either doGet() / doPost() is activated. Your browser often asks you first if you're refreshing post requests.
What could be happening is your servlet is serving another request without form data, hence you get the impression it's not doing anything

Are struts2 actions called when user asks for a jsp through a search engine

I have just started working on a struts2 project. I have seen the power of actions in struts.
i just want to Know few things
1.When a client asks for a page through the search engine does the server direct the request through an action which maps the jsp?
2. If the ans to the above question is no how do we set-up all the bean properties in the action class required for rendering the page?
3.If the ans to the above question is no how to maintain data confidentiality as all interceptors are built around action
If your JSP pages are publicly accessible and a user goes to them directly (e.g., from a search engine or bookmark), then no, your action would not be invoked.
Your JSPs should be placed under the WEB-INF directory (e.g., /WEB-INF/jsp) so that users cannot get to them directly. In Struts2 (any many other MVC frameworks), JSPs are only the templates for your view layer and should not be accessed directly.
There are several comments in reply to one of the answers in Problem with moving JSPs under WEB-INF directory that reinforce this:
I'm not sure about struts, but with Spring, it is accepted practice to put JSPs in WEB-INF and then your view code accesses the protected JSP. This also prevents direct HTTP access to your JSPs so you get better access controls. -- jkf
Same goes for Struts as well. It is considered a good practice to put JSPs in WEB-INF folder. Anyways, I have got my answer. -- craftsman
The way Struts works is that it has a dispatcher servlet that reads the path of incoming requests and decides which action to send them to, then the action executes and forwards to a jsp. So whether the action gets called depends on what the url is that the client is clicking on, if it is a url that is mapped to an action in struts then it will call the action, otherwise not.

Form based login while also applying REST principles

I am a Spring/JavaEE web programmer and am starting to investigate the principles of REST for future web applications, but I can't figure out how to do usable logins. For a Web API it makes sense, but what about end user facing web applications? I have looked into the HTTP Basic/Digest Authentication but that only produces an ugly dialog box. Anyone have any ideas?
That really depends on how you approach form-based login.
The way it's defined in J2EE spec, login page is only shown to the (yet authenticated) user when s/he tries to access a protected resource; it's not (or should not be) accessible by itself. In that scenario login page does not have to be governed by REST principles as it's not a "resource" by itself. In other words, the workflow is:
User tries to GET REST url, '/products/0332425'
S/he is redirected to '/login', POSTs his credentials, is redirected back (as GET) to the original page ('/products/0332425')
Subsequent attempts to get to '/login' result in error (403?) or redirect to "root".
If that does not work for you and you need to have your login form available on multiple pages , treat it as part of the page and its submission as you would any other POST.

Categories

Resources