请给出一个mvc模式编程的实例,最简单的HelloWord。

2021-07-14 16:09:13 浏览数 (1)

马克-to-win:下 面我们先给出一个最简单的mvc例子。这是一个常见的购物车的例子。在下面的例子当中,作为View的add.jsp提交给作为Controller的 ServletHello1.java来处理。真正的处理过程交给了作为Model的Cart.java来处理。作为Controller的ServletHello1.java,用response.sendRedirect("add.jsp");这句话,最后控制流程跳转到 add.jsp。

例1.1.1:

add.jsp:

<%@ page contentType="text/html; charset=GBK" %>

<html>

<body>

<hr>

<center><h3>书目</h3></center>

<table border="1" width="300" cellspacing="0" cellpadding="3" align="center">

<tr><th>书名</th><th>价格</th></tr>

<tr>

<form action="MarkToWinServlet" method="post">

<td>Java自学</td>

<td>25</td>

<td><input type="submit" name="Submit" value="Add"></td>

<input type="hidden" name="id" value="1">

<input type="hidden" name="title" value="Java自学">

<input type="hidden" name="price" value="25">

</form>

</tr>

<tr>

<form action="MarkToWinServlet" method="post">

<td>C 精通</td>

<td>28</td>

<td><input type="submit" name="Submit" value="Add"></td>

<input type="hidden" name="id" value="2">

<input type="hidden" name="title" value="C 精通">

<input type="hidden" name="price" value="28">

</form>

</tr>

</table>

<a href="cart.jsp">看看购物车</a>

</body>

</html>

package com;

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;

public class ServletHello1 extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

HttpSession session = request.getSession();

Cart cart=(Cart)session.getAttribute("cart");

if(cart==null ) cart = new Cart();

request.setCharacterEncoding("GBK");

String id = request.getParameter("id");

String title = request.getParameter("title");

String price = request.getParameter("price");

cart.addItem(id, title, price);

session.setAttribute("cart", cart);

response.sendRedirect("add.jsp");

}

}

更多请看:https://blog.csdn.net/qq_44594371/article/details/103181401

jsp

0 人点赞