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)
Related
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?
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
I'm creating a JSP/Servlet web application and I'd like to upload a file to a Servlet with progress bar.
This is an example of uploading file with jsp and servlet.
Its working but i want to add to it a progress bar.
The FileUploadHandler.java
import java.io.File;
import java.io.IOException;
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;
/**
* Servlet to handle File upload request from Client
* #author Javin Paul
*/
public class FileUploadHandler extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "uploads";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
String name = null;
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
name = new File(item.getName()).getName();
item.write( new File(uploadPath+name));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully "+uploadPath+ name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
The upload.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
The result.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div id="result">
<h3>${requestScope["message"]}</h3>
</div>
</body>
</html>
The web.xml
<servlet>
<servlet-name>FileUploadHandler</servlet-name>
<servlet-class>FileUploadHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadHandler</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Though late, try using following plugin, which makes your UI beautiful and super easy.
https://github.com/blueimp/jQuery-File-Upload
Java examples are as follows:
https://github.com/blueimp/jQuery-File-Upload/wiki
Hey I am trying to create a voting app.
I have several counters in my servlets and I want to be able to display the value of those counters in my jsp file. How do I do it?
Please help me.
I want to display the total number of votes in each section and the winner after the election.
......................................................................................................................................................
servlet file
......................................................................................................................................................
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("/CastVote")
public class CastVote extends HttpServlet {
int javaCount, phpCount, pythonCount, othersCount;
public CastVote() {
super();
javaCount = 0;
phpCount = 0;
pythonCount = 0;
othersCount = 0;
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String choice = request.getParameter("language");
if("java".equals(choice))
{
javaCount++;
}
else if("php".equals(choice))
{
phpCount++;
}
else if("python".equals(choice))
{
pythonCount++;
}
else if("others".equals(choice))
{
othersCount++;
}
}
}
......................................................................................................................................................
Jsp File
......................................................................................................................................................
<%# page language="java" contentType="text/html; charset=UTF-8"
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=UTF-8">
<title>Vote now.</title>
</head>
<body>
<center>
<h2>Welcome to voting portal. Cast your vote.</h2>
</center>
<form action="CastVote" method="post">
Which of the following is the best language for backend programming? <br>
<input type="radio" name="language" value="java">1) Java <br>
<input type="radio" name="language" value="php">2) PHP <br>
<input type="radio" name="language" value="python">3) Python <br>
<input type="radio" name="language" value="others">4) Others <br>
<input type = "submit" value ="Vote">
</form>
</body>
</html>
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.