VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • C#
  • Python
  • PHP
  • Excel
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Eclipse
    • Phần mềm tiện ích
    • Cấu trúc DL&GT
    • Selenium Test

JSP Tuts

JSP là gì? Học JSP cần chuẩn bị những gì? Kiến trúc JSP Vòng đời của JSP Cú pháp trong JSP Tạo ứng dụng JSP trên Eclipse MVC trong JSP Các đối tượng ẩn trong JSP Xử lý ngoại lệ trong JSP

8 Đối Tượng Ẩn Trong JSP

Đối tượng JSP Request Đối tượng JSP Response Đối tượng JSP Config Đối tượng JSP Page Đối tượng JSP PageContext Đối tượng JSP Application Đối tượng JSP Session Đối tượng JSP Exception
List Câu Hỏi Phỏng Vấn JSP
1 / 3
❮ ❯

MVC trong JSP


Học servlet
Học java core

MVC là viết tắt của Model View Controller là một mẫu thiết kế phần mềm được chia thành 3 phần riêng biệt đó là xử lý nghiệp vụ, xử lý giao diện và dữ liệu.


Nội dung chính

  • Ví dụ về MVC trong JSP
  • Run ứng dụng
  • Download Source Code

Ví dụ về MVC trong JSP

Trong ví dụ này chúng ta sử dụng servlet như một controller, jsp như một thành phần view và lớp java bean như một model.

Cấu trúc project:

Ví dụ MVC trong JSP

Trong đó:

  • index.jsp là trang thu thập thông tin người dùng.
  • ControllerServlet.java một servlet được cài đặt như một controller.
  • login-success.jsp và login-error.jsp là các view.
  • web.xml là file mapping servlet.

File: LoginBean.java

package vn.viettuts;

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 ("admin".equals(password)) {
            return true;
        } else {
            return false;
        }
    }
}

File: LoginController.java

package vn.viettuts;

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 LoginController 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);
    }
}

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>jsp-mvc-example</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>LoginController</servlet-name>
        <servlet-class>vn.viettuts.LoginController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginController</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

</web-app>

File: index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Vi du MVC trong JSP</title>
</head>
<body>
  <form action="login" method="post">
    Username: <input type="text" name="name"><br>
    Password:<input type="password" name="password"><br>
    <input type="submit" value="login">
  </form>
</body>
</html>

File: login-success.jsp

<%@page import="vn.viettuts.LoginBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Login Success</title>
</head>
<body>
  <p>You are successfully logged in!</p>
  <%
      LoginBean bean = (LoginBean) request.getAttribute("bean");
      out.print("Welcome, " + bean.getName());
  %>
</body>
</html>

File: login-error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Login Error</title>
</head>
<body>
  <p>username or password is incorrect!</p>
  <%@ include file="index.jsp"%>
</body>
</html>

Run ứng dụng

Hiển thị ban đầu:

Ví dụ MVC trong JSP

Nhập Username=Lucky và Password="admin":

Ví dụ MVC trong JSP

Click Login:

Ví dụ MVC trong JSP

Download Source Code

Download Now!

Học servlet
Học java core

Recent Updates

Lớp JSpinner trong Java SwingĐối tượng config trong JSPĐối tượng exception trong JSPĐối tượng page trong JSPĐối tượng pageContext trong JSPĐối tượng request trong JSPĐối tượng response trong JSPĐối tượng session trong JSPKiến trúc JSPMVC trong JSPTạo ứng dụng JSP trên EclipseVòng đời của JSPSắp Tết 2026 Rồi! - Còn bao nhiêu ngày nữa là đến tết 2026?

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn
Danh Sách Bài Học

Học Java | Hibernate | Spring
Học Excel | Excel VBA
Học Servlet | JSP | Struts2
Học C | C++ | C#
Học Python
Học SQL

Bài Tập Có Lời Giải

Bài tập Java
Bài tập C
Bài tập C++
Bài tập C#
Bài tập Python
Ví dụ Excel VBA

Câu Hỏi Phỏng Vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml