Here used JSP as a view component, JAVA Bean class as a model, servlet as a controller.
index.jsp
[java]
<form action="ControllerServlet" method="post">
Name:<input type="text" name="name">
Password:<input type="password" name="password">
<input type="submit" value="login">
</form>
[/java]
ControllerServlet.java
[java]package SPlessons;
import java.io.IOException;
import java.io.PrintWriter;
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 ControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("name");
String password=request.getParameter("password");
LoginBean bean=new LoginBean();
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean",bean);
boolean status=bean.validate();
if(status){
RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
rd.forward(request, response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
rd.forward(request, response);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
[/java]
Created object to the LoginBean and applied setAttribute method.
[java]LoginBean bean=new LoginBean();
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean",bean);[/java]
Used validation method to the status, to validate the conditions.
[java]boolean status=bean.validate(); [/java]
LoginBean.java
[java]package SPlessons;
public class LoginBean {
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean validate(){
if(password.equals("admin")){
return true;
}
else{
return false;
}
}
} [/java]
Created password name as admin. If user need dynamic password then database is needed.
[java]if(password.equals("admin")){
return true;
} [/java]
login-success.jsp
[java]<%@page import="SPlessons.LoginBean"%>
You are successfully logged in!
<% LoginBean bean=(LoginBean)request.getAttribute("bean"); out.print("Welcome, "+bean.getName()); %> [/java]
login-error.jsp
[java]
Sorry! username or password error
<%@ include file="index.jsp" %> [/java]
Output
Output will be as follows, where user has to enter the name and password, if entered details are valid another
page will be displayed.
After enter the name and password(admin) following page will be displayed.