I have two jsp file, one is NewFile.jsp and another is index.jsp
I want to use variables(defined in index.jsp) in NewFile.jsp.
So I put this line in "NewFile.jsp":
<%# include file = "index.jsp" %>
But page loaded HTTP Status 500 Internal Server Error and it said, :
org.apache.jasper.JasperException: 행 [13]에서 [/index.jsp]을(를) 처리하는 중 예외 발생
10: out.println("can't access");
11: }
12: else {
13: int age = Integer.parseInt(request.getParameter("age"));
14: double height = Double.parseDouble(request.getParameter("height"));
15: boolean sex = Boolean.parseBoolean(request.getParameter("female"));
16:
It said : row [13] is wrong.(It is wrote in Korean but I think you can understand.)
and I have these lines in NewFile.jsp :
function doAction(){
var req = createRequest();
if (req == null){
alert("실행이 되지 않는다!");
return ;
}
var hei = document.getElementById("height").value;
var ag = document.getElementById("age").value;
var fem = document.getElementById("female").checked;
req.open("GET", "index.jsp?female=" + encodeURI(fem) + "&age=" + encodeURI(ag) + "&height=" + encodeURI(hei));
req.setRequestHeader("User-Agent", "XMLHttpRequest");
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
var msg = document.getElementById('msg');
msg.innerHTML = this.responseText;
}
}
req.send();
}
I think it has an error while files interact in request.
And when I erase <%# include file = "index.jsp" %>, it worked well (but not use index.jsp variables in NewFile.jsp).
But I don't know how to modify it.
How can I do to use variables defined in index.jsp in NewFile.jsp?
It's not clear from the description what you are trying to do. It seems that you got a null reference at line 13. If you pass the age as a request parameter than it does not make sense at all "sharing the variables".Here's a working example which demonstrates how to share variables:
<!-- hello.jsp -->
<%
String hi = "Hello from hello.jsp";
request.setAttribute("hi", hi);
%>
<!-- index.jsp -->
<jsp:include page="hello.jsp"/>
<%=request.getAttribute("hi") %>
Keep in mind that the usage of JSP scriptlets is highly discoureged. Check this post for more in-depth details.
Related
I added flow.js in my proyect following the instructions and the call to my java servlet:
localhost:8080/WebExample/UploadImgServlet?flowChunkNumber=1&flowChunkSize=1048576&flowCurrentChunkSize=693916&flowTotalSize=693916&flowIdentifier=693916-image2png&flowFilename=image2.png&flowRelativePath=image2.png&flowTotalChunks=1`
In my servlet I get all parameters of the url (flowChuckNumber, flowChuckSize, etc) but when I try to get the file (request.getInputStream()), it's empty and upload 0 bytes.
Where is the problem? Any Idea?
I found a similar question but it was with PHP...
My code:
HTML(the image is displayed):
...
...
<div flow-init="{singleFile:true}"
flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
flow-files-submitted="$flow.upload()"
flow-file-success="$file.msg = $message">
<div class="drop" flow-drop ng-class="dropClass">
<md-button class="md-raised md-primary" type="file" flow-btn>Upload Image</md-button>
<b>OR</b>
Drag And Drop your image here
</div>
<div class="thumbnail" ng-show="!$flow.files.length">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="Image"/>
</div>
<div class="thumbnail" ng-show="$flow.files.length">
<img flow-img="$flow.files[0]" />
</div>
<table>
<tr ng-repeat="file in $flow.files">
<td>{{$index+1}}</td>
<td>{{file.name}}</td>
<td>{{file.msg}}</td>
</tr>
</table>
</div>
...
...
App AngularJs:
var app = angular.module("webexample", ['ngMaterial', 'ngNotify','uiGmapgoogle-maps','flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: '/WebExample/UploadImgServlet',
permanentErrors: [404, 500, 501],
maxChunkRetries: 1,
chunkRetryInterval: 5000,
simultaneousUploads: 1
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}])
.directive('appDownloadUrl', [function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('dragstart', function (event) {
var config = scope.$eval(attrs.appDownloadUrl);
if (!config.disabled) {
var data = config.mime + ':' + config.name + ':' + window.location.href + config.url;
console.log("data: "+data);
event.dataTransfer.setData('DownloadURL', data);
}
});
}
};
}])
.directive("appDragstart", [function () {
return function(scope, element, attrs) {
element.bind('dragstart', function (event) {
scope.$eval(attrs.appDragstart);
});
}
}]).directive("appDragend", [function () {
return function(scope, element, attrs) {
element.bind('dragend', function (event) {
scope.$eval(attrs.appDragend);
});
}
}]).run(function ($rootScope) {
$rootScope.dropEnabled = true;
});
My Servlet (I followed this example):
protected void doService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
LOGGER.debug("[UploadImgServlet - doService] - init");
int resumableChunkNumber = getResumableChunkNumber(request);
ResumableInfo info = getResumableInfo(request);
//info contains all flow parameters of the url.
RandomAccessFile raf = new RandomAccessFile(info.resumableFilePath, "rw");
//Seek to position
raf.seek((resumableChunkNumber - 1) * info.resumableChunkSize);
//Save to file
InputStream is = request.getInputStream();
long readed = 0;
long content_length = request.getContentLength();
//**PROBLEM: request.getContentLength return -1 so read 0 bytes**
byte[] bytes = new byte[1024 * 100];
while(readed < content_length) {
int r = is.read(bytes);
if (r < 0) {
break;
}
raf.write(bytes, 0, r);
readed += r;
}
raf.close();
...
...
The input stream will be empty because flowjs posts the content using MultiPart by default.
The author of the Java code specified that "Octet" should be used for uploads, not multi-part.
UploadServlet accepts Resumable.js Upload with 'octet'
You need to add "method:octet" to your init,
<div flow-init="{singleFile:true, method:octet}"
I am using Spring, so I just used MultipartHttpServletRequest to get the posted data with MultiPart instead because MultiPart is more common.
This is how I received the contents of the file:
Iterator<String> itr = request.getFileNames();
/* Iterate each file, there should only be one/one chunk */
while (itr.hasNext()) {
fileUploaded = request.getFile(itr.next());
raf.write(fileUploaded.getBytes());
}
raf.close();
I had to do more fixes to the java code provided because it was estimating the number of chunks to receive wrong, so I just used the "flowTotalChunks" parameter.
You don't need to worry about content length. The HttpServletRequest will terminate the input stream at the correct point. Just read until end of stream.
I wanted a lib to upload images with more options and visually appealing (drop file from a folder, thumbnail, etc) than the default html input and I have not been able to do with Flowjs and Java Servlet, so I looked for another lib:
https://github.com/danialfarid/ng-file-upload
https://angular-file-upload.appspot.com/
With this lib, I found it easy to use with Java Servlet.
I don't mark this post as solved for if someone finds a way to do it with Flowjs.
I have a need to know the java version installed on client machine, have come up with the solution here
How to write JavaScript function to check JRE version
When I tried, got with the answer:
console.log(deployJava.getJREs());
But at the address bar, pop up menu is displayed like this
How to hide this?.
If this can not be achieved, please suggest any other idea to implement, as this can not be used,if this popup is not suppressed
I am pretty sure from recent experiments that there is no way to suppress it. For the script to detect the plug-in versions, it must invoke the plug-in itself.
After those experiments I worked to create a script that could detect a variety of things out about the Java plug-in without invoking the plug-in itself. They relied on examining the mime-types info.
This still shows a warning in IE if opened from the local file-system. But I hope it will be more forgiving if loaded from the internet. Please report back.
But note this is what it reports for IE when the 'allow scripts' check is OK'd.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Java Information - Non Deployment Toolkit Script</title>
<meta name='author' content='Andrew Thompson'>
<meta name='description' content='Non Deployment Toolkit Script'>
<script src='mimetypes.js'></script>
<style type='text/css'>
.true {
background-color: #6F6;
}
.false {
background-color: #FB0;
}
.undefined {
background-color: #FF0;
}
.datum {
font-family: monospace;
}
td {
padding: 4px;
}
</style>
</head>
<body>
<h1>Java on this PC</h1>
<h2>Overview</h2>
<p>This page endeavors to ascertain the installation, availability
& version of the Java installed on the client PC.
More importantly, it attempts to discover the information <b>without
invoking the Java Plug-In</b> itself.
The last part is what makes it different
to the Deployment Toolkit Script supplied by Oracle.
</p>
<script type='text/javascript'>
document.write("<h2>Browser Info.</h2>");
document.write(getBrowserInfo());
document.write("<h2>Basic Info.</h2>");
document.write("<table border='1'>");
document.write(get3CellRow('<b>Enabled</b>', isJava(), 'Java is enabled (1.1+) - IE info. (short of ActiveX) stops here'));
document.write(get3CellRow('<b>Version</b>', getVersion(), 'Maximum version reliably <em>known</em> to be available'));
if (isIE()) {
document.write(get3CellRow('<b>MSIE</b>', getIEVersion(), 'Maximum version reliably known to be available in IE, tested using ActiveX'));
}
document.write(get3CellRow('<b>JWS</b>', isJWS(), 'Java Web Start available (1.4.2+)'));
document.write(get3CellRow('<b>Plug-In 2</b>', isPlugin2(), 'Plug-In 2 available (1.6.0_10+)'));
document.write("</table>");
if (plugins.length>0) {
document.write("<h2>Navigator Plug-Ins</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Name</th><th>Version</th><th>File Name</th><th>Description</th></tr>");
for (var ii=0; ii<plugins.length; ii++) {
var t = plugins[ii].name;
if (t.indexOf("Java")>-1) {
document.write("<tr>");
document.write("<td>" + plugins[ii].name + "</td>");
document.write(getDataStyledCell(plugins[ii].version));
document.write("<td>" + plugins[ii].filename + "</td>");
document.write("<td>" + plugins[ii].description + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
if (mimes.length>0) {
document.write("<h2>Navigator Mime-Types</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Mime</th><th>Description</th><th>Types</th></tr>");
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
((t.indexOf("jpi")>0 || t.indexOf("deploy")>0 || t.indexOf("jnlp")>0 || t.indexOf("vm")>0) ||
mimes[ii].description.length>0)
) {
document.write("<tr>");
document.write("<td>" + mimes[ii].type + "</td>");
document.write("<td>" + mimes[ii].description + "</td>");
document.write("<td>" + mimes[ii].suffixes + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
</script>
<hr>
<h2>Description</h2>
<p>In order (if available) the information is:
<ul>
<li><b>Browser info. Table:</b> Not strictly related to Java - the
information in the other tables is determined without
further reference to any information shown in this table (except for the <code>appName</code> used for
identifying IE).
OTOH it is an helpful guide
as to what we should be <em>expecting</em>
from the other information. E.G. IE
will not show the Plug-In or Mime Type tables. <em>Only</em>
FF displays the plug-in version numbers.
</li>
<li><b>Basic info. Table</b>
<ul>
<li><b>Enabled</b>: Java is known to this browser and enabled, according to JavaScript <code>navigator.javaEnabled()</code>.</li>
<li><b>Version</b>: The maximum Java version known to be supported in this browser/PC.
It is set to <code>1.1</code> if the previous check is <code>true</code>, since the MSVM
was the first Java version the public could get in a browser, and the MSVM
implemented Java 1.1. Goes on to check
<code>application/x-java-applet;jpi-version</code>
in the mime types if available
(i.e. typically browsers that are <em>not</em> IE).
</li>
<li><b>MSIE</b> (IE Only): The maximum Java version known to be supported by this instance of Internet Explorer
as determined using ActiveX. It runs from 1.4.2, 1.5.0.. through 1.9.0.
</li>
<li><b>JWS</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was co-bundled.</li>
<li><b>Plug-In 2</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was introduced.</li>
</ul>
</li>
<li><b>Navigator Object Tables:</b>
<em>The rest of the info. is gleaned from the <code>navigator</code> object.
IE does not include this information.</em>
<ul>
<li><b>Plug-Ins</b>: More details of the Java related plugins.
Filtered for <code>Java</code> in the <code>name</code>.
A <code>description</code> showing "Next Generation Java Plug-in" or <code>name</code>
"Java Deployment Toolkit" should be 1.6.0_10+.</li>
<li><b>Mime-Types</b>: More information on the Java related Mime-Types.
Filtered in <code>mime</code> field for <code>'java'</code> + <code>('jpi'||'vm'||'deploy')</code>
or a non-empty <code>description</code>.
The value <code>java-deployment-toolkit</code> in the <code>mime</code>
is a good indicator of 1.6.0_10+.
</li>
</ul>
</li>
</ul>
</body>
</html>
mimetypes.js
// As a version string, this might be '1.4.2_31'.
// I.E. it is not a 'number' but a 'string' and therefore must be treated as a string.
var highestVersion = 'undefined';
var mimes = window.navigator.mimeTypes;
var plugins = window.navigator.plugins;
function isJava() {
return (
typeof(navigator.javaEnabled) !== 'undefined' &&
navigator.javaEnabled());
}
function getVersion() {
var version = 0;
if (isJava()) {
version = 1.1;
}
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
t.indexOf("jpi")>0 &&
t.indexOf("applet")>0
) {
var parts = t.split("=");
version = parts[parts.length-1];
}
}
if (highestVersion=='undefined') highestVersion = version;
return version;
}
function isJWS() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.4.2') {
className = true;
}
return className;
}
function isPlugin2() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.6.0_10') {
className = true;
}
return className;
}
var versionFamily = [
'1.9.0', '1.8.0', '1.7.0',
'1.6.0', '1.5.0', '1.4.2'
];
function getIEVersion() {
for (var i=0; i<versionFamily.length; i++) {
if (testUsingActiveX(versionFamily[i])) {
return versionFamily[i];
}
}
return false;
}
if (isIE() && getVersion()=='1.1') {
highestVersion = getIEVersion();
}
function isIE() {
return navigator.appName=='Microsoft Internet Explorer';
}
function testUsingActiveX(version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
// we need the typeof check here for this to run on FF/Chrome
// the check needs to be in place here - cannot even pass ActiveXObject
// as arg to another function
if (typeof ActiveXObject == 'undefined' || !ActiveXObject) {
alert('[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?');
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
}
function get3CellRow(cell1, cell2, cell3) {
var s = "" +
"<tr>" +
"<td class='" +
getClassName(cell1) +
"'>" +
cell1 +
"</td>" +
getDataStyledCell(cell2) +
"<td class='" +
getClassName(cell3) +
"'>" +
cell3 +
"</td>" +
"</tr>" +
"";
return s;
}
function getDataStyledCell(value) {
var s = "<td class='datum " +
getClassName(value) +
"'>" +
value +
"</td>";
return s;
}
function getClassName(val) {
var className = undefined;
if (
(val) ||
(!val) ||
(val!=="undefined")
) {
className = val;
}
return className;
}
function getBrowserInfo() {
var s = "";
var props = [
'appCodeName','appName','appVersion',
'userAgent',
'platform','cookieEnabled'
];
s += "<table border='1'>";
for (var i=0; i<props.length; i++) {
s+= "<tr>";
s+= "<td><b>";
s+= props[i];
s+= "</b></td>";
s+= "<td>";
s+= navigator[props[i]];
s+= "</td>";
s+= "</tr>";
}
s += "</table>";
return s;
}
Please note (be warned) this script was written by me, a Java programmer. Java programmers are typically the absolute worst people on the planet for writing JS, since we foolishly tend to presume. "It's JavaScript, how hard can it be?".
To write really good JavaScript is indeed an art.
Even worse, this was experimental code that was 'hacked out' with the intention of improving it later, but the project was abandoned and 'later' never arrived.
Caveat emptor.
In my app, I want to convert PDF file to images, but it looks like there is not a module in node.js. So i want to use the java application do the work.
Can we call java command in the cloud foundry node app?
Thanks.
Hong
OK, so I have built an express app that does the job;
app.js looks like this;
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, util = require('util')
, fs = require('fs')
, exec = require('child_process').execFile
, http = require('http');
process.env.MAGICK_TMPDIR = __dirname + '/tmp'
var app = express();
app.configure(function(){
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({uploadDir:__dirname + "/uploads"}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.post('/convert', function(req, res) {
var pdf_file = req.files.pdf.path;
var uploadsPath = __dirname + "/uploads"
var filename = pdf_file.split("/")[pdf_file.split('/').length - 1]
var out = __dirname + '/public/images/' + filename + '.png';
exec('convert', [pdf_file, '-append', out], function(err, stdout, stderr) {
res.redirect('/images/' + filename + '.png');
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
The index view looks like this (just a simple multipart form);
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<form action="/convert" method="post" enctype="multipart/form-data">
<label>PDF File</label>
<input type="file" name="pdf" />
<input type="submit" />
</form>
</body>
</html>
This all works fine on my private instance of Cloud Foundry (VCAP) but not on CloudFoundry.com, I think this is due to permissions issues. I will chase this up with the engineering team and find out if it is possible to call ImageMagick with the correct permissions.
=========
UPDATE
I have fixed the problem for CloudFoundry.com, it appears to stop ImageMagick from using /tmp as a temp dir the env var MAGICK_TMPDIR has to be set, you can see this in the top of app.js file now.
Am also redirecting to the image now rather then reading it in, works like a charm! - http://pdf2png.cloudfoundry.com
====
i have the following problem with this simple asp page:
<%
Dim javaTestObj set javaTestObj = GetObject("java:test")
if javaTestObj.mstrLogin("pepe", "pepe") then
Response.write("It Works!")
end if
%>
the Java class is the following:
public class test{
String pepe;
public test()
{
pepe="pepepepe";
}
public boolean mstrLogin(String usname, String uspass)
{
if((usname+uspass)==pepe)
return true;
else
return false;
}}
I have the compiled .class in every directory i've read it should be (C:\ClassPath\; C:\windows\java\trustedlib\ and in the same directory as the asp page) but i get no results =(
Any ideas of how it would work? I'm using IIS and the browser gives me this error:
Error type:
Microsoft VBScript compilation error (0x800A0401)
expected instruction end:
/login/pruebajava.asp, line 2, column 16
Dim javaTestObj set javaTestObj = GetObject
("java:test")
---------------^
It might be that you just accidently omitted the colon (:) character, but the first line should read
Dim javaTestObj : set javaTestObj = GetObject("java:test")
because in classic ASP you are not allowed to declare and set a variable in the same statement
Dim myVariable = "hello World" '//Error! Not allowed.
Dim myOtherVar
myOtherVar = "hello World" '//OK
Dim myVar : myVar = "Hello World" '//OK
This question already has answers here:
What does servletcontext.getRealPath("/") mean and when should I use it
(4 answers)
Closed 4 years ago.
getRealPath() is returning the actual path in the local system, but returns null when deployed with a .war file.
<%# page import="java.io.*" %>
<%# page contentType="text/html;charset=ISO-8859-1" %>
<%
int iLf = 10;
char cLf = (char)iLf;
String a= application.getResource("/");
//String myfile = application.getRealPath("/")+ "generate.xml";
//String myfile = request.getContextPath()+"generate.xml";
//String myfile = request.getRealPath("/")+"generate.xml";
out.println(myfile);
File outputFile = new File(myfile);
outputFile.createNewFile();
FileWriter outfile = new FileWriter(outputFile);
outfile.write(" <?xml version='1.0' encoding='UTF-8'?> "+cLf);
outfile.write(" <playlist version='1' xmlns = 'http://xspf.org/ns/0/' > " +cLf);
outfile.write(" <title>My Band Rocks Your Socks</title> "+cLf);
outfile.write("<trackList>"+cLf);
%>
<%! String[] sports; %>
<%
sports = request.getParameterValues("sports");
out.println("<html><body><h1>hello</h1></body></html>");
if (sports != null)
{
for (int i = 0; i < sports.length; i++)
{
// outfile.writeln (sports[i]);
String total=sports[i];
String[] sa=total.split("[,]");
// String[] sub=new String();
outfile.write("<track>"+cLf);
for (int j=0;j<sa.length;j++)
{
// outfile.writeln(sa[j]);
// outfile.writeln("sa["+j+"]="+sa[j]);
if( j == 0)
{
outfile.write("<location>" + sa[0] +"</location>"+cLf);
}
else if (j == 1)
{
outfile.write("<image>" + sa[1] +"</image>"+cLf);
}
else if( j==2)
{
outfile.write("<title>" + sa[2] +"</title>"+cLf);
}
}// end of inner for loop()
outfile.write("</track>"+cLf);
//outfile.writeln();
}// end of outer for()
}
//else outfile.writeln ("<b>none<b>");
outfile.write(" </trackList> "+cLf);
outfile.write(" </playlist> "+cLf);
outfile.close();
%>
<object type="application/x-shockwave-flash" width="400" height="170"
data="xspf_player.swf?playlist_url=generate.xml">
<param name="movie" value="xspf_player.swf?playlist_url=generate.xml" />
</object>
Can anyone provide me with an alternative for this?
It would be very helpful if you showed some sample code too.
For a start, ServletRequest.getRealPath(String path) is deprecated. The appropriate replacement is:
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath(request.getContextPath());
However, the API docs for ServletContext.getRealPath(String path) state:
"This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive)."
So the API is fulfilling its contract! However, all is not lost, as you can load a resource from the WAR using the following method, as defined in ServletContext:
ServletContext context = session.getServletContext();
InputStream is = context.getResourceAsStream("generate.xml");
Bit late, but I came across this question when I was having this issue in WebLogic. My solution was to add this to my weblogic.xml:
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-web-app>
<container-descriptor>
<show-archived-real-path-enabled>true</show-archived-real-path-enabled>
</container-descriptor>
</weblogic-web-app>
I found this solution better for when you don't want to (or can't) edit the configuration on the WebLogic server.
do you use Weblogic?
If yes - then this is a Weblogic issue which you may fix in Weblogic admin console ->Domain->Web Applications - click the checkbox "Archived Real Path Enabled".
See: http://ananthkannan.blogspot.com/2009/12/servletcontextgetrealpath-returns-null.html
I had the same problems too. Calling getRealPath() return null when deployed to a standalone server. After searching around for a while, I found the solution for this, it's not in the code. It's in the config of your web server.
For me it's Weblogic 10.3, you go to Home - - Configuration - Web Application, set Archived Real Path Enabled to true. Restart server and everything works fine.
Hope this help,
Regards.
This solves the problem also:
weblogic.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app">
<container-descriptor>
<index-directory-enabled>true</index-directory-enabled>
<show-archived-real-path-enabled>true</show-archived-real-path-enabled>
</container-descriptor>
<virtual-directory-mapping>
<local-path>bla.war</local-path>
<url-pattern>*</url-pattern>
</virtual-directory-mapping>
<context-root>bla</context-root>
I do not believe it is possible to do what you're trying to do.
You should use getResource to read the xml file from inside your war file (this also works without war)
servletContext.getResourceAsStream("/generate.xml")
The leading slash depends on where the generate.xml is stored.
Take note context.getRealPath() can return null when there is user permission problem, check Web server running under which user.
if you want to write into
use
this.getClass().getResource("/").getPath();
to get the path
The following fix working fine for me.
// I am using Struts2
ServletContext sc = (ServletContext) ac.get(StrutsStatics.SERVLET_CONTEXT);
fileInputStream = sc.getResourceAsStream("test.xls");
After deployed war file, I am able to get the file from the context path.
The following fix my problem.
public EHWInit()
{
String resetRootPath = "";
try{
resetRootPath = this.getClass().getResource("/").getPath();
boolean isWinOS = System.getProperty("os.name").startsWith("Windows");
if( isWinOS )
{resetRootPath = resetRootPath.substring(1, resetRootPath.lastIndexOf("chucec"));}
else
{resetRootPath = resetRootPath.substring(0, resetRootPath.lastIndexOf("chucec"));}
resetRootPath = resetRootPath.replace("%20", " ");
System.out.println("EHWInit#75:resetRootPath=" + resetRootPath);
When you try to get getRealPath by this.getClass().getResource("/").getPath() when OS is Windows, then you may get a string like following:
EHWInit#73:getPath=/C:/Program%20Files%20(x86)/Apache%20Software%20Foundation/Tomcat%208.5/webapps/chucec/WEB-INF/classes/
Therefor, you need do some extra works on the returning string.Furthermore, if you want to get getRealPath by request. You can replace the code like follows:
public void resetSystemPath(HttpServletRequest paramHttpServletRequest)
{
//String str = paramHttpServletRequest.getRealPath("/");
HttpSession session = paramHttpServletRequest.getSession(true);
String str = session.getServletContext().getRealPath("/");
System.out.println("getRealPath:"+str);