Servlet 和 SpringMVC的核心:控制器 作用一样,都是 转发控制器。将请求名字,和请求要执行的服务层程序对应起来。
Servlet 如:
例一:
@WebServlet("/ ")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行了控制器")
}
}
对于任何一个前端页面,右键运行后,地址栏生成文件路径URl,该Servlet 的URL请求拦截规则是“ / ” ,即会拦截所有,一运行前端页面就会执行,该Servlet,控制台输出 "执行了控制器"
例二:
html:
<html>
......
<form method="POST" action="LoginServlet">
......
</html>
Servlet :
@WebServlet("/LoginServlet ")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行了控制器")
}
}
前端页面,当表单被提交时有个 LoginServlet 请求。Servlet 程序中拦截规则是 @WebServlet("/LoginServlet ") ,产生LoginServlet 请求后,会自动执行该 Servlet 程序,输出 "执行了控制器"
SpringMVC 控制器
前端:
<html>
......
<form method="POST" action="Login">
......
</html>
SpringMVC 的 Controller
@Controller
public class LoginController {
@RequestMapping("Login")
@ResponseBody
public Login(){
System.out.println("执行了控制器,调用其他服务层语句")
}
}
前端页面,当表单被提交时有个 Login 请求。Controller 程序中自动匹执行 Login 请求的处理内容,调用 相关服务层程序。这里是输出 "执行了控制器,调用其他服务层语句"
综上所述,Servlet 和 SpringMVC的核心:控制器 作用一样,都是 转发控制器。接收各种名字的请求,转发调用各种服务程序,并返回结果值。即将请求名字,和请求要执行的服务层程序对应起来。
注意:
因此如果选择不使用用Spring MVC ,可以使用Servlet代替 Spring MVC 控制器