MVC JSP Program:
Index.jsp(Front-end Design)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="ControllerServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Login-error.jsp (view failure)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<p>Sorry! username or password error</p>
<%@ include file="index.jsp" %>
</body>
</html>
Login-success.jsp(View Success)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="bean.LoginBean"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<p>You are successfully logged in!</p>
<%
LoginBean bean=(LoginBean)request.getAttribute("bean");
out.print("Welcome, "+bean.getName());
%>
</body>
</html>
LoginBean.java (JavaBean and validate)
package bean;
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;
}
ControllerServlet.java ( Controller)
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
public class ControllerServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name=request.getParameter("name");
String password=request.getParameter("password");
LoginBean bean1=new LoginBean(); //using java bean
bean1.setName(name); //set the value to java bean
bean1.setPassword(password);
request.setAttribute("bean",bean1); //set attribute to table key and values
boolean status=bean1.validate(); //calling the validate fucation in javabean
if(status) //return true success or false faliure
RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
rd.forward(request, response);
else{
RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
rd.forward(request, response);
Output:
Success in jsp
Failure in jsp