MVC开发模式(举例)

本文通过一个实际的Java Web项目展示了MVC模式的运用,包括User类作为模型,CheckLogin和IndexServlet作为控制器,以及展示数据和用户交互的JSP页面。代码实现了用户登录、数据查询、删除功能,强调了业务逻辑与界面的分离。
摘要由CSDN通过智能技术生成

MVC开发模式

MVC解释:

MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
由于做项目的时候采用的模式就是MVC,但是具体不知道,那么来举个例子:

例:

在这里插入图片描述
代码功能主要是显示数据库,删除,登录等功能
User.java:

package Mvc;

import lombok.Data;

/**
 * @author netXiaobao
 * @version 1.0
 * @date 2020/11/23 15:46
 */
@Data
public class User {
    private String account;
    private String passwd;
    private String trueName;
}

CheckLogin.java

package Mvc;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * @author netXiaobao
 * @version 1.0
 * @date 2020/11/23 19:24
 */
@WebServlet("/check")
public class CheckLogin extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String a=req.getParameter("account");
        String b=req.getParameter("password");
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/showdb?serverTimezone=PRC","root","");
            QueryRunner run=new QueryRunner();

            //查询显示
            long count= run.query(conn,"select count(*) from net_user where account = ? and passwd = ?",new ScalarHandler<>(),a,b);
            String msg="";
            String url="";
            if (count==0){
                msg="登陆失败";
                url="Mvc/fail.jsp";
            }else if(count==1) {
                msg="登录成功";
                HttpSession s=req.getSession();
                s.setAttribute("account",a);
                url="Mvc/success.jsp";
            }
            req.setAttribute("msg",msg);

            //转发,可以使用req.setAttribute() 传值
            req.getRequestDispatcher(url).forward(req, resp);
        }catch (Exception e){
            e.printStackTrace();

        }

    }
}

Index.java

package Mvc;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * @author netXiaobao
 * @version 1.0
 * @date 2020/11/23 15:42
 */
@WebServlet("/")
public class Index extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/showdb?serverTimezone=PRC","root","");
            QueryRunner run=new QueryRunner();
            //删除
            if(req.getParameter("did")!=null){
                run.update(conn,"delete from net_user where account= ?",req.getParameter("did"));
            }
            //查询显示
          List<User> list= run.query(conn,"select account,passwd,trueName from net_user",new BeanListHandler<>(User.class));
          req.setAttribute("users",list);

          //转发,可以使用req.setAttribute() 传值
          req.getRequestDispatcher("Mvc/show.jsp").forward(req, resp);
        }catch (Exception e){
            e.printStackTrace();

        }
    }
}

Logout.java

package Mvc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author netXiaobao
 * @version 1.0
 * @date 2020/11/23 20:42
 */
@WebServlet("/logout")
public class Logout extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();
        session.invalidate();
        resp.sendRedirect("/Mvc");
    }
}

接下来是JSP代码:
show.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 86182
  Date: 2020/11/23
  Time: 15:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:if test="${sessionScope.account==null}">
    <a href="/Mvc/login.jsp">登录</a>
</c:if>

<c:if test="${sessionScope.account!=null}">
    <p>
        <h5>欢迎:${sessionScope.account}</h5>
    <a href="/logout">安全退出</a>
    </p>
</c:if>


<h3>显示数据</h3>
<c:forEach items="${users}" var="u">
    <p>${u.account}--${u.trueName}----
        <c:if test="${sessionScope.account!=null}">
        <a href="?did=${u.account}">删除</a></p>
        </c:if>
</c:forEach>

</body>
</html>

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86182
  Date: 2020/11/23
  Time: 19:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>管理登录</title>
</head>
<body>
<h3>管理登录</h3>
<form action="/check" method="post">
    账号:<input type="text" name="account"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
<hr>
<a href="/Mvc">返回首页</a>
</form>
</body>
</html>

fail.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86182
  Date: 2020/11/23
  Time: 19:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆失败</title>
</head>
<body>
<h3>登陆失败</h3>
<p STYLE="color: red">${msg}</p>
<br>
<a href="/Mvc/login.jsp">重新登陆</a>&nbsp;
<a href="/Mvc">返回首页</a>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86182
  Date: 2020/11/23
  Time: 19:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆成功</title>
</head>
<body>
<h3>登陆成功</h3>
<p STYLE="color: green">${msg}</p>
<br>

<a href="/Mvc">首页查看</a>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

netXiaobao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值