How to call Java Class from JSP page? Cloud9 & OpenShift JBoss - jboss

I am new to c9. I created a Openshift JBoss application server & imported into C9 via GitHub.
I have a simple Java class in Main\Java\initial.class.
public class initial {
public static void main(String[] args) {
String prn = disp();
System.out.println(prn);
}
public static String disp()
{
String str=" JAVARANCH ";
return str;
}
}
I have a jsp page called from index.html, I am just trying to display the variable 'prn' in the jsp page.
<HEAD>
<TITLE>JBossAS7 JSP snoop page</TITLE>
<%# page import="javax.servlet.http.HttpUtils,java.util.Enumeration" %>
<%# page import="java.lang.management.*" %>
<%# page import="java.util.*" %>
<%# page import="initial" %>
</HEAD>
<BODY>
<H1>WebApp JSP Snoop page</H1>
<img src="images/jbosscorp_logo.png">
<h2>JVM Memory Monitor</h2>
<input type="text" name="text1" size="100" value="<%=prn%>">
But, I am getting below error at the JSP page:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 10 in the generated java file
The import initial cannot be resolved
An error occurred at line: 15 in the jsp file: /snoop.jsp
prn cannot be resolved to a variable
12: <img src="images/jbosscorp_logo.png">
13:
14: <h2>JVM Memory Monitor</h2>
15: <input type="text" name="text1" size="100" value="<%=prn%>">
16:
17: <table border="0" width="100%">
18:
How do I interact with a Java class from my JSP?
thanks.
EDIT due to two answers:
I think the main issue is: the class 'initial' is not being imported successfully. My call to Prn was wrong, I understand that now, but the Import itself is not working.
some suggested having the class inside a package. But Cloud9 IDE does not have an option to create a package.
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 10 in the generated java file
The import initial cannot be resolved

If you try this :
Java class:
public class Initial {
public static String getDisp() {
return "JAVARANCH";
}
}
JSP file :
<HEAD>
<TITLE>JBossAS7 JSP snoop page</TITLE>
<%# page import="javax.servlet.http.HttpUtils,java.util.Enumeration" %>
<%# page import="java.lang.management.*" %>
<%# page import="java.util.*" %>
<%# page import="Initial" %>
</HEAD>
<BODY>
<H1>WebApp JSP Snoop page</H1>
<img src="images/jbosscorp_logo.png">
<h2>JVM Memory Monitor</h2>
<input type="text" name="text1" size="100" value="<%=Initial.getDisp()%>">
</BODY>

You can access your class from your jsp by adding the following.
<input type="text" name="text1" size="100" value="<%= initial.disp() %>">
or by adding a jsp scriptlet prior to your input
<%
String prn = initial.disp();
%>
<input type="text" name="text1" size="100" value="<%= prn %>">
Notice I am using your method disp() not main(). Main is static void with no return.

Related

JSP doesn't see JavaBeans

everybody!
Can't solve this problem:
org.apache.jasper.JasperException: JBWEB004062: Unable to compile class for JSP:
JBWEB004060: An error occurred at line: 14 in the jsp file: /indexJB.jsp
packt.book.jee_eclipse.ch2.bean.LoginBean
cannot be resolved to a type
11: <%if ("POST".equalsIgnoreCase(request.getMethod())&&
12:
request.getParameter("submit")!=null)
13: { %>
14: <jsp:useBean id="loginBean"
15:
class="packt.book.jee_eclipse.ch2.bean.LoginBean">
16:
<jsp:setProperty name="loginBean" property="*"/>
17: </jsp:useBean>
I use:
WildFly 23
Eclipse Version: 2021-09 (4.21.0)
What I found in Internet:
Note
See the detailed error message under More Information.
​This issue occurs because JBoss EAP 6.2 server runtime is using unsupported JDK. Verify the following log statements for reference:
java.library.path = C:\Program Files\Java\jdk1.8.0_20\bin
java.runtime.name = Java(TM) SE Runtime Environment
java.runtime.version = 1.8.0_20-b26
Solution
​To resolve this issue, do as follows:
Point your JBoss EAP 6.2 server to a supported JDK that is JDK 1.7.x
(best is 1.7.0_25).
Restart the application server.
But how to point???
Thanks in ADVANCE!
The whole code is here:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W#C//DTD HTML 4.01 Transitional//EN"
"http://www.w3org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<% String errMsg = null; %>
<%if ("POST".equalsIgnoreCase(request.getMethod())&&
request.getParameter("submit")!=null)
{ %>
<jsp:useBean id="loginBean"
class="packt.book.jee_eclipse.ch2.bean.LoginBean">
<jsp:setProperty name="loginBean" property="*"/>
</jsp:useBean>
<%
if (loginBean.isValidUser())
{ out.println("<h2>WElcome, Admin!</h2>");
out.println("You are logged in");
}
else
errMsg = "Invalid user ID or password!";
}
%>
<body>
<h2>Login:</h2>
<%if (errMsg!=null ) {%>
<span style="color: red;"><%out.print(errMsg); %> </span>
<%} %>
<form method="POST">
User Name: <input type="text" name="userName" style="color: Green; background-color: Yellow"><br>
Password: <input type="password" name="password" style="color: Yellow; background-color: Silver"><br>
<button type="submit" name="submit">SUBMIT</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The problem was solved:
Right click on project-> choose properties -> Java Build Path -> choose third marker Libraries -> put cursor on Classpath -> on right menu choose Add Class Folder -> choose folder for classes -> Apply and Close.
I also restarted Eclipse just in case.
And my JSP finally sees Java Beans!
Hope that will help=)

ClassNotFound Exception: org.postgresql.Driver from [Module "deployment.ValidateUser.war:main" from Service Module Loader]

I am trying to connect with postgre databse with jsp program using Eclipse IDE,
I am getting this error:
"java.lang.ClassNotFoundException: org.postgresql.Driver from [Module
"deployment.ValidateUser.war:main" from Service Module Loader]".
I had put the jar files required for my project even though i am getting classnotfound exception error.
<%#page import="com.uservalidation.FarwordNames"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Variables that will be written --%>
<%
String fname = request.getParameter("fname");
String mname = request.getParameter("mname");
String lname = request.getParameter("lname");
String dob = request.getParameter("dob");
String addr = request.getParameter("addr");
%>
<%-- Creating new staff account - writing --%>
<%
try{
Class.forName("org.postgresql.Driver");
String conURL= "jdbc:postgresql://192.168.1.157:5432/MIPSUITE_DEV";
Connection con = DriverManager.getConnection(conURL,"mipsuitedev01","mipsuitedev01");
Statement st = con.createStatement();
//int status = st.executeUpdate("insert into users(fname,mname,lname,dob,address) values('"+fname+"',"+mname+"','"+lname+"','"+dob+"','"+addr+"')");
/* if(status>0){
out.println("Update sucessful");
}
else{
out.println("Update unsuccessful");
} */
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>
It seems to be fixed the problem by removing all resteasy/jaxrs/jboss libraries from the WAR file's WEB-INF/lib/.
Put postgresql driver
jar files into WEB-INF/lib folder.
I think it's should be work for you.

Spring Mvc Rest Webservice jstl form submittion HTTP Status 415 Content type 'application/x-www-form-urlencoded' not supported

I am Using Spring Mvc Rest Webservice with JSTL form submittion.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# page session="false" %>
<html>
<head>
</head>
<body>
<form:form method="POST" action="rest/save" modelAttribute="employee">
<table>
<tr><td>
id &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<form:input type="text" path="id"/>
</td></tr>
<tr><td>
fname <form:input type="text" path="firstName"/>
</td></tr>
<tr><td>
lname <form:input type="text" path="lastName"/>
</td></tr>
<tr><td>
phone <form:input type="text" path="phone"/>
</td></tr>
</table>
<input type="submit" value="submit" >
</form:form>
Here is my controller function that accepts the request.
#RequestMapping(value = EmpRestURIConstants.SAVE_EMP,method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String setemployee(#RequestBody Employee employee){
dataServices.setemp(employee);
return "success";
}
This works fine and saves the employee when i use it with ajax submit or with using RESTClient
The Error returns is..
HTTP Status 415: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported
How Can i set the Mime type with JSTL form submittion and how can i solve the problem.
Please Somebody help.
When you're posting a form, the data are not sent as JSON, and since you have explicitly set that you're accepting only consumes=MediaType.APPLICATION_JSON_VALUE you get the 415 error. You can have all your cases covered by removing the #RequestBody and the consumes attribute, Spring MVC is smart enough to know what to do in all of your cases (form submition, RESTClient or ajax)
#RequestMapping(value = EmpRestURIConstants.SAVE_EMP,method = RequestMethod.POST)
public #ResponseBody String setemployee(Employee employee){
dataServices.setemp(employee);
return "success";
}

how to access liferay menu from portlet

I define a menu in navigation.vm file which working good in liferay project.
But I want to access this menu from my portlet.
Is there any way to access menu from portlet entry point or view.jsp????
import liferay-ui taglib:
<%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
then you can use
<liferay-ui:navigation displayStyle="from-level-0" >
</liferay-ui:navigation>
Note: setting displayStyle="from-level-0" to give you the normal behavior like on navigation.vm, you can play with attributes differently to get other behavior.
This link describes the way of getting menu items in a jsp directly.
The below code is reproduced directly from the above link with some improved formatting:
<%# taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# page import="java.util.List" %>
<%# page import="java.util.ArrayList" %>
<%# page import="com.liferay.portal.model.Layout"%>
<%# page import="com.liferay.portal.kernel.util.WebKeys"%>
<%# page import="com.liferay.portal.theme.NavItem" %>
<%# page import="com.liferay.portal.theme.RequestVars" %>
<%# page import="com.liferay.portal.theme.ThemeDisplay"%>
<portlet:defineObjects />
<liferay-theme:defineObjects />
<div style="width:100%">
<%
//ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
String title = themeDisplay.getLayout().getName(themeDisplay.getLocale());
List<NavItem> navItems = new ArrayList<NavItem>();
if (layout != null) {
RequestVars requestVars = new RequestVars(request, themeDisplay, layout.getAncestorPlid(), layout.getAncestorLayoutId());
navItems = NavItem.fromLayouts(requestVars, layouts);
}
for (NavItem navItem : navItems) {
if (navItem.getName().equalsIgnoreCase(title)) {
if (navItem.hasChildren()) {
for(NavItem navChild : navItem.getChildren()) {
%>
<div style="float:left;" class="newsMenuPortlet">
<a href="<%= navChild.getURL() %>" <%=navChild.getTarget() %>>
<%= navChild.getName() %>
</a>
</div>
<%
} // inner for-loop ends here
}
}
}// outer for-loop ends here
%>
</div>

Value is not posting in a .jsp page

This is the code that I have for the page that I'm testing out:
Don't worry the startpage and endpage code works.
<% startpage(out); %>
<%
String newusers = request.getParameter("users");
int i = 0;
if (newusers != null){
while(i<10)
{
out.println("<h2>newusers</h2>");
i++;
}
}
%>
<form action="guestAdder.jsp" method=post>
<textarea name=users rows=20 cols=100>
</textarea>
<p>
<input type=submit name=doadd value="Add Users">
</form>
<% endpage(out); %>
it is a HTTP Status 500 - java.lang.NoClassDefFoundError: org/apache/jsp/guestAdder_jsp (wrong name: org/apache/jsp/guestadder_jsp)
I'm guessing you've renamed your jsp file from guestadder.jsp to guestAdder.jsp. Are you on Windows (which isn't case sensitive for filenames)? Looks like the servlet class generated from the JSP page is overwriting the old lowercase-named file but the file isn't being renamed, i.e it is keeping its old name of guestadder_jsp.class
Clear the directory used to cache the servlet classes generated from JSPs - in Tomcat this is tomcat/work