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.
Related
Here i've have 2 servlets
#WebServlet("/Login")
public class Login extends HttpServlet {
.........
.........
}
#WebServlet("/Create")
public class Create extends HttpServlet {
.........
.........
}
And a HTML page like this.
<form name="loginForm" method="post" action="Login">
<table width="20%" bgcolor="0099CC" align="center">
<tr>
<td colspan=2>
<center>
<font size=4><b>HTML Login Page</b></font>
</center>
</td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" size=25 name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="Password" size=25 name="password"></td>
</tr>
<tr>
<td><input type="submit" onclick="return check(this.form)" value="Login"></td>
</tr>
<tr>
<td><input type="submit" onclick="return check(this.form)" value="Create profile"></td>
</tr>
</table>
</form>
I want to redirect to Create servlet when the user clicks on create profile. Can anyone help me with this?
You need to select the action based on the button which is clicked. You can do it using JavaScript. Given below is the minimal, working example which you can extend as per your requirement:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function check(form, button){
if(button.id=='login'){
form.action="Login";
}else if(button.id=='create'){
form.action="Create";
}
form.submit();
}
</script>
<title>Insert title here</title>
</head>
<body>
<form name="loginForm" method="post">
<table width="20%" bgcolor="0099CC" align="center">
<tr>
<td colspan=2>
<center>
<font size=4><b>HTML Login Page</b></font>
</center>
</td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" size=25 name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="Password" size=25 name="password"></td>
</tr>
<tr>
<td><input type="button" id="login" onclick="check(this.form,this)"
value="Login"></td>
</tr>
<tr>
<td><input type="button" id="create" onclick="check(this.form,this)"
value="Create profile"></td>
</tr>
</table>
</form>
</body>
</html>
Login.java
package servlets;
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("/Login")
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Login");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Create.java
package servlets;
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("/Create")
public class Create extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Create");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
You have one form and you want it to go to two different servlet. You can't do that. If you want to goto login servlet first and then goto create servlet. You can do that view requestDispatcher or httpServletresponse.sendRedirect()
RequestDispatcher rd=request.getRequestDispatcher("servlet Name")
rd.forward(request, response);
or by
response.sendRedirect("/url");
Or if you dont want to go the login servlet at all and directly want to go to create then use two forms one for your Login and another one for your Create Profile.
<form name="loginForm" method="post" action="Create">
<tr>
<td><input type="submit" onclick="return check(this.form)" value="Create profile"></td>
</tr>
Im having some little troubles with the UPDATE servlet.
Im trying to update my db but its just not happening. I'm new to this chapter of Java EE.
**NB: I'm just having trouble with the UpdateServlet because i dont know how to get the modified datas from the JSP in order to send it to the DAO and then to update the DB. The rest is OK
The purpose : When the user hits the "Update" button (screenshot below)...
... the JSP forwards the request to the "update user" page (below) where he'll be able to modify the first and last name attached to the email (which is the primaary key)(screenshot below)...
My question is : how do i implement the UpdateUserServlet (see code below) code that gets the User object from the session and updates the database with the new first and last name.
The JSP that displays the User List
<body>
<h1>Users List</h1>
<table cellpadding="5" border=1>
<tr valign="bottom">
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="user" items="${users}">
<tr valign="top">
<td><p>${user.firstName}</td>
<td><p>${user.lastName}</td>
<td><p>${user.emailAddress}</td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</body>
After hitting the "Update button" this JSP below takes over.
....
<body>
<h1>Update User</h1>
<form action="updateUser" method="post">
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"
value="${user.firstName}">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value="${user.lastName}">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td>${user.emailAddress}</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Submit"></td>
</tr>
</table>
</form>
</body> ....
The Update servlet. Ineed help with this one.
package user;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import business.User;
import data.UserDB;
public class UpdateUserServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User user = new User();
HttpSession session = request.getSession();
session.setAttribute("user", user);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmailAddress(emailAddress);
UserDB.update(user);
// TODO: add code that gets the User object from the session and updates the database
String url = "/displayUsers";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
The DAO
package data;
import java.sql.*;
import java.util.ArrayList;
import business.User;
public class UserDB
{
public static int update(User user) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET " + "FirstName = ?, " + "LastName = ? "
+ "WHERE EmailAddress = ?";
try {
ps = connection.prepareStatement(query);
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getEmailAddress());
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
Try adding logs to update(User user) method. See whether control is coming to this place if atall.
I found the root cause in the second JSP see the code below.
<tr>
<td align="right">Email address:</td>
<td>${user.emailAddress}</td>
</tr>
The servlet's getParameter("emailAddress") method was actually getting a null value since there is no parameter name in the code above..
So, it should have been done like this:
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailaddress"
value="${user.emailaddress}">
</td>
</tr>
Note that the -input type="text"- is not necessary since the email address doesnt have to be modified like the name and firsname. So i should find a way to show the email address in something else than a input text box. But it works now
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.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I have written a Java servlet program and run it through local Tomcat 7, But it was showing following error :
HTTP Status 404 - /skypark/registration
type Status report
message /skypark/registration
description The requested resource is not available.
Apache Tomcat/7.0.33
I don't know what was the reason for it
my Html page is
<html>
<head>
<title>
User registration
</title>
</head>
<body>
<form action="registration" method="post">
<center>
<h2><b>Skypark User Registration</b></h2>
<table border="0">
<tr><td>
First Name
</td><td>
<input type="text" name="fname"/></br>
</td></tr><tr><td>
Last Name
</td><td>
<input type="text" name="lname"/></br>
</td></tr><tr><td>
UserName
</td><td>
<input type="text" name="uname"></br>
</td></tr><tr><td>
Enter Password
</td><td>
<input type="password" name="pass"></br>
</td></tr><tr><td>
Re-Type Password
</td><td>
<input type="password" name="pass1"></br>
</td></tr><tr><td>
Enter Email ID
</td><td>
<input type="email" name="email1"></br>
</td></tr><tr><td>
Phone Number
</td><td>
<input type="number" name="phone">
</td></tr><tr><td>
Gender<br>
</td></tr><tr><td>
<input type="radio" name="gender" value="Male">Male</input></br>
</td></tr><tr><td>
<input type="radio" name="gender" value="Female">Female</input></br>
</td></tr><tr><td>
Enter Your Date of Birth<br>
</td><td>
<Table Border=0>
<tr>
<td>
Date
</td>
<td>Month</td>
<td>Year</td>
</tr><tr>
<td> <select name="date">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
.
.
.
have some code
.
.
.
</table>
<input type="submit" value="Submit"></br>
</center>
</form>
</body>
</html>
My servlet is :
package skypark;
import skypark.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Registration extends HttpServlet
{
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
String dcn="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:#JamesPJ-PC:1521:skypark";
String usname="system";
String pass="tiger";
Class.forName(dcn);
return DriverManager.getConnection(url,usname,pass);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
try
{
String phone1,uname,fname,lname,dob,address,city,state,country,pin,email,password,gender,lang,qual,relegion,privacy,hobbies,fav;
uname=req.getParameter("uname");
fname=req.getParameter("fname");
lname=req.getParameter("lname");
dob=req.getParameter("date");
address=req.getParameter("address");
city=req.getParameter("city");
state=req.getParameter("state");
country=req.getParameter("country");
pin=req.getParameter("pin");
email=req.getParameter("email1");
password=req.getParameter("password");
gender=req.getParameter("gender");
phone1=req.getParameter("phone");
lang="";
qual="";
relegion="";
privacy="";
hobbies="";
fav="";
int phone=Integer.parseInt(phone1);
Connection con=prepareConnection();
String Query="Insert into regdetails values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(Query);
ps.setString(1,uname);
ps.setString(2,fname);
ps.setString(3,lname);
ps.setString(4,dob);
ps.setString(5,address);
ps.setString(6,city);
ps.setString(7,state);
ps.setString(8,country);
ps.setString(9,pin);
ps.setString(10,lang);
ps.setString(11,qual);
ps.setString(12,relegion);
ps.setString(13,privacy);
ps.setString(14,hobbies);
ps.setString(15,fav);
ps.setString(16,gender);
int c=ps.executeUpdate();
String query="insert into passmanager values(?,?,?,?)";
PreparedStatement ps1=con.prepareStatement(query);
ps1.setString(1,uname);
ps1.setString(2,password);
ps1.setString(3,email);
ps1.setInt(4,phone);
int i=ps1.executeUpdate();
if(c==1||c==Statement.SUCCESS_NO_INFO && i==1||i==Statement.SUCCESS_NO_INFO)
{
out.println("<html><head><title>Login</title></head><body>");
out.println("<center><h2>Skypark.com</h2>");
out.println("<table border=0><tr>");
out.println("<td>UserName/E-Mail</td>");
out.println("<form action=login method=post");
out.println("<td><input type=text name=uname></td>");
out.println("</tr><tr><td>Password</td>");
out.println("<td><input type=password name=pass></td></tr></table>");
out.println("<input type=submit value=Login>");
out.println("</form></body></html>");
}
else
{
out.println("<html><head><title>Error!</title></head><body>");
out.println("<center><b>Given details are incorrect</b>");
out.println(" Please try again</center></body></html>");
RequestDispatcher rd=req.getRequestDispatcher("registration.html");
rd.include(req,resp);
return;
}
}
catch(Exception e)
{
out.println("<html><head><title>Error!</title><body>");
out.println("<b><i>Unable to process try after some time</i></b>");
out.println("</body></html>");
RequestDispatcher rd=req.getRequestDispatcher("registration.html");
rd.include(req,resp);
return;
}
out.flush();
out.close();
}
}
And the web.xml file is
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>skypark.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/registration</url-pattern>
</servlet-mapping>
</web-app>
This i kept in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\WEB_INF\web.xml
and servlet class in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\WEB_INF\classes\skypark
and registration.html in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\
if any mistake in this makes above error means please help me.Thanks in advance....
I think the problem is with this two line :
<form action="registration" method="post"> in your html page.
<url-pattern>/Registration</url-pattern> in your web.xml
Your action is set to registration and your url pattern expects Registration (Note that capital R and small r ).
Just try changing them (both same ) and it should work
Try putting a request mapping to the method you want to be called by the request. If, for example, you use Spring framework, you need to set your servlet url-pattern in web.xml to htm in your case, then return the name of your html file.
#RequestMapping(value ="/registration",method = RequestMethod.GET)
public String render(Model model, HttpServletRequest request, HttpServletResponse response) {
{
--------------- compute ----
return "registration";
}
If you will put a request to /registration, the server will compute the method mapped to it then search for "registration" (returned value) to show.
Hope it helps !
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.