code doesn't insert the data into the database - java

I am trying a servlet that puts the data into the database:derbi (that comes packed with netbeans). When a user clicks to submit data,the request follows to the FormHandler servlet (given below) If any of the text-field was empty the request follows to another servlet ErrorServlet and if every thing was fine the request follows to the Registered servlet. But before the request follows to the Registered Servlet there is a small code that is written to insert the data into the database (After this code the the user views the success page,that he has been registered).
Now the problem : The user fills all the text fields in the form and clicks submit. When he clicks submit,he sees the success page displaying Registered Successfully . But when i query the databse, i see that the data wasn't submitted to the databse. The rows and columns are empty ! I don't understand the reason for this .
Code for FormHandler.java :
package FormHandler;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.LinkedList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class FormHandler extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
}
#Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
String name = request.getParameter("Name");
String email = request.getParameter("Email");
String password = request.getParameter("Password");
LinkedList list = new LinkedList();
if(name.compareTo("") == 0 || email.compareTo("") == 0 || email.compareTo("") == 0) {
list.add("One or more field's' left blank");
request.setAttribute("ErrorList", list);
RequestDispatcher rd = request.getRequestDispatcher("ErrorServlet.view");
rd.forward(request, response);
} else {
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/MyDatasource");
Connection connection = ds.getConnection();
String sqlStatement = "INSERT INTO INFORMATION VALUES('" + name + "'," + "'" + email + "'," + "'" + password + "')";
PreparedStatement statement = connection.prepareStatement(sqlStatement);
ResultSet result = statement.executeQuery();
}catch(Exception exc) {
System.out.println(exc);
}
request.setAttribute("Data", list);
RequestDispatcher rd = request.getRequestDispatcher("Registered.view");
rd.forward(request, response);
}
}
}
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>FormHandler</servlet-name>
<servlet-class>FormHandler.FormHandler</servlet-class>
</servlet>
<servlet>
<servlet-name>Registered</servlet-name>
<servlet-class>FormHandler.Registered</servlet-class>
</servlet>
<servlet>
<servlet-name>ErrorServlet</servlet-name>
<servlet-class>FormHandler.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormHandler</servlet-name>
<url-pattern>/FormHandler.do</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jdbc/MyDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<servlet-mapping>
<servlet-name>Registered</servlet-name>
<url-pattern>/Registered.view</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ErrorServlet</servlet-name>
<url-pattern>/ErrorServlet.view</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Html File :Code for html file
Note : I have already made a connection to database

I think you are getting somewhere a :
java.sql.SQLException: No ResultSet was produced
because executing your UPDATE query with executeQuery() actually returns no resultset
Use:
statement.executeUpdate();

try the following:
PreparedStatement ps2=null;
ps2 = connection.prepareStatement("INSERT INTO INFORMATION( colname1, colname2,colname3) VALUES(? ,? ,?)");
ps2.setString(1, name);
ps2.setString(2, email);
ps2.setString(3, password);
try {
rs=ps2.executeUpdate();
} catch (SQLException ex) {
// catch if any exception
}

Related

How to set Priority Order of displaying context param parameters on server?

I am trying to get the parameters names in a Servlet Context object from context param elements in an order given in the web.xml file. But on running code on the server, displayed parameter order is not the same as to mention in the web.xml file.
DemoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
ServletContext context=getServletContext();
//we are getting all the initialization parameter from the web.xml file
Enumeration<String> e=context.getInitParameterNames();
while(e.hasMoreElements()) {
String s=e.nextElement();
pw.println("<br>"+context.getInitParameter(s));
}
pw.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Servlet6ServletContextInterface2</display-name>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>DriverName</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>Username</param-name>
<param-value>Pranay Singh</param-value>
</context-param>
<context-param>
<param-name>Password</param-name>
<param-value>abc123</param-value>
</context-param>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Expected Results:
com.mysql.jdbc.Driver Pranay Singh abc123
Actual Results:
Pranay Singh com.mysql.jdbc.Driver abc123
The params are intended to be accessed by their name, so the orders are not guaranteed.
If you really need them in a specific order, you can hard-code the param names (in your own order) into a collection:
List<String> paramNames = Arrays.asList("DriverName", "Username", "Password");
for(String paramName: paramNames) {
pw.println("<br>" + context.getInitParameter(paramName));
}
Or if you want to keep the params dynamic without hard-coding anything, you can at least sort them.
Enumeration<String> e = context.getInitParameterNames();
List<String> paramNames = Collections.list(e);
Collections.sort(paramNames);
for(String paramName: paramNames) {
pw.println("<br>" + context.getInitParameter(paramName));
}

Error in web.xml file when I add context-parameters to it

I am getting an error in web.xml file while adding context parameters to it.
Here is web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<pram-name>ADMIN_PATH</param-name>
<param-value>AdminChatServlet</param-value>
</context-param>
<context-param>
<param-name>ROOMLIST_PATH</param-name>
<param-value>/RoomListServlet</param-value>
</context-param>
<context-param>
<param-name>CHROOM_PATH</param-name>
<param-value>/ChRoomServlet</param-value>
</context-param>
<servlet>
<servlet-name>MainChatServlet</servlet-name>
<servlet-class>MainChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>AdminChatServlet</servlet-name>
<servlet-class>AdminChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RoomListServlet</servlet-name>
<servlet-class>RoomListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChRoomServlet</servlet-name>
<servlet-class>ChRoomServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainChatServlet</servlet-name>
<url-pattern>/MainChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminChatServlet</servlet-name>
<url-pattern>/AdminChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RoomListServlet</servlet-name>
<url-pattern>/RoomListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ChRoomServlet</servlet-name>
<url-pattern>/ChRoomServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
and here is the servlet(MainChatServlet) using those context-parameters:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import com.amir.*;
public class MainChatServlet extends HttpServlet {
String chRoomPath;//="ChRoomServlet.java";
String roomListPath;//="RoomListServlet.java";
String adminChatPath;//="AdminChatServlet.java";
public void init()
{
ServletContext context = getServletConfig().getServletContext();
context.setAttribute("chRoomPath",context.getInitParameter("CHROOM_PATH"));
context.setAttribute("roomListPath",context.getInitParameter("ROOMLIST_PATH"));
context.setAttribute("adminChatPath",context.getInitParameter("ADMINCHAT_PATH"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
chRoomPath = (String)getServletContext().getAttribute("chRoomPath");
roomListPath = (String)getServletContext().getAttribute("roomListpath");
adminChatPath = (String)getServletContext().getAttribute("adminChatPath");
session.setAttribute("chRoomPath",chRoomPath);
session.setAttribute("roomListPath", roomListPath);
session.setAttribute("adminChatPath",adminChatPath);
HashMap hashmap = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chat","root","mysql");
synchronized(getServletContext())
{
hashmap = (HashMap)getServletContext().getAttribute("chatList");
if(hashmap == null)
{
hashmap =new HashMap();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from chatrooms");
while(rs.next())
{
hashmap.put(rs.getString(1),new ChatRoom(rs.getString(1),rs.getString(2),4));
}
rs.close();
getServletContext().setAttribute("roomList", hashmap);
}
}
conn.close();
}
catch(ClassNotFoundException e)
{
System.out.print("Error(Class)");
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print("Error(SQL)");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("chat.jsp");
view.forward(request, response);
}
}
and here is the default-package in which all the .java files(servlets are kept)
Screenshot#1
Why am I getting the error in the web.xml file?
Screenshot#2
EDIT: OR Suggest me any alternate idea if possible.

HTTP Status 500 - Error instantiating servlet class com.marlabs.demo.XMLServlet

I am developing a simple webapp and I am getting the following error when I am registering my users.
HTTP Status 500 - Error instantiating servlet class com.marlabs.demo.XMLServlet
web.xml is as follows
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SimpleServletProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>XMLServlet</servlet-name>
<servlet-class>com.marlabs.demo.XMLServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XMLServlet</servlet-name>
<url-pattern>/XMLServlet</url-pattern>
</servlet-mapping>
</web-app>
My servlet is as follows
package com.marlabs.demo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#SuppressWarnings("serial")
#WebServlet(description = "A simple servlet", urlPatterns = { "/XMLServlet" })
public class XMLServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pout = response.getWriter();
String emailID = request.getParameter("emailID");
String pass = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
HttpSession sess = request.getSession();
ServletContext context = request.getServletContext();
if (emailID != "" && emailID != null) {
sess.setAttribute("savedEmail", emailID);
context.setAttribute("savedEmail", emailID);
}
pout.println("Hello " + fname + "<br/>");
UserDetails user = new UserDetails();
user.setEmailID(emailID);
user.setPass(pass);
user.setFname(fname);
user.setLname(lname);
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
pout.println("Your information is saved!");
}
}

Tomcat: Null Pointer Exception when trying to access web service

I have a dynamic web project that contains a web service. I have exported it as a WAR file and placed it in the webapps directory of tomcat. Tomcat shows that the web app is running. When I attempt to invoke one of the operations of my service, I get the following exception:
java.lang.NullPointerException
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1629)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:461)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:680)
Any idea what this means?
Here's my class the defines the web service:
package webservice;
import java.sql.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.core.MediaType;
#Path("/operations")
public class NotifyWebService {
#Path("/insertNewPatron")
#GET
public String insertNewPatron(#QueryParam("cardNumber")String cardNumber,
#QueryParam("pin") String pin,
#QueryParam("nickname") String nickname,
#QueryParam("deviceID")String deviceID) throws Exception {
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String insertPatronStatement = "INSERT INTO dbo.Patron VALUES ('"+cardNumber+"','"+pin+"','"+nickname+"')";
String insertDeviceOwner = "INSERT INTO dbo.DeviceOwner VALUES ('"+deviceID+"','"+cardNumber+"')";
Statement state = null;
state = c.createStatement();
state.executeUpdate(insertPatronStatement);
state.executeUpdate(insertDeviceOwner);
c.close();
return "true";
}
#Path("/initializeDevice")
#GET
public String initializeDevice( #QueryParam("deviceID")String deviceID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String insertDeviceStatement = "INSERT INTO dbo.Devices VALUES ('"+deviceID+"',1,3,1,3)";
Statement state = c.createStatement();
state.executeUpdate(insertDeviceStatement);
return "true";
}
#Path("/updateDevicePreferences")
#GET
public String updateDevicePreferences(#QueryParam("deviceID") String deviceID,
#QueryParam("dueDateNotice")String dueDateNotice,
#QueryParam("dueDateNoticeAdvance") String dueDateNoticeAdvance,
#QueryParam("holdsNotice") String holdsNotice,
#QueryParam("eventNoticeAdvance")String eventNoticeAdvance) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String updateDeviceStatement = "UPDATE dbo.Devices SET dueDateNotice="+dueDateNotice+", dueDateNoticeAdvance="+dueDateNoticeAdvance
+", holdsNotice="+holdsNotice+", eventNoticeAdvance="+eventNoticeAdvance+" WHERE deviceID='"+deviceID+"'";
Statement state = c.createStatement();
state.executeUpdate(updateDeviceStatement);
return "true";
}
#Path("/removeUser")
#GET
public String removeUser(#QueryParam("cardNumber")String cardNumber) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String removeStatement = "DELETE FROM dbo.Patron WHERE cardNumber='"+cardNumber+"'";
Statement state = c.createStatement();
state.executeUpdate(removeStatement);
return "true";
}
#Path("/addEvent")
#GET
public String addEvent(#QueryParam("deviceID")String deviceID, #QueryParam("eventID")String eventID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String eventStatement = "INSERT INTO dbo.Events VALUES ('"+deviceID+"','"+eventID+"')";
Statement state = c.createStatement();
state.executeUpdate(eventStatement);
return "true";
}
#Path("/removeEvent")
#GET
public String removeEvent(#QueryParam("deviceID")String deviceID, #QueryParam("eventID")String eventID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String eventStatement = "DELETE FROM dbo.Events WHERE deviceID='"+deviceID+"' AND eventID='"+eventID+"'";
Statement state = c.createStatement();
state.executeUpdate(eventStatement);
return "true";
}
#Path("/removeAllEvents")
#GET
public String removeAllEvents(#QueryParam("deviceID")String deviceID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String eventStatement = "DELETE FROM dbo.Events WHERE deviceID='"+deviceID+"'";
Statement state = c.createStatement();
state.executeUpdate(eventStatement);
return "true";
}
}
Here's my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>APNS_WebService</display-name>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Let me know if more information is required!
I believe that the cause of your NPE is the lack of a <servlet-class> element in your <servlet> block. However, deciding what the servlet-class should be raises a bigger problem...
It looks like you have not chosen a JAX-RS framework. See JAX-RS Frameworks for insight on various alternatives.
I am currently using Jersey. A typical web.xml for Jersey might contain:
<servlet>
<servlet-name>WebService</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>webservice</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebService</servlet-name>
<url-pattern>/api/rest/*</url-pattern>
</servlet-mapping>
For many JAX-RS frameworks, the choice of framework will determine what you should enter as the <servlet-class>
Also note that since your root resource is in package webservice, I set the com.sun.jersey.config.property.packages parameter to webservice so Jersey will scan your package for any JAX-RS annotated classes.

Cant deploy WebService that uses MYSQL in Tomcat

This my code for webservice.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package customer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.jws.WebService;
/**
*
* #author Mihir
*/
public class Customer {
String date1;
Format formatter;
Date date = new Date();
public String feedback(String contactno,String comments,String ambience,String service,String
food,String email,String custno,String custname,String storeno,String sno)
{
formatter = new SimpleDateFormat("dd/MM/yy");
date1 = formatter.format(date);
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback","root","root");
Statement stmt = con.createStatement();
String sql = "INSERT INTO fb(contact_no,
date,comments,ambience,service,food,email,cust_no,cust_name,store_no,s_no) " +
"VALUES ('"+contactno+"',
'"+date1+"','"+comments+"','"+ambience+"','"+service+"','"+food+"','"+email+"','"+custno+"',
'"+custname+"','"+storeno+"','"+sno+"')";
stmt.execute(sql);
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Now this is what I am trying to do.
Creating folder in webapps in Tomcat with name customer_customer.
Inside that two more folder - WEB-INF META-INF
Inside META_INF context.xml with content-
Inside WEB-INF
4.a. classes/customer/Customer.class
4b. lib folder with jar -
I. webservices-api.jar
II. webservices-extra.jar
III.webservices--extra-api.jar
IV. webservices-rt.jar
V. webservices-tools.jar
VI. mysql-connector-java-5.1.18-bin.jar
4c. web.xml -
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Customer</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Customer</servlet-name>
<url-pattern>/feedback</url-pattern>
</servlet-mapping>
</web-app>
4d. sun-jaxws.xml
<?xml version="1.0" encoding="UTF-8"?>
<endpoints version="2.0" xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
<endpoint implementation="ws.Customer" name="Adder" url-pattern="/feedback"/>
</endpoints>
I got it now and its working I make changes so that my package an name are different from each other and specified
#Webservice
before my class name.I already tested the Webservice and implemented on my android phone.
Thank you all for your comments.

Categories

Resources