How to call jsp page from java class without using any servlet - java

I just want to call jsp page from simple java class where i don' t have any request objects. without using any servlet. Just forward to jsp page from java class.

First to call a java class from JSP page:
you need to instantiate an instance from this class.
For example:
if you have a class called "myclass" and a JSP called "home.jsp"
then in your JSP page import the myclass ex, <# page import="yourpackagename.yourclassname">
then in the body part instantiate an instance from your class by typing my1.callyourfunction(); as follow:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="yourpackagename.myclass"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>home.jsp</title>
</head>
<body>
<%
myclass my1 = new myclass();
my1.Openpage(response);
%>
</body>
</html>
Second to call a jsp from a java class:
you need to use HttpServletResponse such as the following:
package yourpackagename.myclass;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class myclass{
public void Openpage(HttpServletResponse res) throws IOException{
// here type your JSP page that you want to open
res.sendRedirect("To.jsp");
}
}

If i am not mis understood, you are looking for JSP page to be opened in a browser via java class?
if yes, you can use Desktop API.
You can also look into following answers:
Open local html page - java
Getting java gui to open a webpage in web browser
Also keep in mind that your JSP page should be placed in a web container(Tomcat etc.) and its running when invoked OR you will be stuck finding out Why JSP is not opening.

Related

Getting null on sending values from Servlet to Client-side JSP [duplicate]

This question already has answers here:
Value passed with request.setAttribute() is not available by request.getParameter()
(2 answers)
Difference between getAttribute() and getParameter()
(10 answers)
Closed 4 years ago.
I am trying a simple example of sending values from a servlet Servlet1.java to client-side JSP page client1.jsp.
But I am getting null
Here is the code Server1.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;
#WebServlet("/server1")
public class Server1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String name="Rahul";
request.setAttribute("myname",name);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/client1.jsp");
reqDispatcher.forward(request,response);
}
}
Code for client1.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% String s=request.getParameter("myname");%>
Hello friends <%=s%>
</body>
</html>
What you do is bad.
First you are mixing attributes and parameters. They are different animals. Parameters is what comes from the client and are set once by the servlet container. Attributes are objects that are used by cooperating elements (filters, servlets and JSP pages) for passing data.
So you should at least read the attributes in JSP:
<% String (String) s=request.getAttribute("myname");%>
You must cast the attribute to String because getAttribute returns an Object.
But that's not all. Scriptlets are deprecated for decades, and should only be used for very special use cases, if any. Here, assuming you have a decent servlet container, you could simply use the ${} JSTL automatic attribute:
<body>
Hello friends ${myname}
</body>
It is shorter, cleaner and less error prone.
After your comments, there is another possible problem. You only show the override of doPost in your servlet code, when common requests (unless you post from a form) are GET requests and are processed in doGet. If you use a GET request and only set the attribute in doPost your JSP will not find it...
"myname" you are setting to request.setAttribute
so, you can retrieve as below:
<% String s=(String) request.getAttribute("myname");%>

Get output of java file into jsp page

I was trying to write a JSP page. But i have read many times that source code within JSP page is a bad practice. So then I tried to write a different class in the same package and call it within that JSP page.
Here's the JSP code:
<jsp:useBean id="link" scope="application" class = "tms.TestJava" />
<%
TestJava t=new TestJava();
t.test();
%>
and here's the class code:
public class TestJava {
public void test() throws IOException
{
System.out.println("sdds");
}
}
I have imported the class into JSP page.
Now the problem is that when I use System.out.println in the class (test method), it gets printed onto the console and I want it to print it to the JSP page. How can I achieve this? Is there a seperate method? Do I have to make the class a servlet?
Thanks!
Try using a tag library: JSTL
Specifically:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:out> Tag Example</title>
</head>
<body>
<c:out value="${'<tag> , &'}"/>
</body>
</html>
Or better yet, since you are using JavaBeans already, refactor so that you aren't using System.out() anymore. The idea is that you want to display properties of your bean in your page. Consider: JavaBeans So Do something like this:
Java
public class Course{
private String code = "Math";
public String getCode(){
return code;
}
}
Jsp
<jsp:useBean id="course" class="com.javaBeans.Course" />
<jsp:getProperty name="course" property="code"/>
Chiefly, you don't want to just System.out() to a page. The page should be a view of the data of components on the sever which in this case is the bean.
I think you're going about this the wrong way, but here is a possible solution...
<head>
<%# page language="java" import="tms.TestJava"%>
</head>
<body>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
</body>
public String getAString(){
return "<li></li>";
}
If your goal is to build dynamic JSPs, you will probably want to look into JSTL as someone above mentioned, look into defining your own tags, etc. I don't think very much new dev is using scriplet code.

Struts 2, multiple views and jQuery - How do I reuse common code?

I've read most of the online resources for building a simple "Hello World" app using Java and Struts 2. I understand the simple stuff. My problem is that I'm trying to expand that learning and build a large scale app, and I just don't see how to connect the dots.
Scenario:
I've got three views to begin with: Home.jsp, MyAccount.jsp, Contact.jsp. Each has the following HTML:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
...
</head>
<body>
<!-- If logged in, says "hello <s:property name="username">"
Else displays link to .show() #loginPane -->
<div id="accountHeader">...</div>
<!-- Displays <s:textfield> tags and <s:submit> tag to accept username and password -->
<div id="loginPane" style="display: none">...</div>
<header>...</header>
<nav>...</nav>
<!-- Displays view-specific content that includes Struts 2 tags -->
<div id="content">...</div>
<footer>...</footer>
</body>
</html>
So, obviously there is a lot of code common to each view (anything not in #content div).
How do I architect these views for code reuse?
What I've tried:
Placing common code in common.js and using jQuery .html() calls to populate <div>s. [Doesn't work because jQuery cannot generate code with <s:> tags.]
Using only one .jsp view file and placing view-specific code in common.js to be generated with jQuery .html() calls. [Doesn't work for the same reason -- jQuery cannot generate code with <s:> tags.]
Placing all view components in .jspf files and loading each with jQuery .load() calls from common.js. [Doesn't work -- I'm guessing the .jspf files need the Struts 2 <%taglib ...%> included in each, but jQuery .load() treats the <%taglib ...%> as text to be displayed in the <div>... and also fails to properly generate the <s:> tags.]
What is the proper way to do this? How do I architect my view(s) for code reuse?
My apologies if this isn't the proper forum to ask for architecture help, but I'm really struggling here... Perhaps point me to a more appropriate forum or an online tutorial that addresses this type of architecture?
Thanks in advance!
I've used several methods to accomplish this type of re-use of code including Tiles and tooling around with Sitemesh and other template frameworks. What I've found is that, much as Steven Benitez, in the end I preferred to use JSP taglibs, native Struts2 taglibs, and JSTL to essentially build out my own templating routines. The main reason I prefer this is that there tends to be less overhead and it's been a lot easier to maintain and extend in the long run.
Generally What I do is define my base template, index.jsp for example, and then in each independent Struts controller class I will define what page fragment is used. I try to split my controllers up in such a way that each page or function is handled by a single controller and I implement the Preparable interface. This way I can set a parameter for the page to reference. Sometimes I set it as a variable in the controller class, sometimes a sessions variable depending on what type of stating I need for the application.
Once I have a variable with the page to reference, I can just use a JSTL import or Struts include tag to load the page fragment.
The controller class would look something like this:
#Results({
#Result(name = "success", location = "/WEB-INF/content/index.jsp")
})
public class IndexController extends RestActionSupport implements Preparable{
private String page;
private String pageTitle;
#Override
public void prepare() throws Exception {
page = "home";
pageTitle= "My Home Page";
}
...
}
And then the JSP would look something like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title> ${pageTitle}</title>
</head>
<body>
<c:import url="${page}.jsp" />
</body>
</html>
EDIT: Fragment page example:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<div>
<h1>Welcome Home!</h1>
</div>
<script type='text/javascript'>
$(document).ready(function() {
// page specific scripting if needed
);
</script>
You can encapsulate common template code in JSP tag files, as explained in this answer or you can also use decorator frameworks such as Tiles or SiteMesh to do this.
Personally, I prefer JSP tag files. Do not attempt to write out HTML with jQuery or to put all of your code into a single JSP.

Sending dynamically generated javascript file

Background:
I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:
resp.setContentType("text/javascript");
resp.getWriter().println(script);
Problem:
The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.
Question:
What should be done so that browser treats response from the servlet as a regular javascript file?
Thank you for help.
It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.
I just did a quick test:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 6156155</title>
<script src="javaScriptServlet"></script>
<script>test()</script>
</head>
<body>
</body>
</html>
with
#WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/javascript");
response.getWriter().write("function test() { alert('peek-a-boo'); }");
}
}
and I get
How do you refer to this servlet from your browser ?
If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.
Ex.
<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>
Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.
Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.
ex. Your servlet sends the following, using content type 'text/html' :
<html>
<body>
<script type='text/javascript'>
<!-- write your generated JS here -->
</script>
</body>
</html>
You could always write the script 'in-line' to the web page.
I think this way is better.
<%# page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');
Set content type in JSP:
contentType="text/javascript; charset=UTF-8"

Spring variables not carrying into view

I'm very new to Spring and can't seem to figure out what's wrong here. I'm sure it has to be something simple, but anyway:
I was going through the tutorial on this page, and I have nearly identical code. After pulling down the Apache Commons library and the JSTL stuff, I was in business. Everything works, down to it actually using the jsp I specified as the view, but the variable "message" in the controller is not being displayed when the site is rendered. It's not because of the expression language stuff, either, because I'm not getting the ${message} text displaying either. It's just a blank page.
The only reason I know that the jsp is actually being triggered is because I put a title in there that is no where else and it is being used on page display. I also know that the variable is being set in the controller and the action is being called because of a simple sysout that I put in the mapped function.
Thanks for any help!
EDIT
Here's the jsp:
<%#page contentType="text/html" pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>om nom JSP Page</title>
</head>
<body>
${message}
</body>
</html>
And the controller:
package org.me.home.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
#Controller
public class SomeController {
#RequestMapping("/somepage")
public ModelAndView someAction() {
String mymsg = "Saying hi!";
System.out.println(mymsg);
return new ModelAndView("somepage", "message", mymsg);
}
}
Try to use such a construction:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${message}" />
And are you sure, that the problem is in displaying? Is page loaded fine, I mean is all other HTML displayed on page, besides "message"?
EDIT
Try to use org.springframework.web.servlet.ModelAndView instead of
org.springframework.web.portlet.ModelAndView
Your tomcat maybe using the wrong jstl.jar. Under your tomcat lib folder, check if your jstl.jar is the same version you are using with your project.

Categories