Cant deploy WebService that uses MYSQL in Tomcat - java

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.

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));
}

I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?

my web.xml file :
Web.xml
I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?
I am using the below URL :
http://localhost:8080/learning1/rest/firstRest/User1
<?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" 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">
<servlet>
<servlet-name>Learn</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.java.learning1</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Learn</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My restfulwebservice java file : java file
Server is responding with HTTP Status code 404 : not found
package org.java.learning1;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces("MediaType.TEXT_HTML")
#Path("{name}")
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello";
return greeting;
}
}
Hello user7481861 and welcome to stackoverflow!
You have two errors in your code, I've corrected them bellow and added a comment in each, saying what was wrong.
package org.java.learning1;
//import javax.websocket.server.PathParam; <-- incorrect import
import javax.ws.rs.PathParam; // <<-- correct import
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces(MediaType.TEXT_HTML) // No quotes like stdunbar said in the comments
#Path("/{name}") // missing slash before name
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello " + name; // concatenate the string with the variable name
return greeting;
}
}

Forwarding requests in servlets

so I'm trying to create a servlet which will handle all requests for the WSDL at the endpoint, and then send the WSDL (Right now its just a file on the disk, later, I'm planning to change that file somewhat based on the permissions of the client). The way I'm trying to implement this is by creating a WSDLHandlerServlet class that's mapped to /* in web.xml. The way I understand it - all requests should be intercepted by this.
Once passed to the servlet it checks basically if the URI with query string is - "/TestProject/pace/soap?wsdl" and if so sends back the WSDL. This part works fine when I open "localhost:8180/TestProject/pace/soap?wsdl" in the browser and it displays the correct WSDL.
If the request has no query string, then I forward it to the cxf servlet which is linked to my web service implementor.
However when I send a request from a client (SOAP request), I get -
Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 200: OK
Also it is clearly not reaching the implementing class since if it did, there would be a log. I suspect I have most probably messed up the servlet mappings.
This is the WSDLHandler Servlet-
package servlets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WSDLHandlerServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// This is just a test.. anything without a query string will be sent to
// cxf servlet... and any long request ending with ?wsdl will yield the
// wsdl.. need to work on the design...never mind now it is time to
// begin!!
String query = new String();
query = request.getQueryString();
/*
* File abc = new File("/home/aneeshb/testing.txt"); FileWriter fw = new
* FileWriter(abc);
*
*
* if(!query.isEmpty()){ fw.write(query); fw.close();}
*/String requestURI = request.getRequestURI();
File abc = new File("/home/aneeshb/testing.txt");
FileWriter fw = new FileWriter(abc);
fw.write(requestURI);
fw.append("1234");
fw.append(query);
fw.flush();
if (query==null) {
fw.append("2");
fw.flush();
RequestDispatcher dispatch = request.getRequestDispatcher("/pace");
fw.append("2");
fw.flush();
dispatch.forward(request, response);
fw.append("2");
fw.flush();
}
else if (requestURI.equals("/TestProject/pace/soap")
&& query.equals("wsdl")) {
fw.append("This is in part1 ");
fw.flush();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml");
PrintWriter respWrite = response.getWriter();
File wsdlFile = new File(
"/home/aneeshb/Workspaces/Project1/TestProject/WebContent/WEB-INF/wsdl/stock.wsdl");
FileReader wsdlRead = new FileReader(wsdlFile);
BufferedReader wsdlBuffRead = new BufferedReader(wsdlRead);
int temp = 0;
while ((temp = wsdlBuffRead.read()) != -1) {
respWrite.write(temp);
}
respWrite.flush();
wsdlBuffRead.close();
}
else {
throw new IndexOutOfBoundsException();
}
}
}
My web.xml -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insance"
version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>cxf</display-name>
<servlet>
<description>Apache CXF Endpoint</description>
<display-name>cxf</display-name>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<description>WSDL Handler</description>
<display-name>wsdlh</display-name>
<servlet-name>wsdlh</servlet-name>
<servlet-class>servlets.WSDLHandlerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/pace</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>wsdlh</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
And just for good measure-the cxf servlet config file-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:soap="http://cxf.apache.org/bindings/soap" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd" xmlns:tns="http://impl/">
<jaxws:server id="jaxwsService" serviceClass="impl.GatewayImplementor" address="/soap" >
<jaxws:serviceBean>
<bean class="impl.GatewayImplementor"/>
</jaxws:serviceBean>
</jaxws:server>
</beans>
Thanks, any help with what I am doing wrong or ideas on alternate solutions would be great!

The requested URL /REST/WebService/MyMethod was not found on this server

i'm new to REST Service. i've done a small REST Webservice application and deployed in my online tomcat webserver,
My link -->
http://sample.com.au/REST/WebService/MyMethod?name=sss
but i'm getting the following message
The requested URL /REST/WebService/MyMethod was not found on this server.
when i run the similar in eclipse locally its working....
can anyone please tell me some solution for this...
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
:
:
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
</web-app>
My FeedService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.DELETE;
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 model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;
#Path("/WebService")
public class FeedService {
#GET
#Path("/MyMethod")
#Produces("application/json")
public String names(#QueryParam("name") String name)
{
System.out.println("name----------->"+name);
String feeds = null;
try
{
ArrayList<FeedObjects> feedData = null;
ProjectManager projectManager= new ProjectManager();
feedData = projectManager.GetFeeds(name);
Gson gson = new Gson();
System.out.println(gson.toJson(feedData));
feeds = gson.toJson(feedData);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console
}
return feeds;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/iloadlogistics.com.au"/>
Refer here. Specifically check Example 4.1 and Example 4.5. Should you not deploy that way?

Can't compile servlet file.

I was testing a demo servlet file But, the servlet doesn't seem to respond. I'm not able to understand the problem.
When I click submit on the HTML form the URL is
localhost:8080/Beer-V1/SelectBeer.do
But, shouldn't it be /BeerSelect? Because of #WebServlet("/BeerSelect") ???
web.xml
<?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" metadata-complete="false"
version="3.0">
<servlet>
<servlet-name>CH3 Beer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
BeerSelect.java
package com.example.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BeerSelect")
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
public BeerSelect() {
super();
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br> Got Beer Color " + c);
}
}
When I click submit on the HTML form the URL is localhost:8080/Beer-V1/SelectBeer.do
But, shouldn't it be /BeerSelect? Because of #WebServlet("/BeerSelect") ???
web-container associates a "context-path" for each of the web-application deployed and in your case, I believe it is "Beer-V1".
You have overridden the mapping in web.xml as below and hence you are seeing *.do
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
The xml DD overrides the annotations.

Categories

Resources