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
Related
I am Using Eclipse dynamic web project.
I have 4 files
servlet-> Loginservlet.java
[has doGet() method which calls ConnectionUtil.java and fetches json data from it]
ConnectionUtil.java
[After checking connection to db calls DataDao.java and fetches json data from it which it later gets form database ]
DataDao.java
[fetches data from database and returns it as json in
//List<Map<String,Object>>
format ]
index.jsp
[index.jsp needs that json data from the servlet named Loginservlet.java.]
So If i need that json data from LoginServlet.java i had to
run the servlet first
then my jsp has to call it to get the data.
My question is How can i implement it?
You are getting the data that your JSP needs. Here is Example Flow 1:
User visits yourapp.com/login
Loginservlet is mapped to /login so it gets called
Loginservlet makes use of the other classes to get the data and puts it on the request using request.setAttribute("data",data)
Loginservlet then forwards to index.jsp
index.jsp makes use of the data for example by making it available to JavaScript by wrting it out between <script> tags
If you already had in mind to use Loginservlet to do the actual logging in of the user, then you might want to have a seperate servlet for fetching the data - maybe called WelcomeServlet mapped to '/' so it loads by default when people hit the app.
Of course there is another way, Example Flow 2:
User visits index.jsp
index.jsp contains Javascript to make an AJAX call to a servlet
The servlet gets the data and writes it directly to the response
A handler on index.jsp receives the data and does something with it.
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.
I have a JSP html based form. I want to do the post through my java code, i.e HttpURLConnection, OutputStreamWriter etc..
How do I make my form action process point towards my java class that is to do this post?
My aim is to have a:
JSP page that has a form,
Submit form
Processing and response called out my java code that will generate a response (this is working fine)
Response returned to the calling JSP page.
Really my issue is submitting the form, and send the processing to my java class?
Ok, here is an easy example on how to use servlet. What you actually need is a Servlet. A servlet is actually a java class. Check this example, replace form.html with your jsp and let me know if you have issues. This is a brief description of what a servlet is.
I've created a form and I need the user to enter some info then upload a picture.
So lets say I have something like this:
<form method="post" enctype="multipart/form-data" action="some servlet/filter">
<input type="file" name="logo">
</form>
I need to use java to change that data to a byte[] then to blob so I can insert to a table.
How do I get the data from this form?
A bit of info on this:
I created the page using javascript, then when submitted it will call a java function to handle the data from the form. It seems that when I submit the form the data for the file is not passed over to the servlet.
So far the few methods I've tried have returned null and I'm outta ideas...
Any examples/help is greatly appreciated!
I think the main question I have is where is the file data stored before the java file start working on it? Is a special global variable holding the data or something like that?
You can use the Apache Commons FileUpload library.
The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.
If I understood you right, you need something similar to this example:
http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
I used the following tutorial one year ago:
http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html
It looks like it's a lot, but it's actually easy to understand, and it has a lot of good information.
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.