国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home 類庫下載 java類庫 MVC mode realizes login and login of adding, deleting, modifying and checking

MVC mode realizes login and login of adding, deleting, modifying and checking

Nov 04, 2016 pm 05:15 PM
mvc

I am not using a maven project here, I am using a general web project, so I need to download and add the framework packages I need to use. In the project, I must pay attention to the configuration of the environment. I am using jre1.7

1 Create a new project

MVC mode realizes login and login of adding, deleting, modifying and checking

2 Establish the MVC management package and import the corresponding rack package servlet

MVC mode realizes login and login of adding, deleting, modifying and checking

3 Create the entity class teacher.java corresponding to the database

public class Teacher {
            private  int  tid;
            private  String tname;
            private  String tpsw;
            public int getTid() {
                return tid;
            }
            public void setTid(int tid) {
                this.tid = tid;
            }
            public String getTname() {
                return tname;
            }
            public void setTname(String tname) {
                this.tname = tname;
            }
            public String getTpsw() {
                return tpsw;
            }
            public void setTpsw(String tpsw) {
                this.tpsw = tpsw;
            }
            public Teacher(String tname, String tpsw) {
                super();
                this.tname = tname;
                this.tpsw = tpsw;
            }
            public Teacher(int tid, String tname, String tpsw) {
                super();
                this.tid = tid;
                this.tname = tname;
                this.tpsw = tpsw;
            }
            public Teacher() {
                super();
            }
}

4 Write a new login.jsp file in WebContent Login box

1

2

3 Username:

4 Password:

5

6


5 Configure the web.xml file corresponding to the form request login

MVC mode realizes login and login of adding, deleting, modifying and checking

web .xml file

Note: When configuring, must be before, otherwise an error will be reported

<!-- 提交登錄請求 -->
  <servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.zr.controller.LoginController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>

6 Write the corresponding request entity class LoginController.java: Inherit HttpServlet and rewrite the doget(), dopost() methods, according to the different method requests Call the doget or dopost method

LoginController.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.zr.model.Teacher;
import com.zr.service.valiDateService;
import com.zr.serviceIm.valiDateServiceImpl;
public class LoginController   extends  HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
         throws ServletException, IOException {
                super.doPost(req, resp);
            }
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
           //獲取前臺form表單的input輸入框
           String tname=req.getParameter("tname");
           String tpsw=req.getParameter("tpsw");
           Teacher tc=new Teacher();
           tc.setTname(tname);
           tc.setTpsw(tpsw);
           valiDateService vds=new valiDateServiceImpl();
          Teacher t=    vds.valiDateTeacher(tc);
        HttpSession  session=req.getSession();
        session.setAttribute("teacher", t);
        if (t!=null) {
            //返回的不是空值,重定向到登錄成功界面
            req.getRequestDispatcher("main.jsp").forward(req, resp);
        } else {
            //返回空值,請求轉(zhuǎn)發(fā)到登錄界面
            resp.sendRedirect("login.jsp");
        }      
            }
}

7 Write from the background dao layer to the control layer

public interface TeacherDao {
    
    /**
     * 驗證老師是否存在
     * @param tc
     * @return
     */
    public Teacher validateTeacher(Teacher tc);
}

8.1 Write the encapsulation class to establish the connection with the database JDBCUtil.java

package JDBCUtil;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

    public class JDBCUtil {
         //1.數(shù)據(jù)庫地址  (根據(jù)不同的數(shù)據(jù)標準是不一樣)
          private  final  static String DBURL = "jdbc:mysql://localhost:3306/student_crm?useUnicode=true&characterEncoding=UTF8";
          //2.設(shè)置用戶和密碼
          private  final  static String  USERNAME = "root";
          private  final  static String  PASSWORD = "root";
          //3.設(shè)置驅(qū)動名稱 (根據(jù)不同的數(shù)據(jù)標準是不一樣)
          private  final  static String  DBDRIVER = "com.mysql.jdbc.Driver";
          /**
           * 獲取數(shù)據(jù)庫連接
           * @return  返回數(shù)據(jù)庫連接
           */
          public  static  Connection  getConnection(){
              Connection  con = null;
              try {
                Class.forName(DBDRIVER);
                con  =  DriverManager.getConnection(DBURL, USERNAME, PASSWORD);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
              return  con;    
          }
//關(guān)閉連接 
          public static void  closeJDBC(Statement st,Connection  con) throws SQLException{
                if(st!=null){
                    st.close();
                }
                if(con!=null){
                    con.close();
                }
          }

}

8.2 Implementation of the dao layer

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zr.dao.TeacherDao;
import com.zr.model.Teacher;
import JDBCUtil.JDBCUtil;
public class TeacherDaoImpl implements TeacherDao{
    /**
     * 輸入老師的對象,返回老師對象
     * @param args
     */
    public Teacher validateTeacher(Teacher tc) {
        Teacher teacher=new Teacher();
        //sql語句
        StringBuffer sql=new StringBuffer("select * from teacher where tname=? and tpsw=?");
        //獲取數(shù)據(jù)庫連接
        Connection con=JDBCUtil.getConnection();
        try {
            PreparedStatement  pst=con.prepareStatement(sql.toString());
            pst.setString(1, tc.getTname());
            pst.setString(2, tc.getTpsw());
            //返回一個結(jié)果集
            ResultSet rs=pst.executeQuery();
            if (rs.next()) {
            //把結(jié)果集里面的數(shù)據(jù)放入對應(yīng)的teacher對象
                teacher=new Teacher(rs.getInt("tid"),rs.getString("tname"),rs.getString("tpsw"));
            } 
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return teacher;
    }
}

9 Service Layer

public interface valiDateService {
/**
 * @param tc
 * @return 老師對象
 * 根據(jù)用戶輸入值驗證老師是否存在
 */
    public Teacher valiDateTeacher(Teacher tc);

}

10 Service layer implements ServiceImpl.java

import com.zr.dao.TeacherDao;
import com.zr.daoIm.TeacherDaoImpl;
import com.zr.model.Teacher;
import com.zr.service.valiDateService;
public class valiDateServiceImpl implements valiDateService{
    public Teacher valiDateTeacher(Teacher tc) {
        //父類的引用指向子類的對象,父類可以直接調(diào)用子類的方法
        TeacherDao teacherDao=new TeacherDaoImpl();
        //調(diào)用dao層的方法驗證存在
        Teacher teacher=teacherDao.validateTeacher(tc);
        return teacher;
    }
}

11 com.zr.controller layer

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.zr.model.Teacher;
import com.zr.service.valiDateService;
import com.zr.serviceIm.valiDateServiceImpl;
public class LoginController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 獲取前臺form表單的input輸入框
        String tname = req.getParameter("tname");
        String tpsw = req.getParameter("tpsw");
        // 將前臺對象放入tc對象,作為輸入?yún)?shù)
        Teacher tc = new Teacher();
        tc.setTname(tname);
        tc.setTpsw(tpsw);
        // 調(diào)用Service層的方法傳入tc對象,并用t接收返回結(jié)果
        valiDateService vds = new valiDateServiceImpl();
        Teacher t = vds.valiDateTeacher(tc);
        // 獲取JSP作用域session,將老師t對象放入session
        HttpSession session = req.getSession();
        int a = t.getTid();//最好根據(jù)返回的老師的id進行判斷
        if (a != 0) {
            // 返回的有id,重定向到登錄成功界面
            req.getRequestDispatcher("main.jsp").forward(req, resp);
            session.setAttribute("teacher", t);
        } else {
            // 返回空值,請求轉(zhuǎn)發(fā)到登錄界面
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }
}


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP MVC Architecture: Building Web Applications for the Future PHP MVC Architecture: Building Web Applications for the Future Mar 03, 2024 am 09:01 AM

Introduction In today's rapidly evolving digital world, it is crucial to build robust, flexible and maintainable WEB applications. The PHPmvc architecture provides an ideal solution to achieve this goal. MVC (Model-View-Controller) is a widely used design pattern that separates various aspects of an application into independent components. The foundation of MVC architecture The core principle of MVC architecture is separation of concerns: Model: encapsulates the data and business logic of the application. View: Responsible for presenting data and handling user interaction. Controller: Coordinates the interaction between models and views, manages user requests and business logic. PHPMVC Architecture The phpMVC architecture follows the traditional MVC pattern, but also introduces language-specific features. The following is PHPMVC

An advanced guide to PHP MVC architecture: unlocking advanced features An advanced guide to PHP MVC architecture: unlocking advanced features Mar 03, 2024 am 09:23 AM

The MVC architecture (Model-View-Controller) is one of the most popular patterns in PHP development because it provides a clear structure for organizing code and simplifying the development of WEB applications. While basic MVC principles are sufficient for most web applications, it has some limitations for applications that need to handle complex data or implement advanced functionality. Separating the model layer Separating the model layer is a common technique in advanced MVC architecture. It involves breaking down a model class into smaller subclasses, each focusing on a specific functionality. For example, for an e-commerce application, you might break down the main model class into an order model, a product model, and a customer model. This separation helps improve code maintainability and reusability. Use dependency injection

Uncovering the success of the SpringMVC framework: why it is so popular Uncovering the success of the SpringMVC framework: why it is so popular Jan 24, 2024 am 08:39 AM

SpringMVC framework decrypted: Why is it so popular, specific code examples are needed Introduction: In today's software development field, the SpringMVC framework has become a very popular choice among developers. It is a Web framework based on the MVC architecture pattern, providing a flexible, lightweight, and efficient development method. This article will delve into the charm of the SpringMVC framework and demonstrate its power through specific code examples. 1. Advantages of SpringMVC framework Flexible configuration method Spr

How to implement the MVC pattern using PHP How to implement the MVC pattern using PHP Jun 07, 2023 pm 03:40 PM

The MVC (Model-View-Controller) pattern is a commonly used software design pattern that can help developers better organize and manage code. The MVC pattern divides the application into three parts: Model, View and Controller, each part has its own role and responsibilities. In this article, we will discuss how to implement the MVC pattern using PHP. Model A model represents an application's data and data processing. usually,

How to use MVC architecture to design projects in PHP How to use MVC architecture to design projects in PHP Jun 27, 2023 pm 12:18 PM

In Web development, MVC (Model-View-Controller) is a commonly used architectural pattern for processing and managing an application's data, user interface, and control logic. As a popular web development language, PHP can also use the MVC architecture to design and build web applications. This article will introduce how to use MVC architecture to design projects in PHP, and explain its advantages and precautions. What is MVCMVC is a software architecture pattern commonly used in web applications. MV

How to implement scalable MVC architecture in PHP8 framework How to implement scalable MVC architecture in PHP8 framework Sep 11, 2023 pm 01:27 PM

How to implement a scalable MVC architecture in the PHP8 framework Introduction: With the rapid development of the Internet, more and more websites and applications adopt the MVC (Model-View-Controller) architecture pattern. The main goal of MVC architecture is to separate different parts of the application in order to improve the maintainability and scalability of the code. In this article, we will introduce how to implement a scalable MVC architecture in the PHP8 framework. 1. Understand the MVC architecture pattern. The MVC architecture pattern is a software design

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Sep 11, 2023 am 09:43 AM

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Introduction: With the rapid development of the Internet, Web development plays an important role in today's software development industry. PHP is widely used for web development, and there are many mature frameworks that help developers build applications more efficiently. Among them, the MVC (Model-View-Controller) architecture is one of the most common and widely used patterns. This article will introduce how beginners can use the PHP8 framework to develop MVC applications.

Revealing the secrets of PHP MVC architecture: Make your website fly Revealing the secrets of PHP MVC architecture: Make your website fly Mar 03, 2024 am 09:25 AM

Model-view-controller (mvc) architecture is a powerful design pattern for building maintainable and scalable WEB applications. The PHPMVC architecture decomposes application logic into three distinct components: Model: represents the data and business logic in the application. View: Responsible for presenting data to users. Controller: Acts as a bridge between the model and the view, handling user requests and coordinating other components. Advantages of MVC architecture: Code separation: MVC separates application logic from the presentation layer, improving maintainability and scalability. Reusability: View and model components can be reused across different applications, reducing code duplication. Performance Optimization: MVC architecture allows caching of view and model results, thus increasing website speed. Test Friendly: Detachment

See all articles