I have created a webservice Retrive with the following code :
#WebService(serviceName = "Retrive")
public class Retrive {
/**
* This is a sample web service operation
*/
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
/**
* Web service operation
*/
#WebMethod(operationName = "getData")
public List<String> getData(#WebParam(name = "parameter") String parameter) {
//TODO write your implementation code here:
List<String> haha = new ArrayList<String>();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/ws_pbl","root","");
PreparedStatement ps =con.prepareStatement
("SELECT * FROM ws_pbl.courses where name LIKE '%"+parameter+"%'");
ResultSet rs =ps.executeQuery();
while(rs.next()){
haha.add(rs.getString("name"));
}
}catch(ClassNotFoundException | SQLException e)
{
}
return haha;}}
And I have created a java servlet invoking the web service with the following code:
public class Test extends HttpServlet {
#WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/bidda/Retrive.wsdl")
private Retrive_Service service;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print(getData("data").toString()); } private java.util.List<java.lang.String> getData(java.lang.String parameter) {
// Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
// If the calling of port operations may lead to race condition some synchronization is required.
com.bidda.Retrive port = service.getRetrivePort();
return port.getData(parameter);
}
When I run the servlet and invoking the web service in Netbeans, I getting the following error:
java.lang.IllegalArgumentException: com.bidda.Retrive is not an interface
Related
I am new to Helidon SE and would like to know if there is a way to implement q params in REST service created via Helidon SE.
Any help in this regard is truly appreciated.
Thanks,
Gaurav
If you want to use and read params in the following way e.g.
http://localhost:8080/?q=test&k=test2
Then -in case of Helidon SE- do the following to get those parameters:
private void getParam(ServerRequest request, ServerResponse response) {
Map params = request.queryParams().toMap();
logger.info("params: " + params);
logger.info("q: " + params.get("q"));
logger.info("k: " + params.get("k"));
...
}
Obviously the getParam method is configured for "/" path.
How do I retrieve query parameters in a Helidon SE application:
Here is one example,
HelloService.java
public class HelloService implements Service {
private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap());
HelloService(Config config) {
}
#Override
public void update(Rules rules) {
rules.get("/", this::getDefaultMessageHandler);
}
private void getDefaultMessageHandler(ServerRequest request, ServerResponse response) {
var params = request.queryParams().toMap();
System.out.println("name: " + params.get("name").get(0));
System.out.println("email: " + params.get("email").get(0));
sendResponse(response, params.get("name").get(0));
}
private void sendResponse(ServerResponse response, String name) {
var returnObject = JSON.createObjectBuilder().add("name", name).build();
response.send(returnObject);
}
}
Main
public class HelidonSeRestHelloWorldApplication {
public static void main(final String[] args) {
startServer();
}
private static Single<WebServer> startServer() {
var config = Config.create();
var server = WebServer.builder(createRouting(config)).config(config.get("server"))
.addMediaSupport(JsonpSupport.create()).build();
var webserver = server.start();
webserver.thenAccept(ws -> {
System.out.println("Web server started! http://localhost:" + ws.port() + "/hello");
ws.whenShutdown().thenRun(() -> System.out.println("Web server is down!"));
}).exceptionallyAccept(t -> {
System.out.println("Web startup failed: " + t.getMessage());
});
return webserver;
}
private static Routing createRouting(Config config) {
var helloService = new HelloService(config);
return Routing.builder()
.register("/hello", helloService).build();
}
}
application.properties
server.port=9080
Run the application and hit http://localhost:9080/hello?name=alpha&email=alpha#alpha.alpha
Console output:
name: alpha
email: alpha#alpha.alpha
++ How do I retrieve path parameters in a Helidon SE application:
Main
public class HelidonSeRestHelloWorldApplication {
...........................
...........................
private static Routing createRouting(Config config) {
var helloService = new HelloService(config);
return Routing.builder()
.register("/hello/{name}", helloService).build();
}
}
HelloService.java
public class HelloService implements Service {
............
...........
private void getDefaultMessageHandler(ServerRequest request, ServerResponse response) {
var name = request.path().absolute().param("name");
System.out.println(name);
sendResponse(response, name);
}
.................
.................
}
Run the application and hit: http://localhost:9080/hello/alpha
I've got web servlet class which stores all the responses for requests in synchronizedMap.
Also I have RabbitMQ message handler (listener) which runs in separate thread. On message receive this message handler sends response and removes request from the map.
I put elements in the map on every request:
#WebServlet({"/create_conf_link", "/invite_participant", "/get_conf_credentials", "/get_web_conf_credentials"})
public class VcmsServlet extends HttpServlet implements AutoCloseable {
private static final long serialVersionUID = 1L;
private final VcmsWsMessageHandler mMessageHandler;
private volatile Map<String, HttpServletResponse> mResponses = Collections.synchronizedMap(new HashMap<String, HttpServletResponse>());
/**
* #see HttpServlet#HttpServlet()
*/
public VcmsServlet()
{
super();
mMessageHandler = new VcmsWsMessageHandler(mResponses);
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String corrID = java.util.UUID.randomUUID().toString();
mResponses.put(corrID, response);
On message handle handle method is called in MessageHandler class
public class VcmsWsMessageHandler implements IMessageHandler
{
public VcmsWsMessageHandler(Map<String, HttpServletResponse> responses)
{
mResponses = responses;
}
#Override
public void handle(final String inMethod, final String inMessage, final BasicProperties inProperties)
{
String corrID = inProperties.getCorrelationId();
LOG.info("VCMS response for " + corrID + ": " + inMessage);
synchronized (mResponses)
{
HttpServletResponse response = mResponses.get(corrID);
if(response == null)
LOG.error("Failed to find response object for corrilcation ID " + corrID);
try
{
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(inMessage);
mResponses.remove(corrID);
}
catch(IOException ex)
{
LOG.error("Error sending response");
response.setStatus(HttpServletResponse.SC_CONFLICT);
}
}
}
private volatile Map<String, HttpServletResponse> mResponses;
}
The problem is in that there is no response for corresponding corrID in MessageHandler class, though map element is added in handleRequest method of servlet. HttpServletResponse response = mResponses.get(corrID); returns null. But in some rare cases mResponses.get(corrID); returns valid response and everything is OK.
How should I work with map to sync it between classes?
Thanks.
This is the code (Validate.java Servlet File)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("u");
String password = request.getParameter("p");
Connection con = DBConnection.Connect();
String sql = "select *from users where name=? and pass=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
request.getRequestDispatcher("WelcomeServlet").forward(request, response); //This line calls another servlet
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
WelcomeServlet.java Servlet File
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
response.setContentType("html/text");
PrintWriter pw = response.getWriter();
pw.write("<html><body>");
pw.write("<title>Welcome User</title>");
pw.write("<h1>" + username + "</h1>");
pw.write("</body></html>");
pw.close();
}
Output
I want the validate servlet to call welcome servlet but its asking me whether to download a validate servlet file .PFA for more details
I am getting the popup to download Validate Ser
The content type should be text/html (you wrote html/text) otherwise the browser does not know what to do with the file and asks for downloading it.
There are also a few other problems with the code worth mentioning
You do not really check the result from the DB, so you will forward even if the user does not exist.
You use the parameter name u in one servlet but username in the other.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So, i'm getting slightly familiar with html, css and frameworks in general and i have a fair understanding of Java. However, i can only see how you can make inbuilt functions and computations with Javascript that you add to your html file. But i don't understand how it works with say a Java program on your computer that the website would fetch data and information from. Can anyone explain that? I couldn't find any good answers on the internet.
Say i want to compute the value 2+3 with Java on a server and then fetch that value and display it on the website. How would i do that?
I achieve this functionality by sending an ajax request via javascript to a java servlet on the server here is an example that I use:
Say you have a link:
<a href="#" onclick = 'shipProduct(1)'>Test</a>
When this link is clicked it will look for the corresponding javscript function, which in my case is:
/**
*
* #param {type} action
* #param {type} bundleId
* #returns {undefined}
*/
function shipProduct(bundleId)
{
$.ajax
({
url: "/FlcErp-war/ShipmentServlet", //this is the name of the serverlet in your project
type: "GET", // the type of your request
data: _action + "=addToShipped&bundleId=" + bundleId,
success: function (content)
{
if (content.substring(0, 1) == '_')
{
alert(content);
}
else
{
//rebuild shipment tables to show updated
//information about the item
buildShipmentQueue();
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
alert(status);
alert(error);
}
});
}
What I did was have have an annotated java servlet to serve my request:
your doPost and doGet will handle your post and get requests
/**
*
* #author samo
*/
#WebServlet("/ShipmentServlet")
public class ShipmentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String _addToShipped = "addToShipped";
private static final String _bundleId = "bundleId";
private static final String _shipmentId = "shipmentId";
private static final String _productId = "productId";
private static final String _updateQueue = "updateQueue";
private static final String _unship = "unship";
private static final String _setInSession = "setInSession";
private static final String _externalBundleId = "externalBundleId";
private static final String _plywood = "P";
private static final String _veneer = "V";
private static final String _lumber = "L";
private static final String _bundle = "Bundle";
private static final String _list = "List";
private boolean multipleActions;
private String[] actions;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processBundleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, NamingException, CloneNotSupportedException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
this.actions = null;
//this is where we will get the actions to process
//if there is more than one action the string will contain
// a comma as a delimiter
String action = request.getParameter("_action");
InitialContext ctx = new InitialContext();
LoadShipmentController lsc = (LoadShipmentController) ctx.lookup("loadShipmentController");
switch (action) {
case _addToShipped:
shipProduct(request, out);
break;
case _updateQueue:
Shipment shipment = lsc.getCurrent();
String type = shipment.getShipmentType();
String shipmentQueue = "";
switch (type) {
case _veneer:
shipmentQueue = lsc.getVeneerShipmentQueue();
break;
case _plywood:
shipmentQueue = lsc.getShipmentQueue();
break;
case _lumber:
shipmentQueue = lsc.getShipmentQueue();
break;
}
out.println(shipmentQueue);
break;
case _unship:
unshipProduct(request, out);
break;
case _setInSession:
String bundleId = request.getParameter(_bundleId);
lsc.setBundleId(bundleId);
break;
case _list:
out.println(lsc.getBundleAndProductListString());
break;
// setSessionVariable(_externalBundleId, bundleId);
}
}
}
public void shipProduct(HttpServletRequest request, PrintWriter out) throws NamingException, CloneNotSupportedException {
Integer bundleId = Integer.valueOf(request.getParameter(_bundleId));
InitialContext ctx = new InitialContext();
ShipmentController shipmentController = (ShipmentController) ctx.lookup("shipmentController");
LoadShipmentController loadShipmentController = (LoadShipmentController) ctx.lookup("loadShipmentController");
// getting the product from the bundle, because that's all we care about
Product product = shipmentController.loadBundle(bundleId).getProduct();
String type = product.getProductType();
//because the way we ships differs depending on the product type I need to
//check first mainly for veneer shipments because their bundle count is not
//predetermined
boolean loaded = false;
switch (type) {
case _veneer:
loaded = loadShipmentController.loadVeneerProduct(product, bundleId);
break;
case _plywood:
loaded = loadShipmentController.loadPlywoodProduct(product, bundleId);
break;
case _lumber:
loaded = loadShipmentController.loadLumberProduct(product, bundleId);
break;
}
if(!loaded)
{
out.println("_" + loadShipmentController.getErrors());
}
}
public void unshipProduct(HttpServletRequest request, PrintWriter out) throws NamingException {
Integer bundleId = Integer.valueOf(request.getParameter(_bundle));
InitialContext ctx = new InitialContext();
LoadShipmentController loadShipmentController = (LoadShipmentController) ctx.lookup("loadShipmentController");
boolean unship = loadShipmentController.unshipByBundleId(bundleId);
if (!unship) {
String error = loadShipmentController.getErrors();
out.println("Error:" + error);
}
}
private void setSessionVariable(String name, String value) {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpSession session = (HttpSession) externalContext.getSession(false);
session.setAttribute(name, value);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processBundleRequest(request, response);
} catch (NamingException ex) {
Logger.getLogger(ShipmentServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (CloneNotSupportedException ex) {
Logger.getLogger(ShipmentServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
I want to submit form data to servlet which is Jersey rest client
and inside this servlet I have to call a Restful Webservice.
I have to pass all form data to that rest Webservice and after that we will get a response object from rest to servlet.
I have to pass this response object directly to JSP page here request and response will be in JSON format.
you can use servlet to send data to web service by sendRedirect("<url>")
Is it really necessary to call REST Class from a Servlet?
If so, the following is the way. But your REST call will be treated as a plain class. To call any method of the Rest class you have to create its object and access its methods.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestURI = req.getRequestURI();
RestClass restClassObj = new RestClass();
String parameter1 = "";
String parameter2 = "";
String parameter3 = "";
String restResponse = "";
if(StringUtils.endsWith(requestURI, "services") || StringUtils.endsWith(requestURI, "services/")){
parameter1 = req.getParameter("parameter1");
parameter2 = req.getParameter("parameter2");
parameter3 = req.getParameter("parameter3");
restResponse = restClassObj.getRestClassMethodResponse(parameter1,parameter2,parameter3);
}
resp.setContentType("application/json");
resp.getWriter().write(restResponse);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
Now the RestClass is,
public class RestClass {
public RestClass() {
}
public String getRestClassMethodResponse(#FormParam("parameter1") String parameter1, #FormParam("parameter2") String parameter2, #FormParam("parameter3") String parameter3){
//Now write your own logic and return the data to the Servlet class in //JSON format
return jsonResponse;
}
}