I have the following method in my Servlet.
private String process(HttpServletRequest arg0, HttpServletResponse arg1) {
return ("a key");
}
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
process(arg0, arg1);
}
In web.xml the following code is added
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>iusa.ubicacel.actions.map.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
In inicio.jsp the following is added
<script type="text/javascript" src="<%=request.getContextPath()%>/MyServlet"></script>
In the src tag above I want to add google map api url(which I will retrieve from the database in the servlet) from the process method in the MyServlet.I understand from the comments that my approach is wrong.Can anyone please tell me how to do it correctly with only this jsp and servlet.
A best practice for writing servlets with JSP is to follow the MVC pattern: your servlet will be the controller, the JSP is the view, while the model will consist of your domain objects which are passed from the servlet to the JSP page via request attributes.
I don't think that what you have right now is entirely wrong. But it's only suited for a special scenario where you will need to generate all your javascript code from a servlet (and this is hardly ever a true requirement). Assuming though that this is a true requirement in your case (perhaps you read the whole javascript content from a database), it's OK to define a servlet that renders the JS content (and perhaps map it as /main.js or something, to make the dynamic generation transparent for the JSP page).
Most likely, you need only a bunch of small items to be dynamically generated at runtime (like your google maps url, API key or whatever you store in your database). If this is the case, then your JavaScript code can be statically defined in a .js file and allow initialization with some constructor arguments (or whatever).
In this setup, your servlet will read the url from the database, will pass it to the view by calling request.setAttribute("googleMapsUrl", url) and then call requestDispatcher.forward(...) to pass control to the JSP.
In the JSP, you'll now need to include your static script with src and then you can have another script tag to initialize your code based on dynamic values bound to your request:
<c:url value="/static.js" var="scriptUrl"/>
<script type="text/javascript" src="${scriptUrl}"></script>
<script type="text/javascript">
// let's assume your static script defines an object called `MyGoogleMapsDriver`...
var googleMapsDriver = new MyGoogleMapsDriver('${googleMapsUrl}');
</script>
I hope this helps.
You dont need that, you should access to data so :
Save data from Servlet -> request.setAttribute("MyObject", data);
After in JSP you load data that need -> request.getAttribute("MyObject");
Sorry my english,
good luck.
Note: I don't recommend to do this, but this is the direct answer to the question. For more information, take a look at the comments.
If you just 'want to add the string returned from the process method' you need to do the following:
Make your method public and static.
Then write the following scriptlet: <%= MyServletName.process(request, response); %>. This will output the result of the process method.
At the end you will have the following:
<script src="<%= MyServletName.process(request, response); %>"></script>
The variables request and response are available in this scope.
Important: The thing you are trying to achieve this way looks like a bad design. For various reason commented in this answer. Check the comments made by #LuiggiMendoza and #DaveNewton.
Here are some points to take in account:
Writing scriplet is easy but is not recommended by any mean. See: How to avoid Java code in JSP files?.
Invoking a Servlet method from JSP is bad design. Servlet methods are designed to handle HTTP methods. They were not designed to handle specific situation.
The thing you are trying to do is an anti-pattern, you are not separating concerns. A JSP page should be a view that structure and render information. That information should be pre-processed.
Related
To make a request to Servlet, I need to use mapping inside XML file or add annotation for given Servlet. But why I am not required to do the same for JSP files as well? I will give examples.
How does this work?
index.html:
<html><body>
<form action="result.jsp">
<button>go</button>
</form>
</body></html>
result.jsp:
<html><body>
hello
</body></html>
Notice I didn't have to use any XML mappings nor annotations. It just "finds" it.
But how this doesn't work?
index.html:
<html><body>
<form action="com.example.MyServlet">
<button>go</button>
</form>
</body></html>
com.example.MyServlet:
public class MyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
resp.setContentType("text/html");
pw.println("hello");
}
}
Here, I get error: The requested resource [/TestProject/com.example.MyServlet] is not available. How? How come I didn't need to use XML, nor annotations for JSP, but I had for Servlet? Shouldn't they work the same way, as JSP eventually turns to Servlet. So why is there different behavior? I know I am missing something, I just don't know what...
Why I need mapping or annotation for Servlet, but not for JSP?
As pointed out in the comment above from #SotiriosDelimanolis, that's not what actually happens. A JSP is eventually turned into a servlet and behaves like any other servlet you define on your own. And when you define a servlet you also need to add a URL mapping so that an URL path is resolved to a servlet that can respond to a request made for that URL.
The only difference is that for JSP files this mapping is done implicitly by the servlet container. For the servlets you define, you obviously need to define your own mapping because the server can't know what you want to do with the servlet in your own application.
The specifications says the following (emphasis mine):
A web component is either a servlet or a JSP page. The servlet element in a web.xml deployment descriptor is used to describe both types of web components. JSP page components are defined implicitly in the deployment descriptor through the use of an implicit .jsp extension mapping, or explicitly through the use of a jsp-group element.
and
[...] JSP page translated into an implementation class plus deployment information. The deployment information indicates support classes needed and the mapping between the original URL path to the JSP page and the URL for the JSP page implementation class for that page.
So basically, your JSP is translated into a servlet, and a mapping is created from your original JSP page location path to the servlet thus generated.
The JSP is not actually executed. What's executed is the servlet generated from the JSP. You have to realize that JSPs are provided for convenience. If you want to generate HTML from a servlet you have to do a whole bunch of out.write("<html>"); out.write("\r\n"); and so on, for your entire HTML page. It's not only very error prone, but you will go insane doing so. Thus, the option of providing an JSP combined with the things done behind the scene to make it all work.
I have a java class which performs some operations on files. Since the java code is huge I don't want to write this code in jsp. I want to call the methods in jsp whenever required.
Please tell me the path where I need to keep this file. Also some example code how to use it would be helpful.
In the servlet (which runs before the JSP):
Person p = new Person(); // instantiate business object
p.init(...); // init it or something
request.setAttribute("person", p); // make it available to the template as 'person'
In the template you can use this:
your age is: ${person.age} <%-- calls person.getAge() --%>
I think the question is, how do you make Java code available to a JSP? You would make it available like any other Java code, which means it needs to be compiled into a .class file and put on the classpath.
In web applications, this means the class file must exist under WEB-INF/classes in the application's .war file or directory, in the usual directory structure matching its package. So, compile and deploy this code along with all of your other application Java code, and it should be in the right place.
Note you will need to import your class in the JSP, or use the fully-qualified class name, but otherwise you can write whatever Java code you like using the <% %> syntax.
You could also declare a method in some other utility JSP, using <%! %> syntax (note the !), import the JSP, and then call the method declared in such a block. This is bad style though.
Depending on the kind of action you'd like to call, there you normally use taglibs, EL functions or servlets for. Java code really, really doesn't belong in JSP files, but in Java classes.
If you want to preprocess a request, use the Servlet doGet() method. E.g.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request here.
doYourThingHere();
// And forward to JSP to display data.
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to postprocess a request after some form submit, use the Servlet doPost() method instead.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request here.
doYourThingHere();
// And forward to JSP to display results.
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to control the page flow and/or HTML output, use a taglib like JSTL core taglib or create custom tags.
If you want to execute static/helper functions, use EL functions like JSTL fn taglib or create custom functions.
Although I'll not advice you to do any java calls in JSP, you can do this inside your JSP:
<%
//Your java code here (like you do in normal java class file.
%>
<!-- HTML/JSP tags here -->
In case you're wondering, the <% ... %> section is called scriptlet :-)
Actually, jsp is not the right place to 'performs some operations on files'. Did you hear about MVC pattern?
If you still interested in calling java method from jsp you can do it, for example:
1. <% MyUtils.performOperation("delete") %> (scriptlet)
2. <my-utils:perform operation="delete"/> (custom tag)
Anyway I recomend you to google about scriptlets, jsp custom tags and MVC pattern.
Best Regards, Gedevan
I want to develop a webapplication using Java. But I am quite confused what all these different technologies are and how they work together:
HTTP
HTML
CSS
Javascript
jQuery
Web Container
Servlets
JSP
JSTL
Expression Language (EL)
There is a huge amount of resources which can be found on the web regarding these topics, and each of them looks like you need to read several books to understand them. Can you explain these technologies so that I have a basic understanding of them when starting to develop a webapplication?
Note that the goal of this explanation is to give a general understanding, not to examine all the details of each topic. Experienced users will surely find points which seem to be "too general", but let's don't confuse new users. Links for further reading are provided in each topic.
Let's start with the fundamental basics. You need to know how a webpage comes to your computer in order to understand all the following technologies.
HTTP
HTTP stands for Hyper Text Transfer Protocol. It describes how the browser communicates with the webservers in order to retrieve their content (webpages). Webpages are stored on servers, and the browser needs a way to tell a server which webpage it would like to get. The server, on the other hand, needs to tell the browser if the requested resource was found or not and send this information to the browser.
The browser sends a request to the server. The request consists of several parts:
The URL, e.g. "https://stackoverflow.com/questions/ask", so the server knows which page to deliver.
The HTTP method. Most common are get, which indicates that the browser wants to retrieve information (e.g. a single page, or a websearch), and post, which indicates that the browser pushes some information to the webserver, like a forum post. Post usually changes something on the server (like the new post in a forum), while get does not.
Request body, which can contain for example the text of a textbox, an image to be uploaded, etc.
The server sends back a response, which is the answer of the browser's request. It consists of:
A HTTP status code. This is a three-digit-number which shows the result of the request. Most common are OK (2xx), REDIRECTION (3xx), CLIENT ERROR (4xx) and SERVER ERROR (5xx). Redirection status codes are the best way to redirect the browser to another page.
Response body, this contains the webpage (if any).
HTML
HTML stands for Hyper Text Markup Language and presents the content. HTML text is sent from the server to the client (which is, the browser) and is rendered by the browser to display it to the user. Example HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>My first webpage</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Since HTML has improved over the years, it is important that the first line of each HTML page contains the DOCTYPE declaration. It tells the browser how the different tags (like <p>) should be rendered. The rendering process is done by the browser. Everything, that is done by the browser on the local computer, is called client-side. Remember that term!
CSS
Means Cascading Style Sheets. This adds style to a webpage, like colors, font sizes, positions of elements, etc. CSS definitions are often kept in separate files to improve maintainability. Rendering of styles is also done client-side.
JavaScript
No, this has nothing to do with Java. Repeat: nothing. It is a totally different programming language that is executed by the browser on client-side. With JavaScript, you can include programming logic to your webpage and do things like:
Validating user inputs
Fancy slideshows
Even programming games!
You need to be aware of that JavaScript can be turned off in the browser, and then no JavaScript code will be executed. So you should not rely on the availability of JavaScript for your webapplication (except you have to, like for a game). JavaScript can be abused for things like redirection (where you should use HTTP status codes) or styling of elements (use CSS for that). So before doing something with Javascript, check if it is possible somehow else. Even dropdown menus are possible with only HTML and CSS!
jQuery
jQuery is nothing else than a library written in JavaScript. It becomes handy when you want to make your JavaScript cross-browser compatible, because different browsers have some minor differences in their JavaScript implementations. It is also useful for selecting certain elements of a page, effects, etc. It is still JavaScript, so it runs on client-side.
Web Container
This is a software which is located on your server and runs on server-side. Your webapplications are usually placed in a web container. It is the interface between client requests and your webapplication and does several things to make programming webapplications more comfortable. For example, Apache Tomcat is a web container.
Servlets
Now we get to the Java world. Servlets are part of your webapplication which is located on a server inside a web container, they run on server-side. Servlets are Java classes which process the request from the client and send back a response. A typical HTTP Servlet looks like this:
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML>");
out.println("<html>");
out.println("<head>");
out.println("<title>Hi</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Hello World!</p>");
out.println("</body>");
out.println("</html>");
}
}
HttpServlet classes have several doXxx methods, one for each HTTP method, which can be overridden by the developer. Here, doGet is overridden, which means that this code is executed when a GET request is sent to this servlet. This method gets the request and response as parameters, HttpServletRequest and HttpServletResponse.
To make this Servlet accessible via a URL, the web.xml has to be configured:
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.example.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Now, a client can make a request to our servlet using GET and /hello as URL. For example, if our webapplication runs on www.example.com, correct URL to be used would be http://www.example.com/hello using GET.
JSP
Stands for Java Server Pages. As you have seen, using Servlets to send responses to the client is rather unhandy. Some clever guys had the idea: "What if we could just add Java code to HTML pages?" Well, and that's what JSP is:
<!DOCTYPE HTML>
<html>
<head>
<title>Hello JSP</title>
</head>
<body>
<%
for(int i=0; i<10; i++){
out.print("Loop number " + i);
}
%>
</body>
</html>
In fact, JSPs are translated to Java Servlet code (by the web container) and compiled. Really! It's no magic. That means, they are nothing else than Servlets! This is the equivalent Servlet code for the above JSP:
public class ServletAbc extends GenericServlet {
public void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException{
PrintWriter out = res.getWriter();
out.println("<!DOCTYPE HTML>");
out.println("<html>");
out.println("<head>");
out.println("<title>Hello JSP</title>");
out.println("</head>");
out.println("<body>");
for(int i=0; i<10; i++){
out.print("Loop number " + i);
}
out.println("</body>");
out.println("</html>");
}
}
You see, all Java code is processed on server-side before the response is sent to the client.
JSTL
Stands for Java Standard Tag Library. Like the name says, it is a library which you need to include before you can use it.
JSPs with Java code are still not the best solution. It becomes very unreadable as the size of the pages grows, reduces maintainability and is difficult to read. So, what if we could just use additional tags to implement page flow, loops etc. and let Java classes do the programming logic? Welcome using tag libraries!
There are many tag libraries out there, and JSTL is the "basic" one, providing core functionality. This includes if/else constructs, loops, etc. It is included in JSPs, translated and compiled to Servlets and therefore runs on server-side.
EL
Means Expression Language and is used to evaluate expressions and to access values of Java objects you have created in Java classes. Usually, you combine Servlets, JSP, JSTL and Expression language:
A client request comes to a Servlet. The Servlet does some programming logic (like reading data from a Database) and stores some Java objects in the request. After that, it forwards the request to another resource on the server, like a JSP. Forwarding happens inside the webapplication and is not a redirect.
The JSP uses EL to access the Java objects in the request, displays them and sends the response to the client.
For example, this is your Servlet:
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// access databases, do calculations etc. here
String hello = "Hello world!";
String someBoolean = true;
request.setAttribute("helloObject", hello);
request.setAttribute("myBoolean", hello);
RequestDispatcher dispatcher = request.getRequestDispatcher("/result.jsp);
dispatcher.forward(request, response);
}
}
And the result.jsp:
<!DOCTYPE HTML>
<html xmlns:c="http://java.sun.com/jsp/jstl/core">
<head>
<title>Hello EL</title>
</head>
<body>
${helloObject}
<c:if test="${myBoolean}">
The expression is true.
</c:if>
</body>
</html>
This will output Hello world! The expression is true..
Things to keep in mind
I think I have shown clear enough what runs on server-side and what runs on client-side. Don't mix them up.
Always use the right tool for the right job. HTML for content, CSS for layout and style, Javascript for client-side programming logic. Don't rely on Javascript if you don't need it, some users have it turned off.
Most other technologies, like JSF, are built on top of existing technologies. Find out on what they are built on to understand where they are running (client, server) and what they are supposed to do.
Is there any possible way to send the html form data to java application without using php and asp stuff?
I know we can do this using php and do it before but can i do it directly?
I had used php in my previous app in which user sends his data to php form that saves it into the data base but now i want to directly get the data from the html form.PLease any idea for that?
Maybe you could consider using Java Servlets and JSP for web-based data processing ?
use the html form action attribute to specify an endpoint that will hit a java servlet running inside of a servlet container.
To handle the request in your java class, implement the HttpServlet interface.
http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html
If you are posting from a form, them most likely you will want to implement doPost. Or you can implement service as a catch-all
Example:
<form action="/path/to/Servlet" method="post">
<input type="text" name="foo"/>
</form>
....
doPost(HttpServletRequest request, HttpServletResponse respnose) {
// set String foo to the form element named "foo"
String foo = request.getParameter("foo");
// now do whatever you need to w/ foo
}
Try Tomcat with Java Servlets. You need to:
write a class that extends HttpServlet
override the "doPost(HttpServletRequest, HttpServletResponse)" or "doGet(...)" methods
write a web.xml file mapping the web page URL to the servlet handling the request
compile and bundle everything together as required.
It'll take a little doing to get everything in the right place but it's not too hard. See the Tomcat documentation for further details. Good luck.
You can send the data by using jsp or by sending it in a link like www.google.com?q=usa
and parse it on other side
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.