upload image with imagename using jquery file upload - java

I'm using AjaxFileUpload for uploading a file with some data (inputbox). Whenever I'm trying to upload the file, it shows File Uploading... and then gets stuck for a while. I checked my database, but found there was no effect on it.
Below is what I've done so far.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Ajax File Upload</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_frm").submit(function(){
//remove previous class and add new "myinfo" class
// e.preventDefault();
$("#msgbox1").removeClass().addClass('myinfo').text('Uploading .... ').fadeIn(1000);
$.ajaxFileUpload({
url :'AddPhoto',
secureuri:false,
fileElementId:'image',
dataType: 'json',
success: function(msg){
// alert(msg.MSG)
$("#msgbox1").removeClass().addClass('myinfo').text(msg.MSG).fadeIn(1000);
if(msg.MSG=="Image Successfully Uploaded!!")
{
document.getElementById("image").disabled="disabled";
}
}
});
return false;
});
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="login_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form name="login_frm" id="login_frm" action="" method="post">
<div id="login_box">
<div id="login_header"> Citizen Login </div>
<div id="form_val" style="background-color:black">
<div class="label">Image Name :</div>
<div class="control"><input type="text" name="imgname" id="imgname"/></div>
<div style="clear:both;height:0px;"></div>
<div id="msgbox"></div>
<div class="label">Photograph :</div>
<div class="control"><input type="file" name="image" id="image"/></div>
<div style="clear:both;height:0px;"></div>
<div id="msgbox1"></div>
</div>
<div id="login_footer">
<label>
<input type="submit" name="upload" id="upload" value="Upload" class="send_button" />
</label>
</div>
</div>
</form>
</body>
AddPhoto.java
package fileupload;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class AddPhoto extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Apache Commons-Fileupload library classes
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
if (!ServletFileUpload.isMultipartContent(request)) {
out.print("{MSG:'File Not Uploaded !!'}");
return;
} else {
// parse request
out.print("{MSG:'File Uploading....'}");
List items = sfu.parseRequest(request);
FileItem file = (FileItem) items.get(0);
String type = file.getContentType();
int size = (int) (file.getSize() / 1024);
//String name="images";
String name = file.getFieldName();
out.println("{MSG:'Error" +size+ "'}");
if (name.equals("image")) {
if ((type.equals("image/jpeg")) && ((size < 201) && (size > 10))) {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "epolicia", "admin");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("insert into images(image) values(?)");
ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
ps.executeUpdate();
con.commit();
con.close();
out.println("{MSG:'ID Proof Successfully Uploaded !!'}");
} else {
out.print("{MSG:'ID Proof is not jpg or its more than 200kb!!'}");
}
} else {
out.print("{MSG:'File Not Uploaded !!'}");
}
}
} catch (Exception ex) {
out.println("{MSG:'Error" + ex.getMessage() + "'}");
}
}
}

Regarding to your question, I have 2 points:
Check there: Asynchronous file upload (AJAX file upload) using jsp and javascript.
Ajax File uploader is no good choice if you use JSP. Read that topic.
An advice: do not use
if(msg.MSG=="Image Successfully Uploaded!!")
to compare results. Just try
if(msg.MSG === 1) { // or msg.MSG === true
//process and show the successfully uploaded string
}
That's all. I hope these could help you.

Related

Java-IO UTF-8 encoding problem to save html file

What I am trying to do is a blog page with jsp. For this purpose, I save the content of blogs in an html file. I am using a jsp file to update the content in the existing html file via the browser. I used the textarea tag in a jsp file to edit this html file through the browser. There is no encoding problem in the html content transferred to the textarea. But when I make changes to the html file and save it, the utf-8 characters turn out to be incorrect. For Example:
The html file is read and placed comfortably in the textarea without any encoding problems
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Üzerine Notlar</h1>
</body>
</html>
When i submit for save it:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Ãzerine Notlar</h1>
</body>
</html>
There is the classes and jsp files:
setBlog.jsp (Html file is setting in this file)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="navbar.jsp"/>
<form action="adminBlogProcess?meth=update" method="post">
id:<input type="text" readonly="readonly" value="${setMe.textId}" name="tid">
<label>Text Title</label>
<input type="text" name="name" class="form-control" value="${setMe.name}"/>
<label>File Path</label>
<input type="text" name="textPath" class="form-control" value="${setMe.textPath}"/>
<label>Kategori</label>
<select class="form-control" name="selectedCategory">
<c:forEach items="${loc}" var="val">
<option value="${val.categoryId}">${val.categoryName}</option>
</c:forEach>
</select>
<label>İçerik:</label>
<textarea class="form-control" name="content" rows="100">${contentOfDoc}</textarea>
<input type="submit" class="btn btn-primary" value="Save Changes">
</form>
</body>
</html>
AdminBlogProcess.java
package Controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DataAccess.CategoryDao;
import DataAccess.TextDao;
import Model.Category;
import Model.Text;
#WebServlet("/adminBlogProcess")
public class AdminBlogProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7693704779591981580L;
private CategoryDao cd;
private TextDao td;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String meth = req.getParameter("meth");
String msg="";
if (meth.equalsIgnoreCase("update")) {
update(req);
msg="Yazı Güncellendi!";
} else if (meth.equalsIgnoreCase("add")) {
} else if (meth.equalsIgnoreCase("delete")) {
}
req.setAttribute("message", msg);
req.getRequestDispatcher("/admin/admin.jsp").forward(req, resp);
}
//This update method is write new content into the html file
private void update(HttpServletRequest req) {
String name=req.getParameter("name");
String textPath=req.getParameter("textPath");
int id=Integer.valueOf(req.getParameter("tid"));
Category ct=getCd().getCategoryById(Integer.valueOf(req.getParameter("selectedCategory")));
Text txt=new Text(name, textPath, ct, id);
getTd().update(txt);
String content=req.getParameter("content");
String path="C:\\Users\\90551\\Desktop\\Eclipse Projeler\\2022 Yaz-Haziran Arsiv\\JAVA SERVER PAGES\\004BlogSitesi\\src\\main\\webapp\\texts\\"+textPath;
try (FileWriter fw = new FileWriter(new File(path), StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("");
bw.append(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CategoryDao getCd() {
if (cd == null) {
cd = new CategoryDao();
}
return cd;
}
public void setCd(CategoryDao cd) {
this.cd = cd;
}
public TextDao getTd() {
if (td == null) {
td = new TextDao();
}
return td;
}
public void setTd(TextDao td) {
this.td = td;
}
}
What should i do for fix that encodin problem?

Creating/displaying servlet response on jsp

I have to ask you because i'm stuck and can't go on. I'm trying to make response path like this:
DAO-> Servlet-> JSP
The process is: user fills the form on jsp, clicks "Submit" and gets response on the same JSP (user added or didn't)
adding data to DB is working fine but i got error from WebBrowser :
Type Exception Report
Message can't parse argument number: pageContext.request.contextPath
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
here is my jsp code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix ="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix ="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# page isELIgnored="false"%>
<script type="text/javascript" src="${pageContext.request.contextPath}/jQuery.js"/></script>
<!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>dodaj pracownika</title>
</head>
<body>
<f:view>
<section id = registration" class = "section">
<div class "container tagline">
<em>{0}</em>
</div>
<br>
<AdContentProvider
Name="MIME-type"
Provider="addUser.class"
Properties="optional-properties-for-your-class"
>
</AdContentProvider>
<form action="${pageContext.request.contextPath}/newuser" method = "post">
<form>
<label> Imie</label> <input type="text" name= "imie" id="imie"> <br/>
<label> Nazwisko</label> <input type="text" name= "nazwisko" id="nazwisko"> <br/>
<label> Stanowisko</label> <input type="text" name= "stanowisko" id="stanowisko"> <br/>
<label> Stawka</label> <input type="text" name= "stawka" id="stawka"> <br/>
<input type ="submit" value="Dodaj" id = "dodaj">
</form>
</f:view>
</body>
</html>
and servlet code:
package tk.jewsbar.servlets;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import fasolki.Pracownik;
import tk.jewsbar.dao.Dao;
#WebServlet("/newuser")
public class addUser extends HttpServlet
{
#Override
#Transactional
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String imie = req.getParameter("imie");
String nazwisko = req.getParameter("nazwisko");
String stanowisko = req.getParameter("stanowisko");
double stawka = Double.valueOf(req.getParameter("stawka"));
Pracownik pracownik = new Pracownik (imie, nazwisko, stanowisko, stawka);
Dao dao = new Dao();
int rows = dao.dodajUzytkownika(pracownik);
String err = "null";
if (rows ==0)
{
err = "Niestety nie udalo sie dodac uzytkownika";
}
else {
err = "Dodano uzytkownika" + rows;
}
String pejcz = getHTMLString(req.getServletContext().getRealPath("html/newuser.jsp"), err);
resp.getWriter().write(pejcz);
}
public String getHTMLString(String sciezka, String message) throws IOException
{
BufferedReader czytaj = new BufferedReader (new FileReader(sciezka));
String linia = "";
StringBuffer bufor = new StringBuffer();
while((linia=czytaj.readLine())!= null)
{
bufor.append(linia);
}
czytaj.close();
String pejcz = bufor.toString();
pejcz = MessageFormat.format(pejcz, message);
return pejcz;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String pejcz = getHTMLString(req.getServletContext().getRealPath("html/newuser.jsp"),"");
resp.getWriter().write(pejcz);
}
}
try like this
<script type="text/javascript" src="<c:out value="${contextPath}"/>/jQuery.js"></script>
or
<script type="text/javascript" src="<c:out value="${pageContext.request.contextPath}"/>/jQuery.js"></script>
Instead of
<script type="text/javascript" src="${contextPath}/jQuery.js"/></script>
You may read the suggestions on this link ,
expression-language-in-jsp-not-working

jsp form text + file processing

bookReg.jsp
<%#page import="classes.BooksDTO"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link type="text/css" href="css/mainStyle.css">
</head>
<body>
<%
//D:\Hayden\учеба\джава\JavaBigData\readers\WebContent\img - folder directory
%>
<form action="bookRegProc.jsp" method="post" enctype="multipart/form-data">
Title <input type="text" name="title"> <br>
Plot <textarea rows="30" cols="40" name="plot"></textarea> <br>
<input type="hidden" name="rating" value="0"> <br>
Author <input type="text" name="author"> <br>
Publisher <input type="text" name="publisher"> <br>
Genre <input type="text" name="genre"> <br>
Publication date <input type="text" name="date"> <br>
Cover <input type="file" name="cover" size="50"> <br>
<input type="submit" value="Register"> <br>
</form>
</body>
</html>
bookRegProc.jsp
<%#page import="classes.Uploader"%>
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="java.io.File"%>
<%#page import="classes.BooksDTO"%>
<%#page import="classes.BooksDAO"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Uploader upload = new Uploader();
upload.doPost(request, response);
%>
</body>
</html>
Uploader.java
package classes;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Uploader extends HttpServlet {
BooksDTO dto = null;
BooksDAO dao = new BooksDAO();
String title = null;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title"); // Retrieves <input type="text" name="description">
String plot = request.getParameter("plot");
String rating = request.getParameter("rating");
String author = request.getParameter("author");
String publisher = request.getParameter("publisher");
String genre = request.getParameter("genre");
String date = request.getParameter("date");
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
/*String fileName = title;
InputStream fileContent = filePart.getInputStream();*/
// ... (do your job here)
//DTO process
BooksDTO dto = new BooksDTO();
BooksDAO dao = new BooksDAO();
dto.setTitle(title);
dto.setAuthor(author);
dto.setDate(date);
dto.setGenre(genre);
dto.setPlot(plot);
dto.setPublisher(publisher);
dto.setRating(rating);
try {
dao.insert(dto);
//this inserts all the parameters into database
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//File process
File file;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
String filePath = "D:/Hayden/Eclipse workspace/bigdata/readers/WebContent/img/";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("C:/temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
FileItem fi = (FileItem) filePart;
if(!fi.isFormField()) {
file = new File(filePath + dto.getTitle() + ".jpg");
fi.write(file);
}
}catch(Exception ex) {
System.out.println(ex);
}
}
}
I want to pass text parameters from bookReg.jsp to register it in my database.
I checked the methods for inserting into database works totally fine.
but in doPost method, Uploader.java, request.getParameter passes null to each String.
I searched how to pass text to a servlet for days and I finally followed this instruction : How to upload files to server using JSP/Servlet? (first answer)
but it still passes null only.
what is the difference between passing parameter using request.getParameter in jsp and in a java class as I wrote?
and what is causing the same problem even if I followed the instruction of the first answer in the page that I followed?
(I am using tomcat 8.5 and eclipse oxygen)

Ajax response doesn't display in JSP page

I'm Trying to Save small record using JSP ajax in technology. The project working procedure is like this.
01. index.jsp : Send data to SaveStudent servlet
02. SaveStudent : Get request form jsp and send it to validation java class
03. Validation : Validate data and Send to DaoImpl java class
04. DaoImpl : Override the method in StudentDAO, Do the save SQL query.
05. StudentDAO : A interface has all the database related methods.
Here is the image of the project.
Given below is index.jsp files source code.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form action="SaveStudent" method="post">
<label>Enter Name:</label>
<input type="text" name="name" id="txtName"/>
<br/>
<label>Enter City:</label>
<input type="text" name="city" id="txtCity"/>
<br/>
<input type="submit" value="Send" id="btnSave"/>
<div id="response"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
var $name = $("#txtName").val();
var $city = $("#txtCity").val();
$.post('SaveStudent', {
name: $name,
city: $city
}, function(responseText) {
if (responseText !== null) {
$('#response').text(responseText);
} else {
alert("Invalid Name");
}
});
});
});
</script>
</body>
Here is SaveStudent java class's source code.
package Control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Validation;
public class SaveStudent extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String record = "";
try {
Validation val = new Validation();
record = val.validateSave(request, response);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
if (record != null) {
out.write(record);
} else {
out.print("Error Occured..!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Save record is working fine. Database is also updating. But the problem is The "Save Successful" message is appears in servlet page. Not under the jsp page.
Please help me on this. Thank you.
I figure out a way. I put replace "submit" type to "button". Now working perfectly. Thank you for your Time.

two jsp's that are mixed up in contents! (the second jsp loads over the first one)

I want to read in a textbox a name and I want to pass-it to the next form, and it would be a problem that the form doesn't reset to show only the second form, "basic.jsp". Is there any command to reset the form? Now it shows me the content of basic.jsp mixed up with the index.jsp (request of the name)...
-HelloWorld.java:
package javapapers.sample.ajax;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws java.io.IOException, ServletException {
res.setContentType("text/html");
res.getWriter().write("Hey!");
String textNume = req.getParameter("userInput");
req.setAttribute("nume",textNume);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("basic.jsp");
requestDispatcher.forward(req,res);
}
}
- index.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
<BR>Please enter your name:<input type='text' id='userInput'/>
<div id="hello"><button type="button" onclick="makeRequest()">Adauga</button></div>
<div id="ttt"><input type="text"></input></div>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p>
</script>
</body>
</html>
- ajax.js:
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
//AJAX call starts with this function
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "helloWorld.do", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var userInputValue = document.getElementById('userInput').value;
xmlHttpRequest.send("userInput=" + userInputValue);
}
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var userInput = document.getElementById("userInput").value;
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText; //"hey" def.in java!
document.getElementById("ttt").innerHTML = userInput;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
- basic.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<HTML>
<HEAD>
<TITLE>Elemente de identificare</TITLE>
</HEAD>
<BODY>
<H1>Elemente de identificare</H1>
Domnule <%= request.getAttribute("nume") %> alegeti elementele de identificare:<br>
Felul notificarii<br>
<select name="fel_notif">
<option value="Prima notificare">Prima notificare</option>
<%--<option value="Monday" selected>Monday</option>--%>
</select><br>
Mailul dvs <br><textarea rows="1" cols="30" name="mail"></textarea><br>
Caracterizare <br><textarea rows="3" cols="30" name="caract"></textarea><br>
Circumstante <br><textarea rows="3" cols="30" name="circ"></textarea><br>
Masuri de atenuare <br><textarea rows="3" cols="30" name="masuri"></textarea><br>
Cod notificare: <input type="text" name="cod" value="scot din BD" readonly><br>
<INPUT TYPE="SUBMIT" value="Trimite">
<%--<script type="text/javascript" language="javascript" src="ajax.js"></script>
<div id="pdf"><button type="button" onclick="makeRequest()">Creaza PDF</button></div>--%>
</BODY>
</HTML>
Your not sending userInput to the server. You have to add it to the request to be able to receive it in the servlet. Now you're just doing xmlHttpRequest.send(null). Instead, send the parameter string representing the data from your input. Something like:
xmlHttpRequest.send("userInput=" + userInputValue);

Categories

Resources