Printing text to webpage inside a Java method in JSP - java

I have been struggling to print text inside a Java method on a Java server page. Here are some ways I've attempted to print the text and errors thrown from the Tomcat (Version 7.0.56) compiler:
<%
class Base {
public void main() {
String Text = "ThisIsText";
out.println(Text);
}
}
%>
Error: Cannot refer to the non-final local variable out defined in an enclosing
scope
<%
class Base {
static Text;
public void main() {
String Text = "ThisIsText";
}
out.println(Text);
}
%>
Syntax error, insert "Identifier (" to complete MethodHeaderName
<%
class Base {
static Text;
public String text() {
String Text = "NewText";
return Text;
}
}
%>
<%text();%>
The method text() is undefined for the type Base_jsp
Is there any way to print HTML Text directly from a Java method in a JSP scriptlet?

The out variable is already inside a method - _jspService. So if you are going to use out, declare another method that takes out as parameter using declaration - <%! and then just call this method.

Use a declarative tag instead
<%!
class Base {
JspWriter out;
public Base(JspWriter out) {
this.out = out;
}
public void main() {
String Text = "ThisIsText";
try {
out.println(Text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
%>
<%(new Base(out)).main();%>
when you write something in <%%> the code between these tags is placed in methods so you cant declare function or class inside that tags because we cant have methods or class inside methods.
Similar,Also check

Related

Calling bean method on jsp

I'm trying to call a method that connects that is on a Bean on a jsp file. The method will make a request to a RMI Server and return a string. At this point the method is just return a pre-defined string for test.
This is the bean method:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
}catch(Exception e){
e.printStackTrace();
}
return "Hello";
}
And this is the jsp code:
<h1>Projectos Actuais</h1>
<h2><%
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
try{
aux.getListProjects();
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
I'm guiding my self from another code, and the method is called like this. But in my case it's not working, and I can't figure out what is wrong.
Since you've tagged this struts2, assuming the getListProjects() is on the Action, in JSP use:
<s:property value="listProjects" />
If instead it is on a bean, declare the bean in the Action, and expose it through a getter:
private MyBean bean;
public MyBean getBean(){
return bean;
}
and in JSP use the dot notation:
<s:property value="bean.listProjects" />
P.S: always avoid Scriptlets (<% %>), they're evil.
Quoting and fixing your latest change on edit with some comments:
<h1>Projectos Actuais</h1>
<h2><%
try{
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
//Send result into generated HTML page with out.print!
out.print(aux.getListProjects());
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
As per the flow of Struts there should be field in beanclass with same name of getter & setter. For an example if your method name is getListPorjects then in your bean class there should be a private string variable name listprojects.
Also your method will update with following to way to return listprojects.
example:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
listprojects = "hello"
}catch(Exception e){
e.printStackTrace();
}
return listprojects;
}
Calling bean variable should be with ID over the JSP page.
<jsp:useBean id="aux" class="com.path.to.ConnectToRMIBean" scope="request" />
----
yours stuff
-----
<h1>${aux.listProjects}
hope this will help you. good luck
You are just missing the way <% %> and <%= %> are used in JSP. to print in <% %> tags use
<% out.println("Your results"); %>
and for <%= %>
<%=
String.valueOf(1+2);
%>

Writing text files in java

So I know there are a lot of examples with writing textfiles, but I can't seem to get what is wrong with mine.
Here is the code I have so far
private void saveAddressBook() {
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(fullName);
out.close();
} catch(ValidationException e) {
e.printStackTrace();
}
}
I get an error on out.println(fullName); that says "fullName cannot be resolved to a variable"
Which makes no sense because I use it in other methods and classes. Not to mention it is public.
So what am I doing wrong?
Edit: fullName is declared right at the top of the class. I just didn't include it.
You didn't declare the variable fullName .
Try to declare and assign a value to the variable or give the String as the argument
out.println("my super string");
regards,
Your problem is that you have not defined the fullName variable.
Using out.println("FirstName LastName"); will work just fine, but if you want to pass the fullName variable as an agument to saveAddressBook that would look like:
private void saveAddressBook(String fullName) {
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(fullName);
out.close();
} catch(ValidationException e) {
e.printStackTrace();
}
}

JAVA bean method fails when called from SSJS but not from JAVA

I have a JAVA Class that is defied as a managed-bean. The code below is a stripped down version of it:
package ca.wfsystems.core;
import lotus.domino.*;
public class Utils {
public static void recycleObjects(Object... args) {
for (Object o : args) {
if (o != null) {
if (o instanceof Base) {
try {
((Base) o).recycle();
} catch (Throwable t) {
// who cares?
}
}
}
}
} //end recycleObjects
public static void sysOut(Object msg){
System.out.println(msg.toString());
} //end sysOut
}// End Class
The call to recycleObjects(someObject) works fine when called from JAVA Code, but when I call it from SSJS in a button on an XPage called TestError I get the message "State data not available for /TestError because no control tree was found in the cache."
The SSJS code in the button is:
WFSUtils().sysOut("In Button");
var vw:NotesView = WFSAppProperties().get(sessionScope.get("ssApplication")).getAppDB().getView("vwWFSForms");
WFSUtils().sysOut("Testing Bean" + vw.getName());
WFSUtils().recycleObjects(vw);
where WFSUtils is the name of the managed bean.
the error in the client says:
Error while executing JavaScript action expression
Script interpreter error, line=6, col=12: Java method 'recycleObjects(lotus.domino.local.View)' on java class 'ca.wfsystems.core.Utils' not found
JavaScript code
I have searched for the error "State data not available for" but found a single reference aout it when using the Extension Library but this code does not use it.
You are using varargs in your method.
It's not possible to use varargs from SSJS. Instead, you might call the same method as:
WFSUtils().recycleObjects([vw]);
It will work in that way.

Displaying streams in DIV

I am running some terminal(or command prompt) commands through my servlet as below
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] command =
{
"zsh"
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), response.getOutputStream())).start();
new Thread(new SyncPipe(p.getInputStream(), response.getOutputStream())).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("source ./taxenv/bin/activate");
stdin.println("python runner.py");
stdin.close();
int returnCode = 0;
try {
returnCode = p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("Return code = " + returnCode);
}
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
This is displaying the result after executing terminal commands in a new window, I want to avoid that and pass these stream values back to JSP page and display the same in a div.
How to do that?
Static import
First of all, you can define a scriplet with <%= and %> like explained here and here.
Instead of copying the whole code, you can statically import the .jsp page like so:
<%# include file="YourPage.jsp" %>
Link.
To call the page at runtime instead of at the server-side you do:
<jsp:include page="YourPage.jsp"/>
But this doesn't yield a huge advantage over static importing.
Link
You can also declare your function and then use it throughout your webpage by using <%! and %> like shown here.
If you do any of the methods above, your function will (can) be imported only when the page initially loads (server-side). (To be absolutely correct, <jsp:include is called at runtime in theory but in practice it simulates a request without actually making a complete round-trip: server > browser > server > browser).
Dynamic import
For dynamic importing or loading, you have to resort to jQuery (JavaScript) to load your JSP page client-side.
Please refer to this question: How do I inject another JSP page into a <div> when clicking a link?
You could simply do:
function changeContent() {
$('#content').load('YourPage.jsp');
}
You can find other examples here:
Display another jsp content in current jsp page upon a hyperlink click
CodeRanch
To quote the answer from the last link:
That's something to do with Ajax, Jquery can do that. You can use javascript getElementByID or use Jquery's build_in $("sub_banner") syntax to change the div's content.

Is it possible to print extra custom fileds along with the StackTrace while using log4j

I have this program as shown below , right now its only printng the stacktrace .
my question is that , is it possible to get the stack trace and also a custom field , here in my case i need 1090099
Please tell me if its possible ??
package com;
import org.apache.log4j.Logger;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class);
public static void main(String args[]) {
try {
String accountid = "1090099";
String desc = null;
System.out.println(desc.toUpperCase());
}
catch (Exception t)
{
logger.fatal("Exception inside the Test program ", t);
}
}
}
2013-06-26 21:44:29,723[main] FATAL(Test.java:<main>:16)- Exception inside the Test program
java.lang.NullPointerException
at com.Test.main(Test.java:12)
You have to include it manually in the message you're logging. But it looks to me like what you're really looking for is the MDC (mapped diagnostic context), a way to store values in a thread-local "context" that can then be used to distinguish between log messages relating to different application-level entities.
package com;
import org.apache.log4j.*;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class);
public static void main(String args[]) {
MDC.put("accountid", "1090099");
try {
String desc = null;
System.out.println(desc.toUpperCase());
}
catch (Exception t)
{
logger.fatal("Exception inside the Test program ", t);
} finally {
MDC.remove("accountid");
}
}
}
You would then include %X{accountid} somewhere in your appender's layout pattern and it would include the appropriate MDC entry in every log message, including those logged by third-party code that you call.
I would create my own Exception class, with members to hold the additional information, and a suitable toString() method that displays them. Wrap the original Exception in your custom Exception and add the information you want preserved.
Yes, you can print the value as long as it's in scope.
String accountid = null;
try {
accountid = "1090099";
String desc = null;
System.out.println(desc.toUpperCase());
} catch (Exception t) {
logger.fatal("Exception inside the Test program " + accountid, t);
}
Also, I would suggest using logger.debug instead of system.out.println for your other logging calls...
You are close to achieving that.
In your case you will have to declare the accountid outside the try block and then you can append the accountid along with your Exception inside the Test program message`
String accountid = "";
try {
accountid = "1090099";
String desc = null;
System.out.println(desc.toUpperCase());
}
catch (Exception t)
{
logger.fatal("Exception inside the Test program.\nAccount ID: " + accountid, t);
}

Categories

Resources