How to pass text field value from jsp to java class.
my .jsp code is
<html>
<head></head>
<body>
<FORM>
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</body>
</html>
my .java class code is
here in string str i need to get the textfield value.
class sample{
String str=""; //C:/check/svntes
File exportDir = new File(str);
if (exportDir.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Path ''{0}'' already exists", exportDir);
throw new SVNException(err);
}
exportDir.mkdirs();
}
Hmm .. let's assume how your jsp & java file interact with each other. Correct if im wrong.
A.jsp file
<html>
<head></head>
<body>
<FORM ACTION="B.JSP" METHOD="POST"> //edited part
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</body>
</html>
B.JSP
<jsp:useBean id="sample" scope="page" class="com.home.file.sample" /> // sample is java file name
String name = request.getParameter("text1");
int iRowAffected = 0;
//-------now pass parameter "name" to your sample java file
sample.function_name("name");
Sample.java
public class sample
{
public int function_name(String NAME)
{
String str = NAME;
File exportDir = new File(str);
if (exportDir.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Path ''{0}'' already exists", exportDir);
throw new SVNException(err);
}
exportDir.mkdirs();
//continue with your coding
}
}
To passing value from JSP to Java, you need java Servlet.
Call servet from form tag and then get value using request.getParameter("your value") api of request object.
JSP Page:
<form action="HelloServlet" method="POST">
Please enter your name:
<input type="text" name="text1" id="text1">
<br>
<input type="submit" value="Submit">
</form>
Servlet :
public class HelloWorld extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// reading the user input
String text1= request.getParameter("text1");
}
}
Is your java class a servlet?
Because then you need to post to your servlet like this:
<form action="ServletName" method="GET">
Please enter your name:
<input type="text" name="text1" />
<br />
<input type="submit" value="Submit" />
</form>
And then in your servlet you can get the string value like this:
String str = request.getParameter("name");
name.jsp
<FORM action="/submitName" method="get">
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
First of all, in your above jsp file two things are missing action
and method(optional, by default it takes "get") attributes.
Now to get the input value in you java class, you need to write a Servlet class and configure it in the web.xml with a url mapping "/submitName".
MyServlet.java
// Import required java libraries
// Extend HttpServlet class
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("text1"); //should be same name as form input name
System.out.println(name);
}
}
web.xml will be as follows,
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/submitName</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>name.jsp</welcome-file>
</welcome-file-list>
</web-app>
I got answer by this way..Its working fine.
my.jsp code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form >
Enter the word: <input type="text" name="word">
<input type="submit">
<%# page import = "dem.hashmap"%> <!-- //importing java class -->
<%
hashmap hm = new hashmap(); /* creating reference for my java class */
String inputvalue = request.getParameter("word");
String output = hm.dircreation(inputvalue); /* calling java method */
out.println(inputvalue);
%>
</body>
</html>
my hashmap .java class:
package dem;
import java.io.File;
public class hashmap {
String nav;
public String dircreation(String dir)
{
System.out.println("The Value is--------->"+dir);
boolean success = false;
File directory = new File(dir);
System.out.println("1....The Value is--------->"+dir);
if (directory.exists()) {
System.out.println("Directory already exists ...");
} else {
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
if (success) {
System.out.printf("Successfully created new directory : %s%n", dir);
} else {
System.out.printf("Failed to create new directory: %s%n", dir);
}
}
return nav;
}
}
Related
I keep getting the error This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 405
I created a signup form. but when I submit, it doesn't show the action page.
**In html:
**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Signup Form</title>
<link rel="stylesheet" href="\assets\css\main.css">
</head>
<body>
<nav class="flex-container">
<div class="one"><img src="\assets\images\vanierlogo.jpg" alt="logo"></div>
<div class="two"><a href=\signup.html>Signup</a></div>
<div class="three">Login</div>
</nav>
<div id="txtHint"></div>
<form>
<h3>Create New Student Account</h3><br><br>
<label for="username">Student ID: </label>
<input type="text" id="username" name="username" required><br><br>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="firstName"><br><br>
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="lastName"><br><br>
<label>Enter Password<sup>*</sup>: </label>
<input type="password" autocomplete="passwd" name="passwd" required><br><br>
<label>Confirm Password: </label>
<input type="password" autocomplete="passwd1" name="passwd1" required><br><br>
<label>Are you Full-Time or Part-Time?</label><br><br>
<label for="Full-Time">Full-Time</label>
<input type="radio" id="Full-Time" name="status" value="Full-Time">
<label for="Part-Time">Part-Time</label>
<input type="radio" id="Part-Time" name="status" value="Part-Time"><br><br>
<input type="submit" onclick="createAccount(this)" value="Sign Up!"><br><br>
<footer>* Password must be at least 3 characters in length</footer>
</form>
<script src="\assets\js\main.js"></script>
</body>
</html>
In main.js:
function createAccount(element) {
const currForm = element.closest('form');
const params = "username="+currForm.elements[0].value +
"&firstName="+currForm.elements[1].value +
"&lastName="+currForm.elements[2].value +
"&passwd="+currForm.elements[3].value +
"&passwd1="+currForm.elements[4].value +
"&status="+currForm.elements[5].value;
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:80/SignupHandlingServlet",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhttp.readyState == 4) {
alert("DONE");
alert(xhttp.status);
if (xhttp.status==409 || xhttp.status==417 || xhttp.status==200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
else {
alert(xhttp.method);
let response = JSON.parse(xhttp.responseText);
document.querySelector("#ipText").innerHTML = response.ip;
}
}
else if (xhttp.readyState==0) {
alert("request unsent");
} else if (xhttp.readyState==1){
alert("request OPENED");
} else if(xhttp.readyState==2) {
alert("request HEADERS_RECEIVED");
} else {
alert("The HTTP request response is being downloaded");
}
}
}
**In web.xml:
**
<web-app>
<servlet>
<servlet-name>SignupHandlingServlet</servlet-name>
<servlet-class>SignupHandlingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupHandlingServlet</servlet-name>
<url-pattern>/SignupHandlingServlet</url-pattern>
</servlet-mapping>
</web-app>
**In java:
**
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
#WebServlet("/SignupHandlingServlet")
public class SignupHandlingServlet extends HttpServlet {
/* Process the HTTP Post request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Obtain parameters from the client
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
if (Interpreter.usernameExists(username)) {
out.println("<br><br>That username already exists.<br>");
response.setStatus(417);
}
else if (!passwd.equals(request.getParameter("passwd1"))) {
out.println("<br><br>Please confirm password<br>");
response.setStatus(409);
}
else {
String lastName = request.getParameter("lastName");
String firstName = request.getParameter("firstName");
String status = request.getParameter("status");
Student CreateStudent = new Student(username, passwd, firstName, lastName, status);
Interpreter.saveStudentCredentials(CreateStudent);
out.println("<br><br>Account created successfully<br>");
response.setStatus(200);
}
out.close(); // Close stream
}
}
Any help please? it's my 1st front end school project. It's been long debugging this error with no success.
I was expecting a createAccount page with result of the doPost() printed out.
click here to view my folder structure
When submitting a form, only input fields with the name attribute are submitted.
For inputs 'username', 'new-password' and 'new-password1', there is no name attribute and hence no data sent to server. So, accessing 'passwd' variable (which is null) with equals method will throw 'NullPointerException'.
<html>
<head>
<title>Report Preview</title>
</head>
<body>
<div class="container">
<h2>Patient Data</h2>
<form action = "reportUpdate" method = "post" >
<input type="text" name="fvalue" value="testingData1"/>
<input type="text" name="svalue" value="testingData2"/>
<input type="submit" value="Submit"/>
</form>
</div>
<script type = "text/javascript" src = "main.js"></script>
</body>
</html>
I have a SpringBootProject and I'm using the above Freemarker code template file(*.ftl). I tried to display some input field with the values(binded), after editing I want to extract the data from HTML input tags(fvalue,svalue) to controller without using any model. How to get the values?
My controller code:
#PostMapping({ "/reportUpdate"})
public String reportToUpdate( ) {
String firstName = ""; // I should get fvalue here
String secondName = ""; // I should get svalue here
//Some other logics which will use above value.
return "Data saved!";
}
By using HttpServletRequest request, HttpServletResponse response we can get the data from HTML form.
Using the below code.
public void getDataFromForm(HttpServletRequest request, HttpServletResponse response) throws ServletException{
// Get the values from the request using 'getParameter'
String name = request.getParameter("name");
}
For more info, you can see this.
This question already has answers here:
How to save generated file temporarily in servlet based web application
(2 answers)
Closed 5 years ago.
I am creating a Java Web Application which takes data from a HTML form and saves it to a text file using a Servlet. However when I run the application I cannot see the text file anywhere so I am unsure if it was created successfully or not. Does anyone have any ideas why the file is not appearing?
Here is my code for the HTML form:
<html>
<head>
<title>Register Customer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name = "regcustomer" method = "get" action = "CustomerServlet" >
Customer Name
<input type="text" name="customerName"> <br>
Customer Address
<input type="text" name="customerAddress"> <br>
Telephone Number
<input type="text" name="telNo"> <br>
Email
<input type="text" name="email"> <br>
Cost per KG shipped
<input type="text" name="costPKG"> <br>
<input type="submit" value="Register"> <br> <br>
Back
</form>
</body>
And here is my code for the servlet:
package Servlets;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomerServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
String customerName;
customerName = request.getParameter("customerName");
String customerAddress = request.getParameter("customerAddress");
String telNo;
telNo = request.getParameter("telNo");
String email = request.getParameter("email");
String costPKG = request.getParameter("costPKG");
try{
File file = new File("C:/xyz.txt");
FileWriter fstream = new FileWriter(file,true);
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write(customerName+" "+customerAddress+" "+telNo+" "+email+"
"+costPKG);
out.newLine();
}
pw.println("File is created successfully");
}
catch (IOException e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any suggestions would be much appreciated
Try adding the line:
#WebServlet(urlPatterns = { "/CustomerServlet" })
before:
public class CustomerServlet extends HttpServlet {
Note: If you are using old container (not implemented Servlet 3.0, like Tomcat 6.0), then you have to edit web.xml.
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 3 years ago.
I have a JSP which will let a user register for an account at my website. If the user submits wrong or illegal info into the JSP, then I want to return the same JSP with an appropriate error message next to/above each wrongly filled (form) fields.
If possible, highlight the wrongly filled form field - this feature is not necessary though.
I have given a sample below to show what I need. I understand that the sample must be using something like javascript, but I don't know all that client side scripting. I only want to use JSP to do it. As I said, I want to sort of return the JSP form to the user after marking all the mistakes and how to correct them.
How do I do this ? I only need some initial direction. I will make the code myself and post it here later.
Thanks.
EDIT - I don't want the drop down box. I don't want red borders around wrongly entered fields. I only want to display the error messages (in red color) next to the relevant fields.
Here is some sample code -
<%# page language="java" contentType="blah..." pageEncoding="blah..."%>
<!DOCTYPE html PUBLIC "blah...">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user"><br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
RegServlet -
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;
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static String okUser = "loser";
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(user.equalsIgnoreCase(okUser) == false){
//Do something MAGICAL to set an error next to username field of Form.jsp, then forward.
RequestDispatcher view = request.getRequestDispatcher("/jsp/Form.jsp");
view.forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Validation</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- or download to a directory -->
<!-- <script src="js/jquery-1.9.1.js"></script> -->
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#user').change(function() {
var userName = jQuery(this).val();
jQuery.ajax({
type : 'GET',
url : 'AjaxUserCheck',
data : {user:userName},
dataType : 'html',
success : function(data) {
if(jQuery.trim(data)=='1')
{
jQuery("#userLabel").html("Sorry! username is taken");
//write other stuff: border color ...
}
else if(jQuery.trim(data)=='0')
jQuery("#userLabel").html("user name available");
else
alert(data); //possible error
},
error : function(xhr,status,error){
console.log(xhr);
alert(status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user" id="user">
<label id="userLabel"></label>
<br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
---------Servlet------
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
//if(dao.isUserExist(user)){
if(user.equals("java")){ // check for db if userid exists in DB print '1' else '0'
out.print("1");
}
else
out.print("0");
have the page post to itself, like this login.jsp fragment:
<div class="error">
<%
String usrName = "" + request.getParameter("username");
String usrPass = "" + request.getParameter("password");
if (isValid(usrName,usrPass){
openUserSession(usrName); //here you open a session and set the user, if the session doesn't have an user redirect to login.jsp
response.sendRedirect("index.jsp"); //user ok redirect to index (or previous page)
} else {
out.print("Invaid user or password");
}
%>
</div>
<form action="login.jsp" method="POST"> <!-- login.jsp post to itself -->
<input type="text" name="username" id="username"/>
<input type="password" name="password" />
<input type="submit" value="login" name="login" />
<input type="submit" value="register" name="register" />
</form>
I have problem with get a value from combobox in my .jsp file to servlet.
I use method request.getParameter i other servlets and it works. In this class it don't.
I was also trying to get value from text field to this servlet but also don't work. I don't have any idea how to solve this problem.
I have combobox like that:
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
I'm tring to get value:
String folder = request.getParameter("folders1");
My jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<%# page import="tools.User" %>
<%# page import="java.io.File" %>
<%# page import="java.text.DecimalFormat" %>
<%#page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Serwer dysku sieciowego </title>
</head>
<body>
<div class="container">
<div class="ramka_zaproszenie">
<%
File[] listOfFolders;
User user;
String username;
String status = null;
if(session.getAttribute("user")!=null){
user = (User)session.getAttribute("user");
username = user.getLogin();
status = user.getType().toString();
} else {
username = "unknown";
}
%>
<p class="loguj">Witaj, <%= username %>!</p><br>
<% if(session.getAttribute("user")!=null){ %>
<p class="tekst">Wrzuc plik na serwer:</p>
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
<form action="folder" method="get">
<p class="tekst"> Folder: <br><input class="pole" id="Folder" type="text" name="folderName" />
<br /></p>
<input class="zatwierdz" type="submit" id="submit" value="Utwórz" /><br>
</form>
<br />
<% if(status.equalsIgnoreCase("ADMIN")){ %>
<a class="wroc" href="zmiana_rozmiaru.jsp">Zmiana Pojemnosci</a>
<%}%>
<br />
<br />
<p class="tekst">Posiadane pliki na serwerze:</p>
<form method="post">
Folder:
<select name="folders">
<option value=0 selected="selected" >Wybierz folder</option>
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
<input type="submit" value="Wybierz"><br>
</form>
<br />
Pliki z folderu: <%=request.getParameter("folders")%>
<center><table id="tabela">
<tr class="alt">
<th>Nazwa</th>
<th>Rozmiar</th>
<th>Pobierz</th>
<th>Usun</th>
</tr>
<%
System.out.println(request.getParameter("folders"));
user = (User)session.getAttribute("user");
File[] listOfFiles = user.listOfFiles(request.getParameter("folders"));
if(listOfFiles != null){
for(File file : listOfFiles){
DecimalFormat twoDForm = new DecimalFormat("#.##");
out.print("<tr class=\"alt\"><td>" + file.getName()+"</td><td>" +twoDForm.format((double)file.length()/1024.0)+" KB</td><td align=center> <img border=\"0\" src=\"downloadsmall.png\"></td><td align=center><a src=\"deletesmall.png\" href=\"delete?filePath="+file.getAbsolutePath()+"\" ><img border=\"0\" src=\"deletesmall.png\"></a></td></tr>");
}
}
%>
</table>
</center><br>
<form action="logout" method="post">
<input type="image" src="wylacznik.png" id="submit">
</form>
<br><br>
<%
if (session.getAttribute("warning") != null) {
%>
<span><%= session.getAttribute("warning") %></span>
<%
session.removeAttribute("warning");
}
%>
<% } %>
<div class="footer">Copyright 2013 by JavaProjectTeam.</div>
</div>
</div>
</body>
</html>
And my servlet file
<pre>package servlets;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import tools.Connector;
import tools.User;
#WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private File file ;
public void init(){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
request.setCharacterEncoding("UTF-8");
String folder = request.getParameter("folders1");
HttpSession session = request.getSession(true);
User user = (User)session.getAttribute("user");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
session.setAttribute("warning", "Nie masz zadnych plikow");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(user.getSpace() * 1024);
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write(file);
System.out.println(file.getName());
try{
Connection connection = new Connector().getConnection();
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator('.');
DecimalFormat twoDForm = new DecimalFormat("#.##", otherSymbols);
System.out.println(twoDForm.format((double)file.length()/1024.0));
connection.createStatement().executeUpdate("UPDATE `users` SET `space` = `space`-"+twoDForm.format((double)file.length()/1024.0)+" where id="+user.getId());
} catch(SQLException e){
e.printStackTrace();
}
session.setAttribute("warning", "Plik został dodany do wirtualnego dysku.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
session.setAttribute("warning", "File is too big! Only "+user.getSpace()+"KB left.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}<code>
It's because you're sending a multipart/form-data request while that's by default not supported by servlets. I however notice that you're still using the "legacy" Apache Commons FileUpload to obtain the uploaded file instead of new Servlet 3.0 provided HttpServletRequest#getPart(). In that case, you've basically 2 options:
Stick to Commons FileUpload. You should be collecting regular form fields in the else block of your if (!fi.isFormField()) which you're currently completely ignoring.
if (!fi.isFormField()) {
// Collect uploaded file from fi.
} else {
// Collect normal form field from fi.
}
Get rid of Commons FileUpload and use #MultipartConfig annotation.
#WebServlet("/upload")
#MultipartConfig
public class UploadServlet extends HttpServlet {
This way you can get files by request.getPart() and keep using request.getParameter() the usual way for regular form fields.
See also:
How to upload files to server using JSP/Servlet?
Unrelared to the concrete problem, that's not a combobox, but that's a dropdown. A combobox is an editable dropdown. Further, writing Java code in JSP is a bad practice. Java code belongs in Java classes like a servlet. To loop over options, use JSTL <c:forEach>. And, writing HTML code in a Java class like a servlet is a bad practice. HTML code belongs in a JSP file. Use RequestDispatcher#forward() to present results in a JSP. See further also our servlets wiki page.
Oh, you've a major threadsafety problem in your servlet. There's only one instance of a servlet during applications lifetime which is shared across all HTTP requests. Those fields
private boolean isMultipart;
private String filePath;
private File file ;
would be shared across all HTTP requests resulting in potential major problems when multiple users concurrently use the same servlet at the same moment. Get rid of them and move them to inside the doXxx() method block.