MVC编程模式: mvc是一种使用MVC(Model View Controller 模型-视图-控制器)设计创建Web应用程序的模式
(1) Model(模型)表示应用程序核心(比如数据库记录字段)。(对应数据库)作用(业务逻辑,保存数据的状态)
(2) View(视图)显示数据(数据库记录)。(对应前端)作用(显示页面)
(3) Controller(控制器)处理输入(写入数据库记录)。(对应后端)作用(取得表单数据,调用业务逻辑,转向指定的页面)
传统MVC框架的作用
①将url映射到java类或java类的方法
②封装用户提交的数据
③处理请求–调用相关的业务处理–封装响应数据
④将响应的数据进行渲染,jsp/html等表示层数据
代码实列
(1)首先构建Servlet
package com.ly.servlet;
//传统mvc框架
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet { //继承Servlet接口
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1,获取前端参数
String method = req.getParameter("method"); //传递数据,对象为String类,从web客户端传到web服务器端,代表HTTP请求数据
if(method.equals("add")){
req.getSession().setAttribute("msg","执行了add方法");
}
if(method.equals("delete")){
req.getSession().setAttribute("msg","执行了delete方法");
}
//2.调用业务层
//3.试图转发或者重定向
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp); //复用
}
}
(2)创建jsp文件
```java
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg} <!--取出msg的数据-->
</body>
</html>
(3)编写xml文件
```java
```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.ly.servlet.HelloServlet</servlet-class>
<!--servlet定义的name与自己定义servlet类的路径-->
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern> <!--路径-->
</servlet-mapping>
<session-config>
<session-timeout>15</session-timeout> <!--session超时时间-->
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--欢迎页,相当于首页-->
</web-app>
(4)实现效果
