MVC in JSP Program Example

Required Files:


1. login.jsp
2. LoginBean.java             //Model Component
3. LoginServlet.java         //Controller Component
4. welcome.jsp                 //View Component
5. error.jsp                         //View Component



Project Structure:


login.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet">
UserName<input type="text" name="uname"><br>
Password<input type="password" name="pass"><br>
<input type="submit" value="login">
</form>
</body>
</html>

LoginBean.java

package java8s;
public class LoginBean {
    private String uname, password;

    publig String getUname()
    {
        return uname;
    }
    public void setUname(String uname)
    {
        this.uname=uname;
    }
    public String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password=password;
    }

    public boolean validation()
    {
        if(password.equals("silan"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

LoginServlet.java

package java8s;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LoginServlet extends HttpServlet {
    protected void doGet (HttpServletRequest request, HttpServletResponse
    response) throws ServletException, IOException {

        response. set ContentType ("text/html");
        PrintWriter out=response.getWriter();

        String s1=request.getParameter("uname");
        String s2=request.getParameter("pass");

        LoginBean obj=new LoginBean();
        obj.setUname (sl);
        obj.set Password (s2);

        boolean result=obj.validation();

        if(result)
        {
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
            rd. forward (request, response) ;
        }
        else
        {
            RequestDispatcher rd=request.getRequestDispatcher("error.jsp");
            rd. forward (request, response);
        }
    }
}

welcome.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
out.print("login is successful");
%>
</body>
</html>

error.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
out.print("sry!!!invalid password");
%>
</body>
</html>

Output:

img

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext