calling Webservices from jsp - java

I have created the wsdl successfully .Its url is "http://:/aebis/HelpdeskWebserviceImpl?wsdl".
Now I want to use this url to call the function in jsp.I am using Jboss as server.
Please suggest if any one can help.
Thanks in advance.

Here is a 5-minute example using eclipse
I am gonna use this WSDL to demonstrate
http://www.webservicex.net/ConvertAcceleration.asmx?WSDL
Create a dynamic java project for your JSPs
Create your JSP and some backend java class
your JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%= new myweb.MyClass().getResult() %>
</body>
</html>
and
package myweb;
public class MyClass {
public String getResult(){
return null;
}
public static void main(String[] args) {
MyClass c = new MyClass();
System.out.println(c.getResult());
}
}
Now create the WS client. Click on/select the project
right click and create a new Web Service Client from the given WSDL
Change MyClass to call the web service (you can test first using the class main too)
package myweb;
import java.rmi.RemoteException;
import NET.webserviceX.www.AccelerationUnitSoap;
import NET.webserviceX.www.AccelerationUnitSoapProxy;
import NET.webserviceX.www.Accelerations;
public class MyClass {
public String getResult() throws RemoteException {
AccelerationUnitSoap a = new AccelerationUnitSoapProxy();
Accelerations x = Accelerations.decimeterPersquaresecond;
Accelerations y = Accelerations.centimeterPersquaresecond;
Object z = a.changeAccelerationUnit(1, x, y);
return z.toString();
}
public static void main(String[] args) throws RemoteException {
MyClass c = new MyClass();
System.out.println(c.getResult());
}
}
Add the web app to your server (if there's one. If there isn't, create a new server)
Clear the server (forcing it to refresh the app) and start it
And here it is.

The wsimport tool is part of the JDK and generates "portable artifacts" from a wsdl. That gives you classes to use easily for communicating with the web service without the need of doing the boilerplate code yourself.
But I feel that you may need some more background beforehand, to get a better understanding how to use JAX-RS web services or implement a state-of-the-art web application with JSF, so my advice is to consult the Java EE 7 tutorial for those two (chapter 28 and 7).

Related

Spring Boot can't display .jsp file on the correct endpoint

I am very new to Spring Boot framework and want to clarify why I am facing with this issue.
Issue: .jsp file is not shown at the correct endpoint.
this is my controller class
#Controller
public class HomeController {
#RequestMapping("home")
public String home() {
System.out.println("Hello World");
return "home.jsp";
}
}
This is my application.properties class
spring.mvc.view.prefix = /webapp/
spring.mvc.view.suffix = .jsp
this is what I have inside home.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Change Titlte</title>
</head>
<body>
Hello
</body>
</html>
and lastly, the project directory
When I start spring boot app the site looks like this
Why do you think I can't see the content of home.jsp file?
Any help is appreciated.
Best,
PS: I already added Tomcat Jasper libraries in the pom.xml file
Check this simple examle. It seems you should not use .jsp extension in controller's return statement. Don't forget to specify method of your endpoint. Use #GetMapping instead of #RequestMapping
Also you'd better switch to Spring MVC thymeleaf that works good with html files. jsp - is used mostly for Java EE projects.
There are several things to notice here.
Change mapping to /home instead.
View resolver is configured already, return "home" instead of "home.jsp".
Take Model object as an argument it will be useful.
home(ModelMap model)

Running a servlet in intelliJ from .java class, not .jsp

I'm trying to create and run a servlet in IntelliJ. The problem I'm having is I'm following an Eclipse tutorial and they seem to work very differently. In Eclipse, a servlet.java class is created and run on Tomcat. In IntelliJ a .java class and .jsp file is created. The browser points to .jsp, not .java. The java class doesn't seem to be doing anything at all.
Why are they so different, and how can I point to the .java class instead of the .jsp?
I've added the .java and .jsp code below, which are both the standard stubs created by IntelliJ when creating a new servlet project.
#WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message;
public void init() {
message = "The Tomcat server does not point to this code in IntelliJ";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
public void destroy() {
}
}
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<h1><%= "Tomcat points to this .jsp file, not the .java code" %>
</h1>
<br/>
Hello Servlet
</body>
</html>
The servlet class has an annotation indicating what URI to use, so whatever URL your application is accessed using, followed by /hello-servlet.
Kind of weird that they generate these files that'll be useless 99% of the time.

${} is not working on my JSP page. How can i get my ${} html tag to work again? [duplicate]

This question already has answers here:
How to install JSTL? The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved [duplicate]
(5 answers)
Closed 2 years ago.
So ${} did work. But the JSTL jar files that I'm using made to where the ${} doesn't work anymore. These are my JSTL jar files. jstl-1.2 (1).jar, jstl-impl-1.2.jar, jstl-standard.jar. I am following Navin tutorial on Servlet & JSP Tutorial | Full Course on youtube. He skipped JSTL jar files. I'm a junior developer trying to understand why my ${} isn't working anymore.
Question: Why did my ${} tag not work anymore?
Please be gentle. :D
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html >
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${students}" var="s" >
${s} <br>
</c:forEach>
</body>
</html>
package com.Demo;
public class Student {
int rollno;
String name;
#Override
public String toString() {
return "Student [rollno=" + rollno + ", name=" + name + "]";
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int rollno, String name) {
super();
this.rollno = rollno;
this.name = name;
}
}
<?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_4_0.xsd" version="4.0">
<display-name>JSTLexample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
package com.Demo;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.RequestDispatcher;
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("/DemoServlet")
public class DemoServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//String name = "Navin";
List <Student> studs = Arrays.asList(new Student(1, "brandon"), new Student(2, "Micheal"), new Student (3, "Charles"));
request.setAttribute("students", studs);
RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
}
That "${}" is EL expression language syntax. You require to configure your "web application" web.xml or variant to use the JSTL (Java Standard Tag Library) .jar file in either the servers /commons/lib folder with server.xml (obviously not) or /WEB-INF/lib of your application.
Then call in the names of each tag prefix you wish to use declared at the top of your JSP page.
Tomcat has a few ways of achieving it.
Also your doctype should be
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Yout .tld tag library descriptor should be in the WEB-INF folder.
define the taglib location in your web.xml file
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location>
</taglib>
</jsp-config>
Also, your bean class should be declared in the web.xml and the page declarations to call it in the page at the top too.
Not a bad point to recheck the above if things go wrong.
The servlet you have made is a GET request servlet , they pass parameters on the URL by
?name=**valuOFthisPart&anid=**somethinHere&terminus=
if you use ${Param.student} added as student past the "?" on the url that may be usable to the EL something like this
**?students=name=**valuOFthisPart&next1=somethinHere&next2=somethinHere&terminus=
A POST servlet cannot carry parameters on the URL and is what you are trying to do by the code so is what the request.setAttribute is setting doing is for a POST request (POST requests do carry tokens).
Too, the setAttribute on request object is available by the interface of its class of which it can be done at class level by a wrapper sub class too as next
javax.servlet.ServletRequestWrapper requestWrpp = new javax.servlet.ServletRequestWrapper(request);
requestWrpp.setAttribute("students", studs);
HOWEVER, while more modern versions of web container recognise complex types such as List and Map (but probably not Student class) you may be able to use the code there by what i vaguely think i remember the clause of use of complex objects in JSP processing is and that being it is understood to be convertible to string.
Student is unrecognizable to the web app parser rules, however if you wrote Student to extend ( Map int,String ) then the runtime and compiler may be able to use that set up inside as a ( Map K,V )
Actually, this cannot work because you try to do this in the servlet before JSP processing by the response [ ! unless the Student class is only a servlet support class in the classes folder. (not bean syntax class)
see next paragraph ].
You are trying to use a class the way a bean operates , and a bean must be declared both in the web.xml and the page and the servlet notified too with a Student object reference from either classes or /classes/beans folder !!!
If it is a bean it should be in a bean folder (if it is not a bean and only a support processing class should be in classes with the servlet packaged or not) and called by the response in the JSP parser , but properly loaded, correctly updated current instance of it in the web app user session should be used (something JSF does more easily).
You can obtain current session and beans for servlet instance use by acquiring the web app context and initial instance thread to find the bean you want, its current instance and current state (requires to be a session bean unless the values are constant or it only outputs by set get processing instantly) to get its' current values. Bean classes must be declared throughout the app configuration not dissimilar to servlets but are different with rigid rules of declaration for runtime and syntax.
Final note
// the first argument should be a string NOT an int
req.setAttribute("String Object",(java.lang.Object)anObject);
//NOTE: That object must be convertible to a String from a recognizable java language core class !!!
Just a quick note about post requests, actually it can carry a query string but is considered a bizzarre action inside a Java framework.

Load static resource in Spring Boot with Thymeleaf

I want to make page using thymeleaf. But I have some problem with the static files. I've investigated questions(1,2,3) with similar problem, but it didn't help me.
I use Spring Boot framework in the application.
My files look like:
test.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<script src="js/test.js" th:src="#{/test.js}"/>
</head>
<body>
<button onclick="testFunction('test value')">Button</button>
</body>
</html>
test.js
function testFunction(test) {
console.log(test);
}
Configuration class
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
super.addResourceHandlers(registry);
}
}
And problem, when I load test.html file with javascript not loaded.
#GetMapping(value = "web/test")
public String getTestHtmlPage() {
return "test";
}
/api/v1 is a configuration in application.properties => server.servlet-path=/api/v1
What do I do wrong? Can you help me?
Thanks all!
For a better understanding of registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
I wrote a more thorough answer here that discusses invalid resource location mappings. It didn't receive any upvotes, so I hope it's not terrible. :-)
In short, with the way you're mapping classpath:/static/js/, and then accessing, /js/test.js, you're telling Spring to look in /static/js/js/test.js.
What you probably want is classpath:/static/. In that case, when you try to access /js/test.js, it's looking in /static/js/test.js for the file instead.
As for Thymeleaf, I've never used it, but docs indicate you should load scripts with th:src instead of th:href. th:href appears to only be for HTML content.

JavaBean not working in JSP

My aim is to import my class file in my index.jsp and reading over the internet I learned I'm supposed to use JavaBeans.
So here is my class file placed in WEB-INF/classes/jBean/Bucket.class -
package jBean;
import java.sql.* ;
import java.math.* ;
public class Bucket implements java.io.Serializable{
public static void main(String[] args){
Bucket obj = new Bucket();
obj.DBConn();
}
public static void DBConn(){
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentfeedback","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt("Roll_No")+" "+rs.getString("Name")+" "+rs.getString("Pass"));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
And here is my index.jsp where I want to import the class file -
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<jsp:useBean id="jBean" class="jBean.Bucket" scope="session" />
</body>
</html>
Doing this I get this error message on executing index.jsp file
java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
So, my query is how shall I import the class file, Bucket.java?
And is there any other way to import the file to index.jsp other than using javBeans?
Please help me with this as I can't find what I'm looking for. Maybe cause I might not be asking the right thing.
All I want to do is import the class file Bucket.java to the index.jsp
May God help the helping soul.
Did you observed your project folder structure.
The classes referenced by the jsp must be in the classpath.
And the classpath includes WEB-INF/classes.
The location of the jsp is of no importance.
question regarding jsp page import and <jsp:useBean id

Categories