i tried to make this work .
But still give me error
I still new in this
My .jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Staff Page - Add Book</title>
</head>
<body>
<center>
<h2 style="text-align: center;">Return Book Form.</h2>
<form name="uForm" method="get" action="addbookServlet" enctype="multipart/form-data">
<table align="center" width="300px" style="background-color:#f5f5f5;border:1px solid #e5e5e5; padding:5px;">
<tr><td colspan=2 align="center" height="10px"></td></tr>
<tr>
<td><b>Book ID</b></td>
<td><input type="text" name="book_id" size="50"></td>
</tr>
<tr>
<td><b>Book Title</b></td>
<td><input type="text" name="book_title" size="50"></td>
</tr>
<tr>
<td><b>Book Author</b></td>
<td><input type="text" name="book_author" size="50"></td>
</tr>
<tr>
<td><b>Book Quantity</b></td>
<td><input type="text" name="book_quantity" size="50"></td>
</tr>
<tr>
<td><b>Book Location</b></td>
<td><input type="text" name="book_location" size="50"></td>
</tr>
<tr>
<td><b>Book Image</b></td>
<td><input type="file" name="book_image" accept="image/x-png, image/gif, image/jpeg" size="50"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="g-button" value="Submit"></td>
</tr>
<tr><td colspan=2 align="center" height="10px"></td></tr>
</table>
</form>
</center>
</body>
</html>
My .java file
package caal;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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 caal.DbConnection.*;
public class AddBook extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("text/html");
// PrintWriter out = response.getWriter();
Connection con = null; // connection to the database
String message = null; // message will be sent back to client
// Statement stmt;
String book_id = request.getParameter("book_id");
String book_title = request.getParameter("book_title");
String book_author = request.getParameter("book_author");
String book_quantity = request.getParameter("book_quantity");
String book_location = request.getParameter("book_location");
//String book_image = request.getParameter("book_image");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("book_image");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DbConnection.getConn();
String query = "INSERT INTO booktable(bookId, bookTitle, bookAuthor, bookQuantity, bookLocation, bookimage) VALUES (?,?,?,?,?,?)";
System.out.println("query " + query);
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, book_id);
statement.setString(2, book_title);
statement.setString(3, book_author);
statement.setString(4, book_quantity);
statement.setString(5, book_location);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(6, inputStream);
}
//stmt = con.createStatement();
//stmt.executeUpdate(query);
response.sendRedirect("login.jsp");
con.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
// closes the database connection
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My web.xml become error . if i put like this
<!-- SERVLET FOR ADD BOOK -->
<servlet>
<servlet-name>addBookServlet</servlet-name>
<servlet-class>caal.AddBook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addBookServlet</servlet-name>
<url-pattern>/addbookServlet</url-pattern>
</servlet-mapping>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
The error is
Error occurred during deployment: Exception while deploying the app [fpx] : org.xml.sax.SAXParseException; lineNumber: 52; columnNumber: 23; Deployment descriptor file WEB-INF/web.xml in archive [web]. cvc-complex-type.2.4.a: Invalid content was found starting with element 'multipart-config'. One of '{"http://java.sun.com/xml/ns/j2ee":description, "http://java.sun.com/xml/ns/j2ee":display-name, "http://java.sun.com/xml/ns/j2ee":icon, "http://java.sun.com/xml/ns/j2ee":distributable, "http://java.sun.com/xml/ns/j2ee":context-param, "http://java.sun.com/xml/ns/j2ee":filter, "http://java.sun.com/xml/ns/j2ee":filter-mapping, "http://java.sun.com/xml/ns/j2ee":listener, "http://java.sun.com/xml/ns/j2ee":servlet, "http://java.sun.com/xml/ns/j2ee":servlet-mapping, "http://java.sun.com/xml/ns/j2ee":session-config, "http://java.sun.com/xml/ns/j2ee":mime-mapping, "http://java.sun.com/xml/ns/j2ee":welcome-file-list, "http://java.sun.com/xml/ns/j2ee":error-page, "http://java.sun.com/xml/ns/j2ee":jsp-config, "http://java.sun.com/xml/ns/j2ee":security-constraint, "http://java.sun.com/xml/ns/j2ee":login-config, "http://java.sun.com/xml/ns/j2ee":security-role, "http://java.sun.com/xml/ns/j2ee":env-entry, "http://java.sun.com/xml/ns/j2ee":ejb-ref, "http://java.sun.com/xml/ns/j2ee":ejb-local-ref, "http://java.sun.com/xml/ns/j2ee":service-ref, "http://java.sun.com/xml/ns/j2ee":resource-ref, "http://java.sun.com/xml/ns/j2ee":resource-env-ref, "http://java.sun.com/xml/ns/j2ee":message-destination-ref, "http://java.sun.com/xml/ns/j2ee":message-destination, "http://java.sun.com/xml/ns/j2ee":locale-encoding-mapping-list}' is expected.. Please see server.log for more details.
I also have try using #MultipartConfig but it still not working . I need some help .
In web.xml, you must have correct and corresponding DOCTYPE and DTD/XSD setting, otherwise you may get xml invalidation error.
Try check your web.xml XSD setting refer here and try again.
The XSD version is preferred since JSP 2.0 / Servlets 2.4 (eg: Tomcat 5.5). Note that the XML encoding can be specified as ISO-8859-1, UTF-8, or any other valid encoding in either version, and should match the actual encoding of your text file.
Related
My code is to use java servlets and JDBC to store and retrieve the information from a database. There is no error in the IDE the program is running but, the rows aren't inserted into the database and an error occurred in the firefox browser.
The following code is from the SERVLET file
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ServletRegister extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter("text/html");
String uname = req.getParameter("uname");
String passwd = req.getParameter("passwd");
String email = req.getParameter("email");
int phno = Integer.parseInt(req.getParameter("phno"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hack","root","");
PreparedStatement ps = con.prepareStatement("insert into student values(?,?,?,?)");
ps.setString(1,uname);
ps.setString(2,passwd);
ps.setString(3, email);
ps.setInt(4, phno);
int i = ps.executeUpdate();
if(i>0)
out.print("Registerd Successfully");
out.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The following code is from HTML file
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form action="register">
<table>
<tr>
<td>Enter User Name: <input type="text" name="uname"> </td>
</tr>
<tr>
<td>Enter Password: <input type="password" name="passwd"> </td>
</tr>
<tr>
<td>Enter E-mail: <input type="email" name="email"> </td>
</tr>
<tr>
<td>Enter Phone.no: <input type="number" name="phno" min="6000000000" max="9999999999"></td>
</tr>
<tr>
<td><input type="submit"> <input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>
The following code is from web.xml file
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.hacker.ServletRegister</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
The Error is:
Error obtained in firefox browser
You can use Postman to send a POST request to your server, or change doPost to doGet
In HTML file tag you did not mention the method= "post" So its taking the value by default "get" request.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 5 years ago.
I developed simple login servlet which runs well in eclipes but i am not getting any output from server side help to fix this
used create statement not prepared statement
help to improve logic
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>welcome to Student Account</title>
</head>
<body>
<font color="red">
<center>
Welcome to Student portal <br> <b>kindly login to your acccount</b></br> <b>Login
form</b>
<form method="post" action="./Account">
<table>
<tr>
<td>Student Login:</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>Student Password:
<td><input type="password" name="spasswd"></td>
</tr>
<tr>
<td>
</td>
<td><input type="submit" value="login"> <input
type="reset" value="reset"></td>
</tr>
</table>
</center>
</body>
</html>
StudentAccInfo.java
import java.io.IOException;
import java.io.PrintWriter;
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("/Account")
public class StudentAccInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String sname=request.getParameter("sname");
String spasswd=request.getParameter("spasswd");
String Status=UserService.validate(sname, spasswd);
out.println("<html><body><center>");
out.println("<font color='red' size='7'>");
if(Status.equals("success")){
out.println("Login Success");
}
if(Status.equals("failure")){
out.println("Login failure");
}
out.println("</center></body></html>");
}
}
UserService.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class UserService {
public static String validate(String sname, String spasswd)
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
String Status="";
try{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:ORCL", "scott", "tiger");
st=con.createStatement();
String sql="";
sql=sql+"select * from std where sname=";
sql=sql+"'"+sname+"'";
sql=sql+" "+"and spasswd=";
sql=sql+"'"+spasswd+"'";
rs=st.executeQuery(sql);
boolean b=rs.next();
if(b==true){
Status="success";
}else{
Status="failure";
}
}catch(Exception e){
e.printStackTrace();
}finally {
try{
con.close();
st.close();
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
return Status;
}
}
Note:- I have used create Statement not prepared statement
running well but not getting output
remove ./ from action attribute
<form method="post" action="Account">
I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# 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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# 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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.
hi all I have a LoginServlet that has the functionality to log in a user however I have a jsp page with the styling I'd to use. I am unsure how I can use the functionality from my LoginServlet in my login.jsp
here is the entirety of my code for the LoginServlet, I am aware I have coded to display a page but I need to use this jsp page to display. This is a uni assignment I have been given and it's part of the requirement that we use JSP for display.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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.servlet.RequestDispatcher;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
private void sendLoginForm(HttpServletResponse response,
boolean withErrorMessage)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<CENTER>");
if (withErrorMessage)
out.println("Login failed. Please try again.<BR>");
out.println("<BR>");
out.println("<BR><H2>Login Page</H2>");
out.println("<BR>");
out.println("<BR>Please enter your user name and password.");
out.println("<BR>");
out.println("<BR><FORM METHOD=POST>");
out.println("<TABLE>");
out.println("<TR>");
out.println("<TD>User Name:</TD>");
out.println("<TD><INPUT TYPE=TEXT NAME=uniid></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>Password:</TD>");
out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD ALIGN=RIGHT COLSPAN=2>");
out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");
out.println("</TR>");
out.println("</TABLE>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendLoginForm(response, false);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uniid = request.getParameter("uniid");
String password = request.getParameter("password");
if (login(uniid, password)) {
/*RequestDispatcher rd =
request.getRequestDispatcher("AnotherServlet");
rd.forward(request, response); */
response.sendRedirect("home_student.jsp");
}
else {
sendLoginForm(response, true);
}
}
boolean login(String uniid, String password) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
Statement s = con.createStatement();
String sql = "SELECT uniid FROM user" +
" WHERE uniid='" + uniid + "'" +
" AND password='" + password + "'";
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
return true;
}
rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
catch (SQLException e) {
System.out.println(e.toString());
}
catch (Exception e) {
System.out.println(e.toString());
}
return false;
}
}
here is my jsp page
<%# 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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="header.jsp"/>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<div id = "centrecontent">
<table border="0" cellpadding="2">
<tr>
<td width="500px" align="center">
<br>
<font size="5">Welcome to <i>The Department of <br>Rocket Science</i> Lab System<br></font>
<br>
For <b>Students</b> you can enrol in labs<br> and manage the labs you're enrolled in.<br><br>
For <b>Tutors</b> you can view the labs<br> you're teaching and record attendence.<br><br>
For <b>Lecturers</b> you can create and<br> manage lab classes, register Tutors and<br> assign those Tutors to labs.<br><br>
</td>
<td width="500px">
<table border="0" align="center">
<tr>
<td align="center">
<table border="0" align="center">
<tr> <br><br><b>Existing Member? <br>Sign In Here!</b><br>
<td align="right">
<form name ="login" METHOD=POST ACTION="SaveSession.jsp">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pword"/><br />
<input type=SUBMIT value="Login" name="Submit" />
</td>
</tr>
</table>
<br><br><br><br>
<form name="search_cat_bar" method="get" action="">
<input type="hidden" name="dff_view" value="grid">
Search:<input type="text" name="dff_keyword" size="30" maxlength="50"> <br>in
<select name="dff_cat1num" size="1">
<option value="-1">All Subjects
<option value="-2">--------------
<option value="101">CSE2ICE
<option value="193">CSE3PRA
<option value="193">CSE3PRB
<option value="193">CSE3WAE
</select>
<input type="submit" value="Find">
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table>
<tr>
</tr>
</table>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
I'd like the login.jsp page to call my LoginServlet for the login functions.
You can call servlet by this way:
web.xml
<servlet>
<servlet-name>UserLogin</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>//full class path
</servlet>
<servlet-mapping>
<servlet-name>UserLogin</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
login.jsp
<form name="login" action="<%=request.getContextPath()%>/servlet/login" method="post">
</form>
Servlet:
Login check and also you can send just error message to login page and display message like,
res.sendRedirect(req.getContextPath()+"/webpages/login.jsp?login=failed");
And in login.jsp you can retrieve parameter request.getParameter("login") and display proper message
add action in the html form tag.
action is LoginServlet URL.
It's easier to have the standard way of doing this:
Have jsp page with a form, to receive inputs from the user.
Have a servlet to process the data.
If there is a problem, set an error message and redirect the user to the login page. Otherwise redirect him to the destination.
Do not forget to set your form's action the address of your servlet.
Here is my Code index.jsp
<%--
Document : index
Created on : 14 Feb, 2012, 4:46:05 AM
Author : Sanjib Narzary
--%>
<%#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>JSP Page</title>
</head>
<body>
<form action="/CBKD_WEB/img" method="post"
enctype="multipart/form-data"
name="productForm" id="productForm"><br><br>
<table width="400px" align="center" border=0
style="background-color:ffeeff;">
<tr>
<td align="center" colspan=2 style=" font-weight:bold;font-size:20pt;">
Image Details
</td>
</tr>
<tr>
<td align="center" colspan=2> </td>
</tr>
<tr>
<td>Image Link: </td>
<td>
<input type="file" name="file" id="file">
<td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
</body>
</html>
and Servlet img.java
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.*;
public class img extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(
request);
System.out.println("request: " + request);
if (!isMultipart) {
System.out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(img.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("items: " + items);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
System.out.println("name: " + name);
String value = item.getString();
System.out.println("value: " + value);
} else {
try {
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
System.out.println("Text before replacing is:-"
+ itemName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
System.out.println("domainName: " + domainName);
String finalimage = buffer.toString() + "_" + r + domainName;
System.out.println("Final Image===" + finalimage);
File savedFile = new File("E:/sanjib/" + "temp/" + finalimage);
item.write(savedFile);
out.println("<html>");
out.println("<body>");
out.println("<table><tr><td>");
out.println("<img src=images/" + finalimage + ">");
out.println("</td></tr></table>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
}
}
}
}
}
}
This code is fine and working without any error in Netbeans Web Application with Glassfish 3.1 Server. But what my problem is if i try to upload the image it is showing Alert in Firefox like The connection to the server was reset while the page was loading and in Google Chrome This Error
This web page is not available
The connection to localhost was interrupted.
Here are some suggestions:
Reload this web page later.
Check your Internet connection. Reboot any routers, modems or other network devices that you may be using.
Add Google Chrome as a permitted programme in your firewall or antivirus software's settings. If it is already a permitted programme, try deleting it from the list of permitted programmes and adding it again.
If you use a proxy server, check your proxy settings or contact your network administrator to make sure that the proxy server is working. If you don't believe you should be using a proxy server, adjust your proxy settings: Go to the spanner menu > Options > Under the Bonnet > Change proxy settings... > LAN Settings and deselect the "Use a proxy server for your LAN" checkbox.
Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.