Java Servlet and getRequestDispatcher not forwarding - java

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

Related

I am having http status 404 while running my jsp which is linked to servlet

This is my jsp code:-
<%#page import="java.sql.*"%>
<%# 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>
<body>
<div id="header">
<center>
<div id="over">
<p> <font size="18" color="Brown"><b>UBONA Technologies</b></font></p>
</div>
</center>
</div>
<br><br><br><br><br><br>
<form method="get" action="controller.java">
<div class="container">
<center>
<table tableborder=0>
<tr><td><label><font size="5" color="BLACK"><b>USERNAME</b></font></label></td>
<br>
<td><input type="text" placeholder="Enter User Name" name="username" class="inputi" required></td>
</tr><br>
<tr><td><label><font size="5" color="BLACK"><b>PASSWORD</b></font></label></td>
<br>
<td><input type="password" placeholder="Enter Password" name="password" class="inputi" required></td>
</tr><br>
</table><br>
<input type="submit" class="button" name="submit" value="LOGIN" />
</center></div>
</form>
</body>
</html>
This is my Servlets code :-
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.sql.*;
//#WebServlet("/controller")
public class controller extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e)
{
}
try
{
String uname = request.getParameter("username");
String paswd = request.getParameter("password");
Connection con= null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","6q190No6#");
Statement s = con.createStatement();
ResultSet rs=s.executeQuery("select * from credentials");
rs.next();
String username1 = rs.getString("username");
String password2 = rs.getString("password");
if(uname.equals(username1) && paswd.equals(password2))
{
response.sendRedirect("welcome.jsp");
}
else
{
response.sendRedirect("wrongpas.jsp");
}
rs.close();
}
catch(SQLException sqe)
{
System.out.println("home"+sqe);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
}
this is my web.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/controller</url-pattern>
</servlet-mapping>
</web-app>
I have changed the location of tomcat server as suggested in some videos.
As I saw some replies to the same question which were saying that save class to the root folder/ web-inf/classes i am unable to find that folder too.
If you don't have WEB-INF/classes create it manually and save your class there.
Put your needed jars into WEB-INF/lib/.
First modify your form tag to
<form id="login" action="${pageContext.request.contextPath}/controller" method="GET">
Add id attribute
<input type="text" placeholder="Enter User Name" name="username" id="username" class="inputi" required>
also in here
<input type="password" placeholder="Enter Password" name="password" id="username" class="inputi" required>
Second remove your comment on annotation
//#WebServlet("/controller")
Make it
#WebServlet(name = "controller", urlPatterns = {"/controller"})
Import annotations
import javax.servlet.annotation.WebServlet;
Remove doPost it does nothing in your case.
You don't need web.xml also.
Recommends
Your class name should start with capital letter.
urlPatterns should be different from your class name.
Following changes will resolve your issue:
In JSP code:
<form role="form" method="get" action="${pageContext.request.contextPath}/controller">
In Servlet code:
#WebServlet("/controller")
Adding above line of code will prompt you to import Webservlet annotations library:
import javax.servlet.annotation.WebServlet;
Also it is considered a good practice to begin Java class names with Uppercase
i.e controller.java should be Controller.java

Calling method onClick of Jsp form Jsp

I wish to call a method in JSP onClick, the method is on the same JSP inside scriptlet.
How should I archive this?
<%# page import="java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<form>
<label>Email To</label><br />
<input type="text" name="to" /><br />
<label>Subject</label><br />
<input type="text" name="sub" /><br />
<label for="body">Message</label><br />
<input type="text" name="msg" /><br />
<input type="submit" onClick="sendMail( to, sub, msg )"/>
</form>
</body>
</html>
Note
The methods name is "sendMail", It's called on submit button
I want to do the whole code in JSP only.
The onclick event occurs when the user clicks on an element. This attribute has the ability to call JS functions (front end)
In your case, you want to call a JAVA function (server side) so the best way is to move the java code to a servlet and use it.
Anyway if you want to keep the JAVA function in the jsp, you can do this via ajax in this way
<script type="text/javascript">
$(document).ready(function() {
$('#sendMailBtn').click(function (){
$.ajax({
type: "post",
url: "/path",
data: "email=" + $('#email').val() + "&subject="+$('#subject').val() + "&msg=" + $('#msg').val(),
success: function(msg){
//
}
});
});
});
</script>
AJAX is a developer's dream, because you can
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
Check the full code here
<%# page import="java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}
%>
<html>
<head>
<title>Send Email using JSP</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<form>
<label>Email To</label><br />
<input id="email" type="text" name="to" /><br />
<label>Subject</label><br />
<input id="subject" type="text" name="sub" /><br />
<label for="body">Message</label><br />
<input id="msg" type="text" name="msg" /><br />
<input id="sendMailBtn" type="submit" />
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$('#sendMailBtn').click(function (){
$.ajax({
type: "post",
url: "/path",
data: "email=" + $('#email').val() + "&subject="+$('#subject').val() + "&msg=" + $('#msg').val(),
success: function(msg){
//
}
});
});
});
</script>
</html>
For more information check
AJAX Introduction: http://www.w3schools.com/xml/ajax_intro.asp
onclick Event: http://www.w3schools.com/tags/ev_onclick.asp
JSP- Executes on Server.
JavaScript - executes in browser.
No you cannot call that JSP magically from JS. However you can send an Ajax request or post the form to jsp. BTW, I strongly suggest you to move the java code to a servlet and use it.
This is what I ended up doing
<%# page import= "java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}
%>
<%
String a = request.getParameter("to");
if(a != null){
sendMail(request.getParameter("to"),request.getParameter("sub"),request.getParameter("msg"));
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body><center>
<form action="#" method="post">
<label>Email To</label><br />
<input type="text" name="to" /><br /> <br />
<label>Subject</label><br />
<input type="text" name="sub" /><br /> <br />
<label for="body">Message</label><br />
<input type="text" name="msg" /><br /> <br />
<input type="submit"/>
</form>
</center></body>
</html>
The action="#" reloads the page, and there is a if condition which calls the required method if the parameter is not blank( Please keep in mind that by default on first call the parameter will be null ).

background image not working in html

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

taking String of controller to the textarea using servlet

I have this code
<div class="row">
<div class="col-md-10">
<form class="form-horizontal" action="ChatController">
<textarea name="bottxt" id="disabledTextInput" border="2" class="form-control col-xs-6" rows="8" cols="60"></textarea><br>
<input class="form-control" type="text" name="usertxt" placeholder="your text here">
<button type="submit" class="btn btn-success active"> Send </button>
</div>
</div>
So i have ChatController. I want to return a string every time user types something in TextBox and press "submit". How can i do that .
From what I have understood from our conversation here is your answer. First we have to convert your html page to jsp page because only jsp page can receive response send in form of request dispatcher from servlet. Here it is :-
//textView.jsp
<%#page import="model.TextBean"%>
<%#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 class="row">
<%
TextBean txt=new TextBean();
txt=(TextBean)request.getAttribute("txt");
String text="";
if(txt!=null && txt.getText()!=null){
text=txt.getText();
}
%>
<div class="col-md-10">
<textarea name="bottxt" id="disabledTextInput" border="2" class="form-control col-xs-6" rows="8" cols="60"><%=text%></textarea><br>
<form class="form-horizontal" action="ChatController" method="post">
<input class="form-control" type="text" name="usertxt" placeholder="your text here">
<button type="submit" class="btn btn-success active"> Send </button>
</form>
</div>
</div>
</body>
</html>
Then we receive the value sent from this page in a servlet. But first we have to design a java class called TextBean. Its text variable will store the value of text entered.
package model;
public class TextBean {
String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
In our servlet we assign the value received from jsp page to this bean. Then we use request dispatcher to send response back to the jsp page in form of attribute.
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.TextBean;
public class ChatController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text=request.getParameter("usertxt");
TextBean txt=new TextBean();
txt.setText(text);
RequestDispatcher rd = request.getRequestDispatcher("textView.jsp");
request.setAttribute("txt", (TextBean)txt);
rd.forward(request, response);
}
}
In jsp page we create a new TextBean and set it to the value received from servlet. Then using getter method from bean we store the text in a string variable and then display it in textarea. If it is what you want mark the problem solved by clicking right mark in left side of my answer. If it is not let me know. Happy Coding :)

how to persist value in text field after refresh?

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>

Categories

Resources