I gave a link to forgotpassword.jsp on my index.html page but after sometime i decided to change it so i created a new html file forgotpassword.html the body is similar in both the files but image is shown in forgotpassword.jsp but not in forgotpassword.html . forgotpassword.jsp further goes to pass.jsp and i did the same thing for it also and created pass.html for it, same thing is happening in it pass.jsp is showing image but pass.html is not. Could someone tell me why this is happening ?
and please check the filter if there is something missing or wrong with it.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
header {
background-color:lightsteelblue;
color:white;
text-align:center;
padding:5px;
}
nav {
line-height:30px;
height:300px;
width:100px;
float:left;
padding:5px;
}
section {
width:600px;
float:right;
padding:220px;
}
footer {
background-color:black;
color:white;
clear:both;
float:bottom;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color: lightsteelblue">
<header>
<canvas id="myCanvas" width="500" height="100" style="border:2px solid black; background-color:burlywood ">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "45px Arial";
ctx.strokeText("File Tracking System", 50, 50);
</script>
</header>
Forgot Your Password
<section>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user"/>
<br />
Password: <input type="password" name="pwd"/>
<br />
<input type="submit" value="Login"/>
</form>
<img src="css/NSIC-logo1.png" width="537" height="267" alt="NSIC-logo1"/>
</section>
<footer>Copyright 2016 NSIC. All right reserved.</footer>
</body>
</html>
forgotpass.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Forgot Password Page</title>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:5px;
}
nav {
line-height:30px;
height:300px;
width:120px;
float:left;
padding:5px;
}
section {
width:800px;
float:right;
padding:130px;
}
footer {
background-color:black;
float:bottom;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<header><h3>File Tracking System!!</h3>
<br>
</header>
<nav>
<form action="forgotServlet" method="POST" >
User Name:<input type="text" name="name" value="" size="20" />
Email:<input type="text" name="email" value="" size="20" />
New Password:<input type="text" name="pass1" value="" size="20" />
Repeat Password:<input type="text" name="pass2" value="" size="20" />
<input type="submit" value="submit" name="submit" />
</form>
</nav>
<section><img src="css/NSIC-logo1.png" width="537" height="267" alt="NSIC-logo1"/></section>
<footer>
Copyright 2016 NSIC. All right reserved.
</footer>
</body></html>
forgotpass.html
<!DOCTYPE html>
<html>
<head>
<title>Forgot Password Page</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:5px;
}
nav {
line-height:30px;
height:300px;
width:120px;
float:left;
padding:5px;
}
section {
width:800px;
float:right;
padding:130px;
}
footer {
background-color:black;
float:bottom;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<header><h3>File Tracking System!!</h3>
<br>
</header>
<nav>
<form action="forgotServlet" method="POST" >
User Name:<input type="text" name="name" value="" size="20" />
Email:<input type="text" name="email" value="" size="20" />
New Password:<input type="text" name="pass1" value="" size="20" />
Repeat Password:<input type="text" name="pass2" value="" size="20" />
<input type="submit" value="submit" name="submit" />
</form>
</nav>
<section><img src="css/NSIC-logo1.png" width="537" height="267" alt="NSIC-logo1"/></section>
<footer>
Copyright 2016 NSIC. All right reserved.
</footer>
</body></html>
This is my AuthenticationFilter-
package bean;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AuthenticationFilter implements Filter {
private ServletContext context;
#Override
public void init(FilterConfig fConfig) throws ServletException {
this.context = fConfig.getServletContext();
this.context.log("AuthenticationFilter initialized");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setDateHeader("Expires", 0); // Proxies.
String uri = req.getRequestURI();
this.context.log("Requested Resource::" + uri);
HttpSession session = req.getSession(false);
if (session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet") || uri.endsWith("forgotpass.jsp") || uri.endsWith("doesnotexist.jsp") || uri.endsWith("pass.jsp"))) {
this.context.log("Unauthorized access request");
res.sendRedirect("index.html");
} else {
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
//close any resources here
}
}
Edit: chat-conversation-with-rahul The problem is real. I was unable to solve it.
There is a problem with File Structure of your HTML and JSP Files. As #aksappy commented, check in developer tools(CTRL+SHIFT+I for chrome) for console errors. Also, check the src attribute of your <img> tag on both html and jsp file from developer tools.
Your code is working perfectly.
Proof
JSP IMAGE
HTML IMAGE
Related
I did the tutorial from https://www.tutussfunny.com/registation-form-using-react-js-and-spring-boot/ but the whole frontend seems to be glitchy.
I am a backend dev and I am struggling with JS.
Calling the App.js from a html just doesn't work because of the imports causing
"Uncaught SyntaxError: Cannot use import statement outside a module". Also, the return of HTML in registration.js is causing syntax errors. Can someone who is fluent in JS can look at the code and tell me what should be fixed?
Current code:
registration.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" type="text/css">
<!-- Momentum CSS -->
<link href="registration.css" rel="stylesheet">
</head>
<body>
<section>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="registration.js"></script>
</section>
<div className="register-container">
<form className="register-form" onSubmit={handleSubmit}>
<br></br>
<h1>Register</h1>
<p>Fill in the Information Below</p>
<input type="text"
name="id"
placeholder="id"
onChange="setId(event.target.value);"
/>
<input type="text"
name="firstname"
placeholder="Firstname"
onChange="setFname(event.target.value);"
/>
<input type="text"
name="lastname"
placeholder="lastname"
onChange="setLname(event.target.value);"
/>
<input type="text"
name="email"
placeholder="email"
onChange="setEmail(event.target.value);"
/>
<input type="text"
name="username"
placeholder="username"
onChange="setUsername(event.target.value);"
/>
<button type="submit">Register</button>
</form>
</div>
</body>
</html>
App.js
import Register from "registration";
import 'App.css';
import {BrowserRouter,Switch,Route} from 'react-router-dom';
function App() {
return (
<div className="App">
<BrowserRouter>
<Switch>
<Route path="/" exact>
<Register/>
</Route>
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
Registration.js
function Register()
{
const [id, setId] = useState("");
const [firstname, setFname] = useState("");
const [lastname, setLname] = useState("");
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
async function handleSubmit(event)
{
event.preventDefault();
try
{
await axios.post("http://localhost:8080/save",
{
id: id,
fname: firstname,
lname : lastname,
email : email,
username : username,
});
alert("User Registration Successfully");
setId("");
setFname("");
setLname("");
setEmail("");
setUsername("");
}
catch(err)
{
alert("User Registation Failed");
}
}
}
I tried to create POST request to send my form to the Spring server, but I'm only getting this error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'form' available as request attribute
My controller content:
// Form post handler
#PostMapping("/")
public String home(#ModelAttribute Form form, BindingResult bindingResult, Model model) {
Gson g = new Gson();
Form form_new = g.fromJson(JavaWebApplication.runtimeJsonContent, Form.class);
model.addAttribute("form", form);
model.addAttribute("ip", form.IP);
model.addAttribute("gateway", form.Gateway);
model.addAttribute("port", form.Port);
model.addAttribute("IncomingConnections", form.IncomingConnections);
return "index";
}
Here is my Form model:
public class Form {
public String IP;
public String Gateway;
public int Port;
public boolean IncomingConnections;
public int QoSEnable = 0;
public Form(){}
public Form(String IP, String gateway, int port, boolean incomingConnections) {
this.IP = IP;
this.Gateway = gateway;
this.Port = port;
this.IncomingConnections = incomingConnections;
this.QoSEnable = 0; // Assert that 0 is default
ExportToJson(this);
}
public Form(String IP, String gateway, int port, boolean incomingConnections, int qosEnable) {
this.IP = IP;
this.Gateway = gateway;
this.Port = port;
this.IncomingConnections = incomingConnections;
this.QoSEnable = qosEnable;
ExportToJson(this);
}
}
And my index.html webpage bound on / :
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" th:href="#{./styles/main.css}">
<title>Document</title>
</head>
<body>
<form method="post" action="#" th:action="#{/}" th:object="${form}">
<div id="container">
<img src="https://kable-swiatlowodowe.net.pl/wp-content/uploads/2017/08/mikrotik.png" width="20%" style="margin-bottom: 5%;">
<br>
<div id="input-el">
<div class="input-element"><input type="text" placeholder="IP" name="IP" th:value="${ip}" th:field="*{IP}" id="input-element-ip"></div>
<div class="input-element"><input type="text" placeholder="Gateway" th:value="${gateway}" th:field="*{Gateway}" name="Gateway" id="input-element-gateway"></div>
<div class="input-element"><input type="number" placeholder="Port" th:value="${port}" th:field="*{Port}" name="Port" id="input-element-port"></div>
</div>
<div id="checkbox-el">
Incoming connections:<br>
<label><input type="checkbox" th:checked="${IncomingConnections}" th:field="*{IncomingConnections}" name="conections" id="conections-el">Allow</label>
</div>
QoS Mode<br>
<label><input type="radio" name="qos-mode-el" id="input-radio-game-first" checked>Game First</label>
<label><input type="radio" name="qos-mode-el" id="input-radio-multimedia-first">Multimedia First</label>
<button type="submit">Save</button>
</div>
</form>
</body>
</html>
Sample Postman request:
Response for this request:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles/main.css">
<title>Document</title>
</head>
<body>
<form method="post">
<div id="container">
<img src="https://kable-swiatlowodowe.net.pl/wp-content/uploads/2017/08/mikrotik.png" width="20%" style="margin-bottom: 5%;">
<br>
<div id="input-el">
<div class="input-element">
<input type="text" placeholder="IP" name="IP" value="" id="input-element-ip"></div>
<div class="input-element">
<input type="text" placeholder="Gateway" value=""name="Gateway" id="input-element-gateway"></div>
<div class="input-element">
<input type="number" placeholder="Port" value="0" name="Port" id="input-element-port"></div>
</div>
<div id="checkbox-el">
Incoming connections:<br>
<label><input type="checkbox" name="conections" id="conections-el">Allow</label>
</div>
QoS Mode<br>
<label><input type="radio" name="qos-mode-el" id="input-radio-game-first" checked>Game First</label>
<label><input type="radio" name="qos-mode-el" id="input-radio-multimedia-first">Multimedia First</label>
<button type="submit">Save</button>
</div>
</form>
</body>
</html>
Each value content is clear
Any idea how to make this binding work correctly?
you are not passing the form object to your thymeleaf template
Do this -
#GETMapping("/")
public String getHome(Model model){
model.addAttribute("form", new Form());
return "index";
}
This will return a Form object to your thymleaf and then it can process the data in your code --
<form method="post" action="#" th:action="#{/}" th:object="${form}">
// This will now receive form object
</form>
I'm working on a simple java web app that displays a page in which you can add a new client and then it shows another pages that presents the client newly added but i keep getting this error:
HTTP Status 404 - /LearningJSP/AddClient
type Status report
message /LearningJSP/AddClient
description The requested resource is not available.
I don't get where the problem is.
Here are the files of my app.
the "add new client" .jsp
<%# page pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Création d'un client</title>
</head>
<body>
<div>
<form method="get" action="AddClient">
<fieldset>
<legend>Informations client</legend>
<label for="nomClient">Nom <span class="requis">*</span></label>
<input type="text" id="nomClient" name="nomClient" value="" size="20" maxlength="20" />
<br />
<label for="prenomClient">Prénom </label>
<input type="text" id="prenomClient" name="prenomClient" value="" size="20" maxlength="20" />
<br />
<label for="adresseClient">Adresse de livraison <span class="requis">*</span></label>
<input type="text" id="adresseClient" name="adresseClient" value="" size="20" maxlength="20" />
<br />
<label for="telephoneClient">Numéro de téléphone <span class="requis">*</span></label>
<input type="text" id="telephoneClient" name="telephoneClient" value="" size="20" maxlength="20" />
<br />
<label for="emailClient">Adresse email</label>
<input type="email" id="emailClient" name="emailClient" value="" size="20" maxlength="60" />
<br />
</fieldset>
<input type="submit" value="Valider" />
<input type="reset" value="Remettre à zéro" /> <br />
</form>
</div>
</body>
</html>
Servlet
package Controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Client;
/**
* Servlet implementation class ClientServ
*/
public class ClientServ extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String Add = "/affichierClient.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String Nom = request.getParameter("nomClient");
String Prenom = request.getParameter("prenomClient");
String Adresse = request.getParameter("adresseClient");
String Telephone = request.getParameter("telephoneClient");
String Email = request.getParameter("emailClient");
String message;
if(Nom.trim().isEmpty() || Adresse.trim().isEmpty() ||
Telephone.trim().isEmpty()) {
message="Vous n'avez pas rempli tous les champs";
}
else {
message="Client crée avec succès";
}
Client client = new Client();
client.setNom(Nom);
client.setPrenom(Prenom);
client.setAdresse(Adresse);
client.setEmail(Email);
client.setTelephone(Telephone);
request.setAttribute("client", client);
request.setAttribute("message", message);
this.getServletContext().getRequestDispatcher(Add).forward(request, response);
}
}
The jsp page to display the newly added client
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="UTF-8"%>
<!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>Affichage de client</title>
</head>
<body>
<p class="info"> ${message} </p>
<p>Nom: ${client.Nom}</p>
<p>Prenom: ${client.Prenom}</p>
<p>Adresse: ${client.Adresse}</p>
<p>Numéro de télephone: ${client.Telephone}</p>
<p>Email: ${client.Email}</p>
</body>
</html>
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>WebApp</display-name>
<servlet>
<servlet-name>AddClient</servlet-name>
<servlet-class>Controllers.ClientServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddClient</servlet-name>
<url-pattern>/AddClient</url-pattern>
</servlet-mapping>
</web-app>
It is likely that the problem comes from that line:
<form method="get" action="AddClient">
As you give a relative URL instead of an absolute one, it is used to build a full URL starting from the current one.
So if the previous URL was /LearningJSP the following request is sent to /LearningJSP/AddClient when it should use /AddClient ending in a normal 404 error.
Fix: just use an absolute URL:
<form method="get" action="/AddClient">
Read about how to create breakpoints in eclipse.
Place a breakpoint here
String Nom = request.getParameter("nomClient");
Read about how to start a debugging session in eclipse.
Start one. If The execution never stops at the breakpoint means the configuration is wrong. If it does stop, means that the 404 is thrown in a subsequent request.
If you only have doGet(...) handling requests then you probably have url path issues
I'm having a problem that when my JSP loads, it returns a blank page. The page is supposed to call the Controller with the parameter "btnListar" and call de DAO to list entries from the database. I debugged the code (I'm using NetBeans to build this app), and the values are being passed correctly, the variables are filled with entries from the DB that the DAO gets, but the page the browser is supposed to show just doesn't appear, it's blank.
My Controller:
public class ExperienciaControle extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String action = request.getParameter("action");
switch (action) {
case "btnCadastrar": {
Experiencia exp = new Experiencia();
exp.setEmpresa(request.getParameter("txtEmpresa"));
exp.setCargo(request.getParameter("txtCargo"));
exp.setData(request.getParameter("txtData"));
exp.setAtribuicoes(request.getParameter("txtAtrib"));
ExperienciaDAO dao = new ExperienciaDAO();
dao.insertExp(exp);
break;
}
case "btnAtualizar": {
Experiencia exp = new Experiencia();
exp.setEmpresa(request.getParameter("txtEmpresa"));
exp.setCargo(request.getParameter("txtCargo"));
exp.setData(request.getParameter("txtData"));
exp.setAtribuicoes(request.getParameter("txtAtrib"));
ExperienciaDAO dao = new ExperienciaDAO();
dao.updateExp(exp);
break;
}
case "btnRemover": {
Experiencia exp = new Experiencia();
exp.setId(Integer.parseInt(request.getParameter("chckId")));
ExperienciaDAO dao = new ExperienciaDAO();
dao.deleteExp(exp);
break;
}
case "btnListar": {
ExperienciaDAO dao = new ExperienciaDAO();
ArrayList<Experiencia> expArray = dao.selectExp();
request.setAttribute("expArray", expArray);
break;
}
default:
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# page import="java.util.*" %>
<%# page import="Modelo.*" %>
<!DOCTYPE html>
<html>
<head>
<script src="../js/dropdown.js"></script>
<script src="../js/jquery-1.12.3.min.js"></script>
<script src="../js/lista.js"></script>
<link type="text/css" rel="stylesheet" href="../css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="../css/admin.css" />
<link type="text/css" rel="stylesheet" href="../css/dropdown.css" />
<link type="text/css" rel="stylesheet" href="../css/body.css" />
<link type="text/css" rel="stylesheet" href="../css/main.css" />
<link type="text/css" rel="stylesheet" href="../css/fonts.css" />
<title>Currículo | Administração</title>
</head>
<body>
<div class="body">
<div>
<nav id="primary_nav_wrap">
<ul>
<li class="current-menu-item">Home</li>
<li><a>Experiência</a>
<ul>
<li>Adicionar</li>
<li>Listar</li>
</ul>
</li>
<li><a>Educação</a>
<ul>
<li>Adicionar</li>
<li>Atualizar</li>
<li>Remover</li>
</ul>
</li>
<li><a>Habilidade</a>
<ul>
<li>Adicionar</li>
<li>Atualizar</li>
<li>Remover</li>
</ul>
</li>
</ul>
</nav>
</div>
<div id="divAddExp" style="display:none" class="cadastros">
<form name="frmExp" action="../ExperienciaControle" method="POST">
<h1 style="font-family: Roboto">Cadastro de Experiência</h1><br />
<label for="lblEmpresa">Empresa </label><input type="text" name="txtEmpresa" class="form-control" /><br />
<label for="lblCargo">Cargo </label><input type="text" name="txtCargo" class="form-control" /><br />
<label for="lblData">Data </label><input type="text" name="txtData" class="form-control" /><br />
<label for="lblAtrib">Atribuições </label><textarea rows="4" cols="50" name="txtAtrib" class="form-control"></textarea><br />
<input class="btn" type="submit" name="btnCadastrar" value="Cadastrar" />
</form>
</div>
<div id="divUpdExp" class="cadastros">
<form name="frmExp" action="/ExperienciaControle" method="GET">
<h1 style="font-family: Roboto">Listagem de Experiência</h1><br />
<table>
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Empresa</th>
<th>Cargo</th>
</tr>
</thead>
<%
request.getRequestDispatcher("/ExperienciaControle?action=btnListar").forward(request, response);
ArrayList<Experiencia> expArray = (ArrayList<Experiencia>) request.getAttribute("expArray");
for (Experiencia exp : expArray) {
%>
<tr>
<td><input type="checkbox" name="chckID" value="<%= exp.getId()%>" /></td>
<td><%= exp.getId()%></td>
<td><%= exp.getEmpresa()%></td>
<td><%= exp.getCargo()%></td>
</tr>
<%
}
%>
</table>
<span><input class="btn" type="submit" name="btnListar" value="Listar" /></span>
<span><input class="btn" type="submit" name="btnAtualizar" value="Atualizar" /></span>
<span><input class="btn" type="submit" name="btnRemover" value="Remover" /></span>
</form>
</div>
</div>
</body>
</html>
If I remove the Java code from the JSP and turn it into a pure HTML page, it works perfectly, the page comes up without any problems. Tomcat (and Glassfish) log shows no error messages, which makes things even harder. :(
What am I doing wrong here? Why am I getting a blank page?
COMPLETE CODE: http://gitlab.creationkit.com.br/thales/Curriculum
I am uploading a file in a form, that form also contains some textfields I enter some values in the textfields. I want this value to remain when I click upload button. And there is also a save button, when I click this button uploaded file should get saved in database. Can any one help me out?
JSP file is here:
<body>
<form action="./upload" enctype="multipart/form-data" >ID: <input type="text" name="id" value="" />Name: <input type="text" name="name" value="" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
I need the bussiness logic in a servlet..
Your options are:
Persist the data to your back-end and re-populate the form
Persist the data to the the in-browser Storage (http://www.w3schools.com/html/html5_webstorage.asp)
Put the upload form in an IFRAME
The easiest option is the IFRAME.
Hey you are saying the text field values should be there while clicking Upload button. You don't have to do this thing. By default it will be there. You should it will venish man? Please mention your exact requirement.
See there is no provision to keep the file field data using value attribute.
See this link
package comunity.stackoverflow.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestController
*/
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestController() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request,
HttpServletResponse response) {
storeInRequest(request, "id");
storeInRequest(request, "name");
storeInRequest(request, "uploaded");
// write your upload logic here then navigate to the same page;
try {
request.getRequestDispatcher("/test.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void storeInRequest(HttpServletRequest request,String param){
String val = request.getParameter(param);
if(param!=null && !param.isEmpty()){
System.out.println(val);
request.setAttribute(param, val);
}
}
}
Use standard.jat and jstl.jar
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<form action="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/>
Name: <input type="text" name="name" value="${name}" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
</html>
Use this JSP file. It might solve your problem.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<form action="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/><br/>
Name: <input type="text" name="name" value="${name}" /><br/>
<input type="file" id="selectedFile" style="display: none;" />
<input type="text" name="uploaded" id="uploaded" value="${uploaded}" readonly="readonly" size="60">
<input type="button" value="Browse..." onclick="mymethod()" /><br/>
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
<script type="text/javascript">
function mymethod(){
document.getElementById('selectedFile').click();
var val = document.getElementById('selectedFile').value;
document.getElementById('uploaded').value = val;
}
</script>
</html>