I have a jsp page having a 'submit' option for input.On clicking it i want to update the value of a table called tbIndividual.What can be the best approach to do it?
On jsp page i have somthing like this :
User Name : <%=rs.getString(2)%>
First Name : <%=rs.getString(4)%>
Last Name : <%=rs.getString(5)%>
Email Id : <%=rs.getString(6)%>
Contact : <%=rs.getString(7)%>
<input type="submit" value="ADD"></input>
And now i want to update the value of status of that particular individual from 'NO' to 'WAIT' state.On click of this submit button.
Is making new servlet for this task a good option or doing the code in jsp a better one ?
If i need to make a new servlet then what will be the code for it on jsp page .?Please help.
If you are trying to learn servlet with this project then you should create a separate servlet where you will perform your business logic (e.g addition of element in Db) and jsp should be kept away from business logic because role of jsp is to render the output not to produce the output.
If this is a project for production purposes, then you should ( IMO you must ) opt some web framework. As framework will reduce your effort, headache and increase productivity.
First of all, there are certain things you need to understand while developing web applications in Java. I have a few recommendations and inputs
Please don't use Scriptlets. Scriptlets are deprecated and they make your code clumsy and the maintainance will be hard. Use JSTL
You need to create a form in your html to have a set of variables to push them to the server on clicking submit button. The form will have an action attribute which contains the URL where the request should be sent
Create a Servlet and map with the action URL and write the doPost method which can receive the form parameters and do the business logic whatever changing the status from NO to WAIT or anything else
Please take a note that you need to have Session variables in order to have the store the data in between requests from the same client. eg browser.
Is making new servlet for this task a good option or doing the code in jsp a better one ?
Writing a new servlet is a good option, than doing the business logic in jsp page. jsp is meant for presentation, just view. They shouldn't be used to perform business logic
If i need to make a new servlet then what will be the code for it on jsp page .?
JSP should just have all the necessary html elements and attributes like form, action attribute etc.. to post the parameters in the request to the action URL. Please note the method attribute of form. You should use HTTP POST method for posting form parameters to the server
Note : Finally, Writing Servlets are also NOT recommended. Instead, you should opt for webframeworks like Spring MVC , Struts etc. Please go through the link to understand about web frameworks answered by #BaluC
Hope this clarifies.
Related
i work on JSP and i want to call a java method(Function) on Click on a html button without using<script></script>.how?
i try to write this code:
<button onclick="<%po.killThread();%>">
<font size="4">Kill</font>
</button>
but it doesn't work... so please help me.
thanks
You're misunderstanding how server-side programming works. When you load that page, the webserver will get to the line <button onclick="<%po.killThread();%>"> and will immediately parse and execute the JSP snippet, in your case po.killThread(), and replace everything between the <% and %> with the return value of that method, if any. And all these happens on server side, before client receives any thing. (Note that this will only happen if that page is not already been loaded and compiled into a Servlet by the server.)
Thus, the HTML that client receives, will be something like, <button onclick="some return value or nothing">, which means that nothing will happen when you press the button. If you want to execute further JSP commands on the button press you will need to make a new request to the server - for example, by redirecting the page.
This will call the function killThread when you open the website.
Try to redirect to another jsp which calls the function.
this will not run at all because after the jsp page is compiled it will return the po.killThread() value but will not call this method
You can see this by viewing the page source
JSP is a server-side technology. Did I say server-side?
In order to understand how JSP works and to clear any misconception, JavaRanch Journal (Vol. 4, No. 2): The Secret Life of JavaServer Pages is a very good read.
An excerpt from the same,
JSP is a templating technology best-suited to the delivery of dynamic text documents in a format that is white-space agnostic.
Template text within a JSP page (which is anything that is not a dynamic element), to include all white-space and line terminators, becomes part of the final document.
All dynamic elements in a JSP are interpreted on the server and once the document is sent to the client, no further dynamic interaction is possible (short of requesting the same or another document).
If you are using JSPs, then to perform some method calles, you will have to write a servlet and then call the method in doPost or doGet method of servlet.
On the other hand, if you want to make things simpler, use JSF framework which will help you achieve your objective as JSF supports event handling.
I have a jsp page which contains a form which calls a servlet, after inserting data into the database by a servlet hot to display successs alert to the user on the page?
Thanks in advance for answering.
Either you call the servlet asynchronously with AJAX and have a success callback function (see jQuery example: http://api.jquery.com/category/ajax/ )
Or you do it the old fashioned way with a synchronous Post which loads a success page, or the same page with for example a query parameter that states that you have succeed. This could then be used to activate a script block in your JSP (or whatever template language is your flavour).
You can use a javascript alert box. See http://www.w3schools.com/js/js_popup.asp
I have a very simple Java MVC web application and am using a servlet to handle form validation. If the form is validated, the request is forwarded to the appropriate view. However, if the form fails validation, the request is forwarded back to the form, which then displays the appropriate error message(s).
My question is this -- what is the most efficient way to re-populate all of the form fields with the data that was originally entered in the form by the user?
I am not using an MVC framework, just simple HttpServlets as the controller with .jsp as the view.
The easiest and probably least effort is to just use
<input name="foo" type="text" value="${param.foo}"/>
This should default to "" when the user first visits the form.
A little more can be done to create a custom tag which binds to the request. However this is probably not the solution you were looking for.
Edit: You may want to use <c:out value="${param.foo}"/> to protect against XSS attack.
Pass the fields back to the jsp as part of the request object. request.setAttribute(..)
Use those attributes to set the form fields.
we have a classic JSP + Servlets application and would like to show "Content is loading" sort of message when data in the page takes a while to load.
Is there an easy way to do this via JS?
Scenario:
Page1 (a.jsp) -> select drop downs ->
click search //data is sent back to
server for db
URL changes to (b.jsp), white page is shown, then data load after 30ish seconds
for those 30 seconds I want to show a spinner or some message.
adding ajax or jquery would require a design change which we can not do right now. Though the application already uses jQuery for other stuff but b.jsp is making the DB call from that page...
calling DB in jsp would be very much frowned upon. given the premise of the question, you could
//b.jsp
<div id="msg">data is loading...</div>
<%
out.flush();
db.performanLengthJob();
%>
<script> $("msg").remove(); </script>
<p>Data is loaded!</p>
AJAX is the way to do it. You'll need something on the server side to help you keep track of progress.
Load your data (in b.jsp) with ajax request.
Make a JS function which starts on load, let it show your message ('30 seconds left') and then let it perform ajax request to load necessary data.
I recommend you to use some js-framework, like jQuery, it'll make things much simplier.
In order to handle ajax-request on the server-side you'll need to create one more servlet and map it to some url, like your_app_name/ajaxsupport. This servlet should return data in some convenient format (it can be plain text, or xml, or JSON or whatever else). On the client you'll process received data and show it.
A quick solution can be to use onbeforeunload JS event of your base page html body s.g. like
<body onbeforeunload="$("yourComponent").show();">
How can I use Servlets to access the HTML uses of having JSP without having to have all my client-facing pages called *.jsp?
I would rather do this than using all the response.write() stuff because I think it is easier to read and maintain when it is all clean "HTML".
Is this is fair assesment?
EDIT: What I'm going for is having the Servlets output things to the screen without having to redirect to a .jsp file.
In this way, I could write all the JSP stuff, but when it comes time to display it, the page the URL the user sees is essentially, "http://blah.com/posts/post-id" which is the address of the servlet and not "http://blah.com/posts.jsp?pos=post-id".
But I would still write all presentation logic in an external .jsp.
Just hide the JSP away in /WEB-INF folder so that noone can access it directly and create a servlet which forwards the request to this JSP file. Don't do a redirect, else you will see the new URL being reflected in the address bar. E.g.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String postId = request.getPathInfo();
// Do your business thing here. Any results can be placed in request scope. E.g.
request.setAttribute("post", post); // post is a bean containing information you'd like to display in JSP.
// Then forward request to JSP file.
request.getRequestDispatcher("/WEB-INF/posts.jsp").forward(request, response);
}
Map this servlet on an url-pattern of /posts/*.
In the /WEB-INF/posts.jsp make use of taglibs to control page flow and EL to access the data. E.g.
<h2>${post.title}</h2>
<p><fmt:formatDate value="${post.date}" type="date" /> - ${post.message}</p>
Finally just invoke the servlet by http://example.com/posts/postid. The /postid part will be available by HttpServletRequest#getPathInfo(). You need to parse the value yourself and do the business thing with it.
I'm not entirely sure what you're asking here. You can ge servlets themselves to write HTML, but that's not clean at all.
An alternative is to get your servlets to create HTML via a templating engine, such as Velocity or Freemarker. The syntax in the templates may be cleaner for your particular application, if less fully featured.
Back in ancient times (think '98...) this was called a "Model 2 architecture": a servlet received the request, processed it, and handed the request over to a JSP page that handled the view.
See this article for one example of how this is done, or simply search for "JSP Model 2".
Edit: for that, you can use RequestDispatcher.include() instead of forward() as described in the previous article. The rest should still be applicable.
If I understand correctly you want to hide *.jsp extension from user, right?
In that case when your Servlet redirects to a jsp page have it do this:
RequestDispatcher disp = request.getRequestDispatcher("hidden.jsp");
disp.forward(request,response);
By using Request Dispatcher instead of redirect you "hide" your .jsp extension behind the servlet name. However in case your JSP page redirects to another JSP page this won't work.
If you want the .jsp file to be visible use response.encodeURL or response.sendRedirect
I think you're looking for the Front Controller Pattern - this is the basis of "JSP Model 2" web apps (as #andri mentioned) and pretty much all the (hundreds?) of Java web frameworks.