什么是MVC
MVC:Model、view、Controller(实体、视图、控制器)
以前的框架
弊端
- 用户直接访问控制层,控制层就可以直接操作数据库;
- 控制器代码非诚臃肿,需要处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
解决 - 将控制器任务划分成两层,分别完成是Controller与Service
现在的框架
Model
View
Controller
- 接收用户请求
- 交给业务层处理对应的代码
- 控制视图的跳转
实例讲解MVC
由于这里的逻辑处理非常简单,所以没有出现Service层
public class User {
public long id;
public String name;
public School school;
}
public class School {
public String name;
public String address;
}
@WebServlet(urlPatterns = "/user")
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
School school = new School("No.1 Middle School", "101 South Street");
User user = new User(123, "Bob", school);
req.setAttribute("user", user);
req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp);
}
}
<%@ page import="com.itranswarp.learnjava.bean.*"%>
<%
User user = (User) request.getAttribute("user");
%>
<html>
<head>
<title>Hello World - JSP</title>
</head>
<body>
<h1>Hello <%= user.name %>!</h1>
<p>School Name:
<span style="color:red">
<%= user.school.name %>
</span>
</p>
<p>School Address:
<span style="color:red">
<%= user.school.address %>
</span>
</p>
</body>
</html>
- 浏览器访问http://localhost:8080/user
MVC高级开发
问题
- 在实例讲解MVC中,控制器使用的是Servlet,视图使用的是JSP,如果这样直接把MVC搭在Servlet和JSP之上还是不太好,因为:
- JSP也页面开发不友好,更好的替代品是模板引擎;
- 业务逻辑最好由纯粹的Java类实现,而不是强迫继承Servlet
解决
- 通过普通的Java类实现MVC的Controller
@GetMapping("/hello")
public ModelAndView hello(String name);
@PostMapping("/signin")
public ModelAndView doSignin(SignInBean bean);
@GetMapping("/signout")
public ModelAndView signout(HttpSession session)
参考廖雪峰
|