I have Spring controller and I am setting a model value and want to display in my JSP:
public class TestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(Model model){
model.addAttribute("message", "Programmer Gate");
return "/test";
}
}
My test.jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome</title>
</head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<p>${message}</p>
</body>
</html>
I am not seeing the message value as the JSP rendering as follows:
Well, life goes on ...
(0.3343913194169942)
${message}
How to access the model message variable value in the JSP?
I am using a JNI library (jshortcut-0.4-oberzalek https://github.com/jimmc/jshortcut/downloads ).
I wrote one jsp file and imported this jar and I am calling this jsp in ajax call.
i placed the library project folder, I am using WinSCP and putty.
Now I am getting the java.lang.unsatisfiedlinkerror: jshortcut not found in java.library.path
Code :DesktopCreation.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="net.jimmc.jshortcut.JShellLink" %>
<%# page import="javax.servlet.http.HttpServlet,javax.servlet.http.HttpServletRequest,
javax.servlet.http.HttpServletResponse" %>
<!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">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="link" class="net.jimmc.jshortcut.JShellLink"></jsp:useBean>
<%!
JShellLink link;
String imgPath;
String iconPath="";
%>
<%
link = new JShellLink();
imgPath = JShellLink.getDirectory("") + "http://www.google.com";
iconPath="F:/WorkWorship/ShortCut/img/ico6.ico";
link.setFolder(JShellLink.getDirectory("desktop"));
link.setName("Manju");
link.setPath(imgPath);
link.setIconLocation(iconPath);
link.save();
%>
</body>
</html>
Code : Ajax
/*
* creates a new XMLHttpRequest object which is the backbone of AJAX,
* or returns false if the browser doesn't support it
*/
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function createShortCut() {
var xmlHttpRequest = getXMLHttpRequest();
var con=confirm("Do you Wish to Crete?");
if(con){
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("GET", "DesktopCreation.jsp", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
alert("ShortCut Created....");
alert("Thanks for Downloading ShortCut");
}else{
alert("No thanks .....");
}
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
Code:Shortcut.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">
<title>SHORTCUT</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
<h4 id="hello">Create ShortCut</h4>
<input type="image" src="F:\WorkWorship\DescktopShortCut\Dasara.jpg" width="100" height="100" onclick="createShortCut()" />
</body>
</html>
please any one can help.
Thanks in Advace
I am trying to pass video in bytes from controller and read and play it on jsp. It is working for videos having size less than 1 MB MB but it is not working for files bigger than 1 MB. Please help me..
here is my controller which reads file and writes bytes into output stream.
#RequestMapping(value = "/playVideo", method = RequestMethod.GET)
#ResponseBody
public void home(Locale locale, Model model,HttpServletRequest request,HttpServletResponse response) throws IOException {
logger.info("Welcome home! The client locale is {}.", locale);
String filePath = "D://Uploads//s.mp4";
int fileSize = (int) new File(filePath).length();
response.setContentLength(fileSize);
response.setContentType("video");
FileInputStream inputStream = new FileInputStream(filePath);
ServletOutputStream outputStream = response.getOutputStream();
int value = IOUtils.copy(inputStream, outputStream);
System.out.println("File Size :: "+fileSize);
System.out.println("Copied Bytes :: "+value);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
response.setStatus(HttpServletResponse.SC_OK);
}
Here is my jsp page
<%# 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">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<video width="320" height="240" controls>
<source src="/elearningportal/playVideo" type=video/mp4>
</video>
</body>
</html>
Have you tried using a bigger BufferSize?
response.setBufferSize(fileSize);
I using a JSP page to write into a file
Input Box in JSP will send some DATA
DATA
FARSI (Persian): INPUT_MSG = کد من کار نمی کند برای زبان فارسی.
<notification><myprojectid>256333859</myprojectid><mobile>123456789</mobile><uniqueid>ABCDEF565667DD</uniqueid><noation/><title>Push-Notification</title><message>INPUT_MSG</message><timestamp>20132611112245</timestamp></notification>
But in the file it has been stored in like given value
éï ÃÂ
àéçñ ÃÂÃÂ
à éÃÂï èñçà òèçàÃÂçñóÃ.
JSP PAGE Encoding For : SendMessage.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<form method="post" action="genMsgFile.jsp" name="testForm">
<span>Farsi Message : </span>
<input type="text" name="faMSg" />
<input type="submit" value="Push Message" />
</form>
</body>
</html>
JSP PAGE Encoding For : writeInfile.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.io.*"%>
<%#page import="java.util.*"%>
<%#page import="java.lang.*"%>
<html>
<body>
<%!
public void createFile(String msgLocation, String filepath, String msgTosend){
String fp = msgLocation + filepath;
// System.out.println("$$ PATH $$$ "+ fp);
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(fp));
pw.println(msgTosend);
pw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
%>
<%
String farMsg = request.getParameter("faMSg");
createFile(msgPATH,farsiFile,farMsg);
%>
</body>
</html>
What changes i should make in writeInfile.jsp so it will stored in readable format ???
This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.
This is my function
public Print(HttpServletRequest request,HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
};
This is where I call it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<%# page import="com.otrocol.app.*" %>
<%
Print(request, response);
%>
</body>
</html>
This is what I think the result is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
</body>
</html>
"haha"
This is what I want the response to be:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
"haha"
</body>
</html>
This is the error I get:
The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function.
Otherwise you are taking a second writer, and with buffering everything goes haywire.
Also as output already did happen do not set the content type in the function.
At the top of the JSP is a nice location, also for the imports.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
When having one writer the function would print at the correct spot in the body.
Nice intuition about the cause. BTW begin a function name with a small letter.
It's not a direct answer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSP from Java code.
Code example:
register.jsp
<%# taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<p>
<c:out value="${custom:printHaha()}" />
</p>
</body>
</html>
custom-tags.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>custom-taglib</shortname>
<uri>CustomTags</uri>
<function>
<name>printHaha</name>
<function-class>com.yourpackage.Tags</function-class>
<function-signature>
java.lang.String print()
</function-signature>
</function>
(...)
Tags.class
public class Tags {
public static String print() {
return "haha";
}
}
More info on Tags: official docs
I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp
now to print something on asp you can do this any number of ways
print by expression tag
use out (which is an object the server creates)
out.print("Blah...");
and more
to understand what happens to a jsp look into /work/catalina/blah.../
There are two pages. The first one is the Main Page. This one performs some
pseudo calcs.
Based on those calcs, either Success.jsp or Failure.jsp is returned.
This code will do what you wanted to have achieved.....
Even though as the others pointed out, there are more advanced techniques as of
late, still in order to dance, first you have to know the moves....
Primarily look at this
cObj.Print(request, response); in the 2nd jsp page.
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
</body>
</html>
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<!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">
<title>Failure!</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%cObj.Print(request, response);%>
</body>
</html>
Java Bean
package rustler.Beans;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Beany implements Serializable
{
public Beany()
{
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setJunk(String sStr)
{
//System.out.println("What a punk!");
custName = sStr;//"What a punk!";
}
public void Print(HttpServletRequest request,HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
public String prntJunk()
{
//System.out.println("What a punk!");
return custName;//"What a punk!";
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}