servlets connectivity & running on tomcat - java

How can I use this path: "file:///E:/apache-tomcat-7.0.10/webapps/examples/WEB-INF/match.html" ? Is this correct?
This is my html file:
<html>
<form method=post action="../classes/match1">
<body bgcolor="powderblue">
<center><h1>MATCH</h1>
<hr/>
MATCH NO <input type="text" name="op1"/><br/><pre>
DATE <input type="text" name="op2"/><br/><pre>
CITY <input type="text" name="op3"/><br/><pre>
TEAM1 <input type="text" name="op4"/><br/><pre>
TEAM2 <input type="text" name="op5"/><br/><pre>
STADIUM <input type="text" name="op6"/><br/><pre>
WINNER <input type="text" name="op7"/><br/><pre>
MAN OF THE MATCH <input type="text" name="op8"/><br/><pre>
<input type="submit" value="submit"/>&nbsp
<input type="reset" value="reset"/>
</body>
</html>
My servlet code:
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.sql.Date.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class match1 extends HttpServlet {
Connection con;
PreparedStatement pst;
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException {
try {
PrintWriter out=res.getWriter();
con=null;
pst=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:odbc:gan","scott","tiger");
int count=0;
String op1=req.getParameter("op1");
String op2=req.getParameter("op2");
String op3=req.getParameter("op3");
String op4=req.getParameter("op4");
String op5=req.getParameter("op5");
String op6=req.getParameter("op6");
String op7=req.getParameter("op7");
String op8=req.getParameter("op8");
pst=con.prepareStatement("insert into matchdetails values(?,?,?,?,?,?,?,?)");
pst.setString(1,op1);
pst.setString(2,op2);
pst.setString(3,op3);
pst.setString(4,op4);
pst.setString(5,op5);
pst.setString(6,op6);
pst.setString(7,op7);
pst.setString(8,op8);
out.println("<html><center><body>matched</body></center></html>");
int count1=pst.executeUpdate();
if(count1==0) {
out.println("<html><center><body>ENTER ALL FIELD VALUES</body></center></html>");
} else {
out.println("<html><center><body>INSERTION SUCCESFUL</body></center></html>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con!=null) con.close();
} catch(Exception e) {
System.out.println("error");
}
}
}
}

How can I use this path: "file:///E:/apache-tomcat-7.0.10/webapps/examples/WEB-INF/match.html" ? Is this correct?
You mean, how to access it by a webbrowser? No, that path is not correct. Tomcat listens on HTTP requests only. When started properly, it by default listens on http://localhost:8080. All webapps get their own context name which defaults to the webapp folder name. So your webapp is accessible by http://localhost:8080/examples. However, files in /WEB-INF folder are not directly accessible. You need to move the match.html one level up, in the /examples folder. Then you'll be able to access it by http://localhost:8080/examples/match.html.
Unrelated to the concrete problem, declaring connection and statement as instance variable of the servlet is a poor practice. This is not threadsafe. You need to declare them inside the method block, right before the try statement. Your HTML has also some syntax errors. Use http://validator.w3.org to learn about them. Finally, emitting raw HTML in servlets is also a poor practice, there you normally use JSPs for. But maybe you're currently just learning. Just to let you know :) Already using preparedstatements and closing the connection in finally is very good for a starter.
As to learning JSP/Servlets, I'd suggest to read our info/wiki pages as well.
JSP info page
Servlets info page

First, your html need to be a little
cleaner (see below).
Second, if you
want match.html, don't use match1
in the form action.
Third, put the
match.html file under the war
folder, not web-inf.
Fourth, you
will need to set up the web.xml
configuration file.
I did not even look yet at the servlet class, but I would suggest first to test some System.out.println() output to make sure it is even executed.
<html>
<body bgcolor="powderblue">
<center>
<h1>MATCH</h1>
<form method="post" action="/match.html">
<pre>MATCH NO <input type="text" name="op1"/></pre>
<pre>DATE <input type="text" name="op2"/></pre>
<pre>CITY <input type="text" name="op3"/></pre>
<pre>TEAM1 <input type="text" name="op4"/></pre>
<pre>TEAM2 <input type="text" name="op5"/></pre>
<pre>STADIUM <input type="text" name="op6"/></pre>
<pre>WINNER <input type="text" name="op7"/></pre>
<pre>MAN OF THE MATCH <input type="text" name="op8"/></pre>
<pre><input type="submit" value="submit"/></pre>
<input type="reset" value="reset"/>
</form>
</center>
</body>
</html>

Related

Open mutiple pdf files in separate tabs

Hi I am trying to open multiple pdf files on a click , I am trying in this way.
Considering user will select multiple options to get pdf files by selecting multiple radio buttons.
<html>
<head>
<title>sendRedirect Program using Servlet</title>
</head>
<body>
<form name="pdf" target="_blank" method="get" action="http://localhost:8080/SendRedirectProg/sr">
<table border="1" width="500">
<tr>
<td>Select PDF:</td>
<td><INPUT type="radio" name="pdf" size="20" value="PDF 1">PDF 1
<INPUT type="radio" name="pdf" size="20" value="PDF 2">PDF 2
<INPUT type="radio" name="pdf" size="20" value="PDF 3">PDF 3</td>
</tr>
<tr>
<td><INPUT type="submit" size="20"></td>
</tr>
</form>
</table>
</body> </html>
So consider uer will select all 3 radio buttons and I want to open all these pdf files in different tabs.
I am trying in this way.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SendRedirectProg extends HttpServlet
{
public void method(ActionRequest req, ActionResponse res) throws
{
PrintWriter p=res.getWriter();
res.setContentType("text/plain");
String s=req.getParameter("pdf");
if(s.equals("PDF 1") && s.equals("PDF 2") && s.equals("PDF 3"))
{
res.sendRedirect("http://localhost:8080/SendRedirectProg/DemoPDF1.pdf");
res.sendRedirect("http://localhost:8080/SendRedirectProg/DemoPDF2.pdf");
res.sendRedirect("http://localhost:8080/SendRedirectProg/DemoMCA 3.pdf");
}
}
but it only displays last one, I am understanding use of res.sendRedirect, but still how we can achieve this ?
Any suggestions?
You cannot open 3 tabs in one redirect. What you can do is use jQuery or javascript
Redirect to a page where you write the url's to 3 different hidden div's or generate the script directly
onload of the page, use javascript to open them.
window.open(url1,'_blank');
window.open(url2,'_blank');
window.open(url3,'_blank');
target="_blank" is your answer ;)
<form name="pdf" method="get" target="_blank" action="http://localhost:8080/SendRedirectProg/sr">
More information: http://www.w3schools.com/tags/att_form_target.asp
There is also problem in your java code, you should use only one redirect, accordingly to passed value.
if(s.equals("PDF 1"))
{
res.sendRedirect("http://localhost:8080/SendRedirectProg/DemoPDF1.pdf");
}
if(s.equals("PDF 2"))
{
res.sendRedirect("http://localhost:8080/SendRedirectProg/DemoPDF2.pdf");
}
if(s.equals("PDF 3"))
{
res.sendRedirect("http://localhost:8080/SendRedirectProg/DemoMCA 3.pdf");
}

Call multiple method of Servlet from jsp page

I have a jsp page from where I am calling my servlet named 'InsertServlet'. I have done my required work in the service method in my servlet. I have also created a user define method in my servlet named doSomething(). But now I am being failed to call the method doSomething() from my jsp page. Is it possible to do it or I have to create a single servlet for every single action ?!! Can anyone please help me on this please ???!!! Here are my codes below >>>
my jsp page ###
<form action="IbatisInsertServlet" method="POST">
First Name : <input type="text" name="firstName" value="" /><br/>
Last Name : <input type="text" name="lastName" value="" /><br/>
Salary : <input type="text" name="salary" value="" /><br/>
<input type="submit" value="Enter" /><input type="reset" value="Clear" /><br/>
</form>
my servlet's service method where I have done my work ###
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
...
...
} catch (Exception ex) {
System.out.println("Exception is :: " + ex.getMessage());
} finally {
out.close();
}
}
my servlet's doSomething method which I want to call ###
public void doSomething(){
System.out.println("working");
}
If the doSomething method is going to be called from a JSP (which is really just a servlet) then I suggest that you put this code in a separate class which can be instantiated from the JSP and/or the the servlet. This would assume that the logic ofdoSomething has got nothing to do with the request
The idea of calling a servlet is that you are interfacing through HTTP, so if in some cases (as part of the GET/POST) you want to call doSomething then consider adding a parameter informing the servlet to do this.
E.g
myWebApp/myServlet?action=doSomething
First you have to understand how Servlet Container works!
The whole thing stands on a idea, named "Don't call us, we'll call you" also known as "Inversion of Control".
So when we write a servlet, we simply provides the methods which may be called by the container when needed! As a result the method signatures are predefined for a servlet and its not in your hand to add any method if you want.
So the answer is no, you can not invoke your doSomething() of Servlet from jsp, in a straight way!
Try this example:
html
<form action="IbatisInsertServlet" method="POST">
...
<input type="hidden" value="save" name="cmd"/>
<input type="submit" value="Enter"/>
...
</form>
<form action="IbatisInsertServlet" method="POST">
...
<input type="hidden" value="edit" name="cmd"/>
<input type="submit" value="Edit"/>
...
</form>
servlet
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String cmd = request.getParameter();//<--
if("save".equals(cmd)) {
save();
}
else if("edit".equals(cmd)) {
edit();
}
} catch (Exception ex) {
System.out.println("Exception is :: " + ex.getMessage());
} finally {
out.close();
}
}
private void save() {
...
}
private void edit() {
...
}
If you can extend the JSP page from servlet (subclassing), there may be way. You can post the data to the same jsp page or servlet (based on your needs). You can call the method of the parent class, here it would be the servlet you are extending from.
Your JSP code
<%-- top of the page. extend the servlet --%>
<%# page extends="your.package.IbatisInsertServlet" %>
<form action="IbatisInsertServlet" method="POST">
First Name : <input type="text" name="firstName" value="" /><br/>
Last Name : <input type="text" name="lastName" value="" /><br/>
Salary : <input type="text" name="salary" value="" /><br/>
<input type="submit" value="Enter" /><input type="reset" value="Clear" /><br/>
</form>
<%-- to call the function --%>
<% doSomething() %>
Note that you can leave the action empty if you want to call the same JSP or redirect it to the server. Also note that the JSP servlet and the IbatisInsertServlet will be two separate instances. Make sure you call the super.service(...) as needed.
This should work for you
This is just a complement to ScaryWombat answer.
If you call your method doSomething, it should not be part of a servlet but of another class. This way, you separate the concerns :
servlets (including JSP) manage the interactions with forms, requests, responses, session
other classes do the real job
If you full application if less than 100 lines of code, it not much important, but if it grows, you get smaller classes with less dependances which are easier to write and test.
This domain classes can be instantiated by a servlet (or a JSP) if they do not last longer than a request. If not you should instantiate them in a ServletContextListener, put them in the ServletContext and use them from any servlet of JSP you want.

Maven: Deploying an HTML form page with a Response Java EE that prints results with POST

I have an HTML file that has a form:
<head>
</head>
<body>
<h1>Voter Registration Page</h1>
<p>Please fill out all information below to register as a voter.</p>
<form method = "post" action = "results">
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname" ><br>
Address: <input type="text" id="address" name="address"><br>
City: <input type="text" id="city" name="city"><br>
State: <input type="text" id="state" name="state"><br>
Zip: <input type="text" id="zip"name="zip"><br>
Phone Number: <input type="text" id="phone" name="phone"><br><br>
Affiliation:<br>
<input type="radio" name="affil" value="Democrat">Democrat<br>
<input type="radio" name="affil" value="Green Party">Green Party<br>
<input type="radio" name="affil" value="Liberterian">Liberterian<br>
<input type="radio" name="affil" value="Republican">Republican<br>
<input type="radio" name="affil" value="Unafilliated">Unafiiliated<br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Using Maven and JAVA EE I'm trying to use POST to make a results page when the user clicks Submit on the HTML form:
web.xml
<servlet>
<servlet-name>results</servlet-name>
<servlet-class>controller.Response</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>results</servlet-name>
<url-pattern>/results</url-pattern>
</servlet-mapping>
Current Java Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Response extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>demolet</title></head>");
out.println("<body>");
out.println("<p>First Name:</p>");
out.println("<p>Last Name:</p>");
out.println("<p>Address:</p>");
out.println("<p>Phone:</p>");
out.println("<p>Afiiliation:</p>");
out.println("</body></html>");
out.close();
}
}
However, the main problems I'm having are:
1.I'm trying to figure out is how to pass in the values answered in the HTMl file to the Java file so it can properly write a html file with the results.
2.I'm new to Java servlets and xml so I have a feeling my set up is incorrect somwhere.
If anyone can offer any help for any of these two problems, that would be great. Thanks.
Don't worry about the Maven part for now, I know how to use the command line to set up my project and see results and stuff.
You need to read <form /> field value from request parameter.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException{
PrintWriter out = response.getWriter();
.......
String firstname=request.getParameter("firstname");
out.println("<p>First Name:"+ firstname +"</p>");
.......
}
Your HTML form data can be fetched using the request object:
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
System.out.println((String)paramNames.nextElement());
}
All the data that is submitted as a part of GET/POST will become part of a HttpServletRequest object. You can use the same to fetch the values. Refer javadocs for more details.
It is also good practice not to write HTML in .java files and not to write java in .jsp files.

form values not submitted to the servlet

I am trying to submit the text field value and print it using the servlet. The index.jsp is my main page and I am using jsp:include to include the form which reside in another page which is login.html.
here is the code i have for login.html
<form id="f1" action="ControllerServlet" method="GET">
<p>username
<input class ="text-input" type="text" id="txtusername" />
</p>
<p>
<input type="submit" value="submit" />
</p>
the index.jsp
<div id="col3_content" class="clearfix">
<h1>H1 Heading</h1>
<jsp:include page="login.html"></jsp:include>
</div>
the controller servlet
String usrname = request.getParameter("txtusername").toString();
out.print(usrname);
The problem is this is throwing a null pointer exception. what am I doing wrong here ? any help appreciated. thanks
Please use name not id
<input class ="text-input" type="text" name="txtusername" />
The id is not used to identify the name of the input parameter. The right attribute for the parameter is name, currently you are using an input without a name. So use
<input class ="text-input" type="text" name="txtusername" id="txtusername" />
You need to define name attribute of input tag to get it in Servlet by name.
<input class ="text-input" type="text" id="txtusername" name="txtusername" />
Also make sure you are writing code in doGet or service method of servlet as you have GET as action in form tag.
Code for Login.html
<form action="ControllerServlet" method="GET">
<p>username :
<input type ="text" name="txtusername" /></p>
<p><input type="submit" value="submit" /> </p>
</form>
ControllerServlet.java
public void service(ServletRequest request, ServletResponse response)
{
String username = request.getParameter("txtusername");
PrintWriter out = response.getWriter();
out.println("User Name " + username)
I faced a similar situation, when I checked front end, the form seems to have all the value populated correctly. However, after form.submit, from server side using request.getParameter("the parameter") does not return the value populated. After tuning on the network traffic tab in browser, I see the parameter was there, but there was a typo.
Hopefully could save you some time if same thing happens to you.

Getting going on play framework - what silly mistake am I making here?

So I am starting out using the play framework with Mongo and have an issue with trying to get something working using the simple MVC pattern. I can't see the wood for the trees with this and know the solution is bound to be simple.
I have a user object defined as an entity:
package models;
import play.modules.mongo.MongoEntity;
import play.modules.mongo.MongoModel;
#MongoEntity("users")
public class User extends MongoModel
{
public String username;
public String email;
public String password;
}
And I have a controller with the following two methods in it:
package controllers;
import models.User;
import play.mvc.Controller;
import play.Logger;
public class UserController extends Controller
{
public static void createUser()
{
User user = new User();
render(user);
}
public static void insertUser(User iUser)
{
Logger.info("Paul 1: " + iUser + " :: " + (iUser == null));
}
}
And the routes defined as follows:
POST /insertUser UserController.insertUser
GET /users UserController.createUser
So I have the following page view defined and when I click save, the code in the controller is telling me that the User object is null:
#{extends 'main.html' /}
#{set title:'Create User' /}
<form action="#{UserController.insertUser(user)}" method="POST"/>
Username: <input type="text" value="${user.username}" /><br/>
Password: <input type="text" value="${user.password}" /><br/>
Email: <input type="text" value="${user.email}" /><br/>
<input type="submit" value="Add User" />
</form>
I have tried a ton of permutations on the acton and can't figure out why it is not working. Any ideas? All help is greatly appreciated, I know it is somethign stupid I am missing, it is just what.
I think you're at least missing the name atrributes on the HTML forum input elements, which Play! will use to map the form values to your controller parameter(s). Try the following:
#{extends 'main.html' /}
#{set title:'Create User' /}
<form action="#{UserController.insertUser(user)}" method="POST"/>
Username: <input type="text" name="user.username" value="${user.username}" /><br/>
Password: <input type="text" name="user.password" value="${user.password}" /><br/>
Email: <input type="text" name="user.email" value="${user.email}" /><br/>
<input type="submit" value="Add User" />
</form>
Alternatively, you can use the template #{form} tag to have the templating system generate the form for you. This might also be useful to cross-check the output of the #{form} tag with your own form to see what is different.
Update: you may also have to delete the user parameter in the form action attribute #{UserController.insertUser(user)}, which would then be more like #{UserController.insertUser}.
The solution was to rename the User class to be called UserItem. I expect there is a default User class somewhere in Mongo or Play! that was getting in the way.
Edit: Yes, including the name mappings was also instrumental in the solution although it alone did not resolve the issue. I will upvote it accordingly.

Categories