MVC思想
JavaEE前後的設計思想
- Model1:在早起的時候,JavaEE以JSP爲中心,使用JSP和JavaBean技術
開發一個簡答的應用,完全夠用。
但是當項目比較大的時候,存在的問題:JSP既要展示界面,又要處理請求,而JSP本身不是很擅長處理請求。
因此將處理請求提取出來,即Servlet。 - Model2:爲了解決Model中JSP不善於處理請求的操作,在Model2中引入Servlet,專門用於處理請求。
使用到的技術有:JSP、Servlet、JavaBean
以Servlet爲中心,所有請求都要先發給Servlet
各自做自己擅長的,這就是責任分離思想。 - MVC:
MVC最早應用與C/S領域,在JavaEE中發揚光大。主要強調責任分離思想。
M:Model (JavaBean)
V:View (JSP)
C:Control (Servlet)
每個請求對應一個響應。
合併Servlet
一開始一個對象需要寫四個(增刪改查)類,這樣當對象很多的時候,很不方便,於是我們用一個類來包含着四種操作。
package com.Bryan.smis.web.servlet;
import java.io.IOException;
import java.util.List;
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 com.Bryan.smis.dao.IStudentDAO;
import com.Bryan.smis.dao.impl.StudentDAOImpl;
import com.Bryan.smis.domain.Student;
//處理所有Student相關的請求操作
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1751771427617825274L;
private IStudentDAO dao;
public void init() throws ServletException {
dao = new StudentDAOImpl();
}
//分發操作
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//這一點要在獲取參數之前進行編碼轉化
req.setCharacterEncoding("UTF-8");
String cmd = req.getParameter("cmd");
if ("save".equals(cmd))
this.saveOrUpdate(req, resp);
else if ("edit".equals(cmd))
this.edit(req, resp);
else if ("delete".equals(cmd))
this.delete(req, resp);
else
this.list(req, resp);
}
//列表
//http://localhost/student
protected void list(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//1.接收請求參數,封裝對象
//2.調用業務方法處理請求
List<Student> list = dao.listAll();
//3.控制界面跳轉
req.setAttribute("student", list);
req.getRequestDispatcher("/WEB-INF/views/student/list.jsp").forward(req, resp);
System.out.println("List Done!");
System.out.println("!!!");
}
//編輯
//http://localhost/student?cmd=edit
protected void edit(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//1.接收請求參數,封裝對象
String id = req.getParameter("id");
//2.調用業務方法處理請求
if (hasLength(id)) {
Student stu = dao.get(id);
req.setAttribute("student", stu);
}
//3.控制界面跳轉
req.getRequestDispatcher("/WEB-INF/views/student/edit.jsp").forward(req, resp);
}
//刪除操作
//http://localhost/student?cmd=delete
protected void delete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//1.接收請求參數,封裝對象
String id = req.getParameter("id");
//2.調用業務方法處理請求
dao.delete(id);
//3.控制界面跳轉
resp.sendRedirect("/student");
System.out.println("Delete Done!");
}
//新增或更新
//http://localhost/student?cmd=save
protected void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//1.接收請求參數,封裝對象
String id = req.getParameter("id");
String name = req.getParameter("name");
String gender = req.getParameter("gender");
String age = req.getParameter("age");
Student stu = new Student(id, name, gender, Integer.valueOf(age));
//2.調用業務方法處理請求
if (dao.get(id) != null) {
dao.update(id, stu);
} else {
dao.save(stu);
}
//3.控制界面跳轉
resp.sendRedirect("/student");
}
private boolean hasLength(String str) {
return str != null && !"".equals(str.trim());
}
}
同時修改 list.jsp 和 edit.jsp 中的資源名稱:
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>CURD</title>
</head>
<body>
<a href="/student?cmd=edit">Addition</a>
<table border="1" width="80%" cellpadding="0" cellspacing="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Operation</th>
</tr>
<c:forEach items="${student}" var="s" varStatus="vs">
<tr style='background-color: ${vs.count % 2 == 0 ? "aqua":""}'>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.age}</td>
<td>
<a href="/student?cmd=delete&id=${s.id}">Delete</a> |
<a href="/student?cmd=edit&id=${s.id}">Edit</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
edit.jsp
<%@ page language="java" contentType="text/html; charset=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>CURD</title>
</head>
<body>
<h3>${student == null?" 添加學生 ":" 更新學生 "}</h3>
<form action="/student?cmd=save" method="post">
學號:<input type="text" name="id" required value="${student.id}"/><br/>
姓名:<input type="text" name="name" required value="${student.name}"/><br/>
性別:<input type="radio" name="gender" value="M" ${student.gender =="M" ? "checked":""}/>男
<input type="radio" name="gender" value="F" ${student.gender =="F" ? "checked":""}/>女<br/>
年齡:<input type="number" name="age" required value="${student.age}"/><br/>
<input type="submit" value='${student == null?" 保存 ":" 更新 "}'>
<input type="button" value="查看列表" onclick="window.location.href='/student?cmd=list'">
</form>
</body>
</html>
若我們將部署的工程添加上下文路徑,則要修改源代碼中的資源路徑,這顯然不是我們想要的,因此,在JSP文件中,使用
${pageContext.request.contextPath}
若報錯,則從Tomcat中找一個 jsp-api.jar 包,然後帶java代碼中,也加上上下文路徑:
resp.sendRedirect(req.getContextPath() + "/student");
注意,在保存操作時用請求轉發會導致死循環:
req.getRequestDispatcher("/student").forward(req, resp);
因爲會將cmd中的save值也會作爲請求而保留下來繼續進行請求。因此儘量使用重定向。
另一個問題,當在刪除操作中重複操作刪除內容時:
不能在一個請求中向不同資源做跳轉。