Sending File from JSP to Servlet - java

Please have a look at he following code
JSP
<%--
Document : index
Created on : Nov 27, 2012, 1:11:48 PM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div>
<div>Content for New Div Tag Goes Here</div>
<p> </p>
<p> </p>
<p> </p>
<div>
<form method="post" action="FileSelector" enctype="multipart/form-data">
Select File: <input type="file" name="location"/></div>
<br>
<input type="submit" value="Submit"/>
</form>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</div>
</body>
</html>
Servlet
package importWizard;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileSelector extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
PrintWriter pw = response.getWriter();
File location = (File)request.getParameter("location");
pw.write(location);
}
}
As you can see, I am unable to send the file from JSP to Servlet. I don't need to send the file, but at least the complete location of the file (It is only sending the file name). How can I send the file or the complete location of the file from JSP to servlet?

I don't need to send the file, but at least the complete location of the file (It is only sending the file name). How can I send the file or the complete location of the file from JSP to servlet?
That's not possible using standard HTML <input type="file"> element. It sends merely the entire file contents along with the filename as that's basically the only way for the server to get the file contents. The server has namely no direct access to the client's local disk file system, so the client's absolute disk file system path as sole information would have been useless. Note that the MSIE browser will due to a security bug send the full absolute client side disk file system path along instead of only the filename, but that's thus not how things are supposed to work.
If you really need to have only the client's absolute disk file system path, then your best bet is to create a (signed) applet or webstart application which obtains it by JFileChooser and finally embed it in the web page.
See also:
How to get the file path from HTML input form in Firefox 3

Related

Getting Attribute [modelAttribute] invalid for tag [form] according to TLD

I am completely new to Spring and I am getting error "Getting Attribute [modelAttribute] invalid for tag [form] according to TLD"
while running below code.
<%# 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>Personal Info Page</title>
</head>
<body>
<center><h1>Personal Info Page</h1></center>
<form:form method="post" action="/user-web/processuserregistration.do" modelAttribute="user" >
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lasttName"/></td>
</tr>
<tr>
<td>Middle Name:</td>
<td><form:input path="middleName"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>
</body>
</html>
After running the piece of code, I am getting below error :
Oct 07, 2019 9:31:44 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/user-web] threw exception [/jsp/person.jsp (line: [9], column: [0]) Attribute [modelAttribute] invalid for tag [form] according to TLD] with root cause
org.apache.jasper.JasperException: /jsp/person.jsp (line: [9], column: [0]) Attribute [modelAttribute] invalid for tag [form] according to TLD
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:292)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:115)
Is there anything I can do to resolve the error ?
I am completely new to Spring
Well,
I am going to say upfront, I am not a JSP developer, but I use Java and HTML/CSS/JS all day. I have not compiled a JSP page, but I know it is just HTML with some script. What I can help you with, is just giving you a small heads up that the word "attribute" when used with/about HTML refers to the "assignment-looking-like" things that are inside of an HTML element. For instance, you are using an HTML 'form' element.
According to w3schools.com, which I refer to at least once a day when I'm coding, the HTML form element is allowed the following attributes... The text inside the next "Comment Block" has been word-for-word copied from the following link: https://www.w3schools.com/html/html_forms.asp
The Action Attribute The action attribute defines the action to be performed when the form is submitted. Normally, the form data is sent
to a web page on the server when the user clicks on the submit button.
In the example above, the form data is sent to a page on the server
called "/action_page.php". This page contains a server-side script
that handles the form data:
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current
page.
The Target Attribute The target attribute specifies if the submitted result will open in a new browser tab, a frame, or in the
current window. The default value is "_self" which means the form
will be submitted in the current window. To make the form result open
in a new browser tab, use the value "_blank"... Example:
<form action="/action_page.php" target="_blank">
Other legal values are "_parent", "_top", or a name representing the
name of an iframe.
The Method Attribute The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data:
<form action="/action_page.php" method="get">
or
<form action="/action_page.php" method="post">
1: https://www.w3schools.com/html/html_forms.asp
Important Point being: HTML Form's may not have the "modelAttribute='user'" line that you have added...
<form:form method="post" action="/user-web/processuserregistration.do" modelAttribute="user" >
According to the Oracle Documentation, a TLD is the Tag Library Descriptor - and it is used in JSP programming. Here is a link to Oracle's TLD page. Again, I'm sorry for posting as non-JSP guy... but maybe this will help :)
https://docs.oracle.com/cd/E17904_01/web.1111/e13722/tld.htm#TAGLB120

Http404 error while click the submit button (Servlet question)

Guys! I am new to servlet. I tried to follow the step with book to create a servlet. It's just a login form where user enter the userid and password click the login, it should then display the input value in webpage. However, when I enter the userId and password, I get Http404 error.
I was wondering something maybe wrong with context.xml but I am not sure.
I also tried to mapping the servlet in xml, but still get the error.
here is my html
<!DOCTYPE html>
<html>
<head>
<title>USER LOGIN</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<form action="UserServlet" method="get">
<!-- Name text Field -->
<p>
<label>User ID</label>
<input type ="text" name="userId" size="30"/>
</p>
<p>
<label>User Password</label>
<input type ="text" name="userPassword" size="30"/>
</p>
<!--Button for submit -->
<input type ="submit" name="Login" value="LogIn"/>
<input type ="button" value="LogOut" onclick="self.close()"/>
</form>
</body>
here is my servlet.java
public class UserServlet extends HttpServlet
{
//process the HTTP GET REQUEST//
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
//get the data
String userId=request.getParameter("userId");
String passWord=request.getParameter("userPassWord");
//determine the input if user missing these two send back the message
if (userId.isEmpty()&&passWord.isEmpty())
{
out.println("UserId and passWord can not be empty.");
}
else
{
out.println("<p>your id is "+userId);
out.println("<br>your password is"+passWord);
out.println("<br>You entered the data successfully </p>");
}
}
}
here is my context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/userLogin"/>
I didn't change any thing in context.xml
its working when I run the project, but once I click the button it just gives me
Type Status Report
Message /userLogin/UserServlet
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
can you check what is the servlet mapping provided in web.xml. I think the mapping would not be matching the request.
or you can post the web.xml

Using servlet form on jsp page without redirecting to servlet

I'm working on a project that requires a JSP page which includes another JSP page that processes a login form using a Servlet.
The problem I am coming upon is that whenever I try to login, the servlet works, the possible mistakes in the form show up, but the link redirects to the Servlet and does not stay on the same JSP page.
Example of how it looks with a template:
-JSP Page before clicking login
link: JSPpage.jsp
**text outside of included login form**
<included JSP page with the login form>
Email: something
Password: ******
-JSP Page after clicking login
link: MyServlet
<login form>
Email: something
Error: invalid email
Password:
Basically the highlighted text that is outside of the included form disappears. That is because the link changed to Servlet.
I want to process the login from inside the JSP Page, so that any template around the login form will remain the same and will not get deleted (the page won't redirect).
I've searched all over for a solution to this problem.
I realize that my explanation is really weak & I apologize for that.
Please be so kind and help me with this. I do not wish to use AJAX or JavaScript or a frame to do that unless it's a MUST and can't be done with JSP/Servlet directly.
Thank you,
Matej.
EDIT:
Servlet: Prijava.java
package servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import baza.Podatki;
public class Prijava extends HttpServlet{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
HttpSession session = request.getSession();
String email=request.getParameter("email");
String geslo=request.getParameter("geslo");
int st=0;
if (email!=null){
try {
if(!Podatki.shranjenEmail(email))
request.setAttribute("napakaPrijava", "Email ne obstaja!");
else if (!Podatki.preveriPrijavoUporabnik(email, geslo)&&!Podatki.preveriPrijavoZaposlen(email, geslo))
request.setAttribute("napakaPrijava", "Nepravilno geslo!");
else{
request.setAttribute("prijava",true);
session.setAttribute("email", email);
}
request.setAttribute("email", email);
} catch (SQLException e) {
e.printStackTrace();
}
}
else if (request.getParameter("odjava")!=null)
session.removeAttribute("email");
System.out.println(session.getAttribute("email"));
System.out.println("Prijava:"+request.getParameter("prijava"));
RequestDispatcher view = getServletContext().getRequestDispatcher("/Prijava.jsp");
view.forward(request, response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
doPost(request,response);
}
}
Prijava.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page isELIgnored="false" %>
<!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=UTF-8">
<title>Renta Ferari</title>
<link rel="stylesheet" type="text/css" href="obrazci.css">
</head>
<body >
<div style="width:250px;height:110px; border:solid 1px; bordor-radius:15px; border-color:red">
<c:choose>
<c:when test="${!prijava}">
<form method="post">
<table align="center">
<tr><td>E-mail:</td> <td><input type="text" name="email" class="vnos" value="${email}"></td></tr>
<tr><td>Geslo: </td><td><input type="password" name="geslo" class="vnos"><br></td></tr>
<tr><td colspan="4"><c:out value="${napakaPrijava}"></c:out></td></tr>
<tr><td colspan="2"><input type="submit" name="prijava" value="Prijava"></td></tr>
</table>
</form>
</c:when>
<c:otherwise>
<div align="center">
Prijavljeni ste kot: <c:out value="${email}"></c:out>
<form method="post" action="login">
<input type="submit" name="odjava" value="Odjava">
</form>
</div>
</c:otherwise>
</c:choose>
</div>
</body>
</html>
So basically I want to include the above code inside a new JSP along with my template's header, content & footer.
I tried many options and "solutions" like jsp:include, <%# include file .. etc. None worked as I wanted them to. Whenever I clicked on the submit button for the login, it redirected me to the servlet's URL, thus overwriting the included header, content & footer.
I am not asking for you to code it, I'd just like some insight on how I can do this, since many websites do that.
From what your code and what you say, it sounds like you have a login form included on each page of your application. When the user uses the form you want them to be redirected back to whatever page they were viewing before submitting the login form.
What you could do is include servlet path of the orginal servlet or jsp as a hidden field in your form:
<input type="hidden" name="forwardTo" value="${pageContext.request.servletPath}" />
Then you can forward to this in your Servlet:
String forwardTo= request.getParameter("forwardTo");
RequestDispatcher view = getServletContext().getRequestDispatcher(forwardTo);
view.forward(request, response);

JSP and servlet does not respond to forwarding

I'm having some problems with forwarding and where the JSP file refuses to forward even though I'm forwarding : I start from here :
index.html :
<!DOCTYPE html>
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form action="loginPage">
Username: <input type="text" name="username"><br>
Password : <input type="text" name="password"><br>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
with the screen :
Then I move to that JSP file - adminPage.jsp:
<!DOCTYPE html>
<html>
<head><title>System Administrator Page</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Hello ${name.firstName} ${name.lastName} , You've logged in successfully!</h1>
<h1>
Please choose one of the following options
</h1>
<fieldset>
<legend>Add a new manager to the bank system</legend>
<form action="adminAdds1">
Press here to continue
</form>
</fieldset>
<fieldset>
<legend>Add a new employee to the bank system</legend>
<form action="adminAdds2">
Press here to continue
</form>
</fieldset>
</body></html>
with that screen :
but when I click either one of the two options , and move to adminAddNewEmployee.jsp of adminAddNewManager.jsp , I get this , over and over again , even though both files are located at the same folder of adminPage.jsp:
HTTP Status 404 -
--------------------------------------------------------------------------------
type Status report
message
description The requested resource () is not available.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.28
where the project tree is :
How can I fix this ? I understand that WEB-INF requires some forwarding , but where do I put the forwarding ? in the JSP ?
but note that I use href and it still failing .
Regards
EDIT:
in adminPage.jsp is added that :
<fieldset>
<legend>Add a new manager to the bank system</legend>
<form action="adminAdds1">
Press here to continue
</form>
</fieldset>
and created a new servlet Admin1.java :
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/adminAdds1")
public class Admin1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
request.getRequestDispatcher("/WEB-INF/results/adminPage.jsp").forward(request, response);
}
}
but when I run the all thing again I get :
HTTP Status 404 - /WebBank/src/servlets/Admin1
--------------------------------------------------------------------------------
type Status report
message /WebBank/src/servlets/Admin1
description The requested resource (/WebBank/src/servlets/Admin1) is not available.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.28
Files inside WEB-INF are not directly accessible from client.
One way would be change
<a href="SomeServletmapping">
Inside SomeServlet get method do
request.getDispatacher(yourJSP).forward();
Second way:
move those JSPs outside the WEB-INF folder.
Take a look here
Press here to continue
According to specification nothing is accessible (directly) inside WEB-INF folder.
It can be possible to do it using
<%# include file="WEB-INF/path/to/expected.jsp" %>
Or dispatching to JSP using request dispather or using framework like Spring!

Changing index.html refuse to take place in actual running of a web application

Something very weird is happening when I try to edit my index.html file .
I'm working with jsp-s and servlets , in Java.
When I try to update one of the fields , for instance :
<!DOCTYPE html>
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Bank application</th></tr>
</table>
<br/>
<fieldset>
<legend>Bank Account Balance</legend>
<form action="show-balance">
Customer ID (id001, idffffffffffffffffdsafds002, id003):
<input type="text" name="cusdddddddddddddddddddddddddddtomerId"/><br/>
<input type="submit" value="Sddddddddddddddddddddddddddddddddddddddhow Balance"/>
</form>
</fieldset>
<br/>
// from here, the rest is the same as the above
I get this (same as before) :
Why when changing the index.html file , no change takes place ?
I'm using :
Apache 7
Xampp
Thanks
Browsers will cache HTML files unless you explicitly tell the browser to refresh (ctrl + F5). I'm guessing you're just loading the cached version of the HTML.

Categories