I have LoginServlet like this:
package servlets;
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("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("gogikole") && password.equals("1234")) {
response.sendRedirect("mainMenu.jsp");
return;
}
}
}
And login.jsp like this:
<%# 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>Login page</title>
</head>
<body>
<form method="post" action="LoginServlet"></form>
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</body>
</html>
For some reason when I input correct username: (gogikole) and password: (1234) and click on submit button it won't to redirect me to mainMenu.jsp
When I click on button, nothing happen it just stay on login page like I didn't even click or type anything.
How to fix that problem and redirect when I click on submit button (Login)?
I created mainMenu.jsp and, for now that is one allmost blank page only with message "Welcome".
Your submit button is not submitting the form.
i.e., you have closed the form immediately:
<form method="post" action="LoginServlet"></form>
The problem is that your form inputs and submit button are outside the form You have to enclose as below.
<form method="post" action="LoginServlet">
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
Related
here I want to upload my file into my upload folder but in my scenario, it cannot store in that folder. The file name is printed in the console but the file does not store in the upload folder. In the Developer tool console, I get an error called Failed to load resource: the server responded with a status of 404 (Not Found).
DemoForm.java
package controller;
import java.io.*;
import java.util.* ;
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 DemoForm
*/
#WebServlet("/DemoForm")
#MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10, //10MB
maxFileSize = 1024 * 1024 * 50, //50MB
maxRequestSize = 1024 * 1024 * 100 //100MB
)
public class DemoForm extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "upload";
/**
* #see HttpServlet#HttpServlet()
*/
public DemoForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("username", request.getParameter("username"));
request.setAttribute("password", request.getParameter("password"));
request.setAttribute("sex", request.getParameter("sex"));
request.setAttribute("favious", Arrays.toString(request.getParameterValues("favious")));
request.setAttribute("description", request.getParameter("description"));
request.setAttribute("experience", request.getParameter("experience"));
request.setAttribute("fileName", uploadFile(request));
request.getRequestDispatcher("form_result.jsp").forward(request, response);
}
private String uploadFile(HttpServletRequest request) {
String fileName = "";
try {
Part filePart = request.getPart("photo");
fileName = getfileName(filePart);
String applicationPath = request.getServletContext().getRealPath("");
String basePath = applicationPath + File.separator + UPLOAD_DIR
+ File.separator;
// creates the save directory if it does not exists
File fileSaveDir = new File(basePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File outputFilePath = new File(basePath + fileName);
inputStream =filePart.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while((read = inputStream.read(bytes))!= -1) {
outputStream.write(bytes,0,read);
}
}catch(Exception ex) {
ex.printStackTrace();
fileName="";
}finally {
if(outputStream != null) {
outputStream.close();
}
if(inputStream != null) {
inputStream.close();
}
}
}catch(Exception ex){
fileName = "";
}
return fileName;
}
private String getfileName(Part part) {
final String partHeader = part.getHeader("content-disposition");
System.out.println("*****partHeader:" + partHeader);
for(String content : part.getHeader("content-disposition").split(";")) {
if(content.trim().startsWith("fileName")) {
return content.substring(content.indexOf('=')+ 1).trim()
.replace("\"", "");
}
}
return null;
}
}
Form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="DemoForm" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td> username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td valign="top"> Sex </td>
<td>
<input type="radio" name="sex" value="male" checked="checked"/>Male
<br>
<input type="radio" name="sex" value="female"/>Female
</td>
</tr>
<tr>
<td valign="top"> Favious </td>
<td>
<input type="checkbox" name="favious" value="fav1"/>Favios 1<br>
<input type="checkbox" name="favious" value="fav2"/>Favios 2<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 3<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 4<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 5<br>
</td>
</tr>
<tr>
<td valign="top"> Description:</td>
<td><textarea rows="10" cols="20" name="description"></textarea></td>
</tr>
<tr>
<td>Experiences</td>
<td>
<select name="experience">
<option value="1"> 1 year </option>
<option value="2"> 2 year </option>
<option value="3"> 3 year </option>
<option value="4"> 4 year </option>
</select>
</td>
</tr>
<tr>
<td valign="top"> Photo</td>
<td><input type="file" name="photo "/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save"/></td>
</tr>
</table>
</form>
</body>
</html>
Form_result.jsp
[<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Account Information</h3>
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td>Username</td>
<td> ${username}</td>
</tr>
<tr>
<td>Password</td>
<td> ${password}</td>
</tr>
<tr>
<td valign="top">Sex</td>
<td> ${sex}</td>
</tr>
<tr>
<td valign="top">Favious</td>
<td> ${favious}</td>
</tr>
<tr>
<td valign="top">Description</td>
<td> ${description}</td>
</tr>
<tr>
<td>Experience</td>
<td> ${experience}</td>
</tr>
<tr>
<td valign="top">Photo</td>
<td><img src="upload/${fileName}"></td>
</tr>
</table>
</body>
</html>][1]
I think the error is not in your file uploading. Your request has not been received by your servelet. Just comment out all the codes and check whether your doPost is working or not? Check the URL you are hitting.
The endpoint on which you are trying to upload the file is invalid.
Errorcode 404 means that the endpoint can not be found.
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>
I am trying to call a java method('method1') that runs some r code(using RCaller) when a specific button is clicked on a JSP page('button1'), but when i click on the button it doesn't do anything and I am getting no errors in the output. I'm trying to use a servlet to run the java method from a JSP file. I'd appreciate any help.
Analysis.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Analysis Page</title>
</head>
<body>
<center><h2>
Final year Prototype
</h2></center>
<center> <table border="0">
<thead>
<tr>
<th>Disabilities Analysis</th>
</tr>
</thead>
<tbody>
<tr>
<center><td></td></center>
</tr>
<tr>
<td>
<center>
Current HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
New HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
<form action="${pageContext.request.contextPath}/myservlet" method="POST">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
</center>
</td>
</tr>
<tr>
<td>
<center>
Return
</center>
</td>
</tr>
</tbody>
</table></center>
</body>
</html>
myServlet.java:
package webJava;
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("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TestMethods t = new TestMethods();
String button = request.getParameter("button");
if ("button1".equals(button)) {
t.method1();
} else if ("button2".equals(button)) {
t.method2();
} else if ("button3".equals(button)) {
t.method3();
} else {
}
request.getRequestDispatcher("/Analysis.jsp").forward(request, response);
}
}
TestMethods.java:
package webJava;
import java.io.File;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
public class TestMethods {
public void method1() {
try {
RCaller caller = new RCaller();
RCode code = new RCode();
caller.setRscriptExecutable("/Library/Frameworks/R.framework/Versions/3.3/Resources/Rscript");
caller.cleanRCode();
caller.setRCode(code);
// load the ggplot2 library into R
code.R_require("ggplot2");
// create a data frame in R using x and y variables
code.addRCode("df <- data.frame(x,y)");
// plot the relationship between x and y
File file = code.startPlot();
code.addRCode("ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method='lm') + ggtitle('y = f(x)')");
caller.runOnly();
ImageIcon ii = code.getPlot(file);
code.showPlot(file);
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void method2() {
//some code
}
public void method3() {
//some code
}
}
My project directory:
Screenshot
I'm currently learning JSP/Servelets. The following is code containing 2 JSP pages and a servlet, which works as follows:
JSP #1 requests user info, & passes it into a servlet.
The servlet Instantiates a JavaBean class, and passes it to the 2nd JSP, using the Session Object.
The 2nd JSP then displays the info that th user entered in the 1st JSP; the user can then hit the Return button to return to the 1st JSP.
My Question is: I've read in various Tutorials (notably Murach's JSP, which this code is based on) that if the Javabean attributes are passed to the session object rather than the request object, the JavaBean's values should be maintained throughout the session. However when I return to the first page, the JB fields are empty. Am i doing anything wrong? I would appreciate any help!
The following is the code:
1st 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>Email Application</title>
</head>
<body>
<h1>Join our Email list</h1>
<p>To join our email list, enter your name and email address below.<br>
Then, click on the Submit button</p>
<form action="addToEmailList" method="post">
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td>
<input type="text" name="firstName"
value = "<jsp:getProperty name="user" property="firstName"/>">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value = "<jsp:getProperty name="user" property="lastName"/>">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value = "<jsp:getProperty name="user" property="emailAddress"/>">
</td>
</tr>
<tr>
<td>I'm interested in these types of music:</td>
<td><select name="music" multiple>
<option value="rock">Rock</option>
<option value="country">Country</option>
<option value="bluegrass">Bluegrass</option>
<option value="folkMusic">Folk Music</option>
</select>
</td>
</tr>
<tr>
<td ></td>
<td><input type="submit" name="Submit"></td>
</tr>
</table>
</form>
</body>
Servlet:
public class AddToEmailListServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private String firstName;
private String lastName;
private String emailAddress;
private String[] musicTypes;
private Music music;
private User user;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
this.request = request;
this.response = response;
setInstanceVariables();
writeDataToFile();
forwardResponseToJSPpage();
System.err.println("Hello!");
}
private void setInstanceVariables()
{
this.firstName = getFirstName();
this.lastName = getLastName();
this.emailAddress = getEmailAddress();
this.musicTypes = request.getParameterValues("music"); //getMusic();
this.user = new User(firstName,lastName,emailAddress);
}
private String getFirstName()
{
return request.getParameter("firstName");
}
private String getLastName()
{
return request.getParameter("lastName");
}
private String getEmailAddress()
{
return request.getParameter("emailAddress");
}
private void writeDataToFile() throws IOException
{
String path = getRelativeFileName();
UserIO.add(user,path);
}
private String getRelativeFileName()
{
ServletContext sc = getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
return path;
}
private void forwardResponseToJSPpage() throws ServletException, IOException
{
if(this.emailAddress.isEmpty()||this.firstName.isEmpty()||this.lastName.isEmpty())
{
String url = "/validation_error.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
else
{
music = new Music(musicTypes);
HttpSession session = this.request.getSession();
session.setAttribute("music", music);
session.setAttribute("user", user);
String url = "/display_email_entry.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
2nd JSP:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# include file="/header.html" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><jsp:getProperty name="user" property="firstName"/></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><jsp:getProperty name="user" property="lastName"/></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><jsp:getProperty name="user" property="emailAddress"/></td>
</tr>
</table>
<p>We'll use the Email to otify you whenever we have new releases of the following types of music:</p>
<c:forEach items="${music.musicTypes}" var="i">
<c:out value="${i}"></c:out><br/>
</c:forEach>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action="join_email_list.jsp" method="post">
<input type="submit" value="Return">
</form>
</body>
<%# include file="/footer.html" %>
</html>
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.