Spring MVC [entry]

MVC Design Overview

In the early Java Web development in the unified display layer, the control layer, data layer operation of all to the JSP or JavaBean to handle, we call Model1:

 
  • Drawbacks arise:
  • Serious coupling between the JSP and Java Bean, Java code and HTML code are also coupled together
  • It requires developers not only to master Java, but also a superb front-end level
  • Front and rear interdependence, need to wait for the backend to complete the front-end, back-end is also dependent on the completion of the front end, in order to effectively test
  • Code reuse is difficult

Because of the above drawbacks, so in this way it was soon replaced by the Servlet + JSP + Java Bean, early MVC model (Model2) such as the following figure:

 

First, the user's request will reach the Servlet, then calls the appropriate Java Bean, upon request, and all the displayed results to the JSP to complete, so we called MVC pattern mode.

  • M represents the model (Model)
    What model is it? It is the data model, that is, dao, bean
  • V represents the view (View)
    what view is it? That is, pages, JSP, used to display the data model
  • C represents the controller (controller)
    What controllers? The controller's role is to different data (Model), show that such a role in the different views (View), Servlet plays.

Let's write about our first Spring MVC program:

Further reading: Web development model

Spring MVC architecture

To solve the persistence layer has been good database transaction untreated programming, but also in order to meet the strong rise of NoSQL, Spring MVC gives the program:

 
 

传统的模型层被拆分为了业务层(Service)和数据访问层(DAO,Data Access Object)。 在 Service 下可以通过 Spring 的声明式事务操作数据访问层,而在业务层上还允许我们访问 NoSQL ,这样就能够满足异军突起的 NoSQL 的使用了,它可以大大提高互联网系统的性能。

  • 特点:
    结构松散,几乎可以在 Spring MVC 中使用各类视图
    松耦合,各个模块分离
    与 Spring 无缝集成

示例:

1、在web.xml 配置一个DispatcherServlet 并且使用 
初始化参数 contextConfigLocation 关联容器对应的配置文件 

可以<url-pattern>元素的值改为 / ,表示要拦截所有的请求,并交由Spring MVC的后台控制器来处理(也可以用*)

contextConfigLocation 关联容器对应的配置文件 也可以写到WebContent下面的WEB-INF下面,这个时候就不用再web.xml中配置初始化上下文配置,如果不配置,运行servers的时候,编译器会报这个异常,xml文件名字自定义可改

 

 

2、编写netmk_web.xml(也就是异常报错说缺少dispatcher-servlet.xml,名字可自定义的哈)

开启基于标注 Spring MVC
开启组件扫描 <context:component-scan base-package="" /> 
开启mvc的标注 <mvc:annotation-driven /> 自动配置了一个HandlerMapping 

3、编写一个普通的java类使用@Controller 把java类变成控制器
控制器方法的返回值可以是String也可以是 ModelAndView 

方法名任意参数任意 在控制器方法上加 @RequestMapping("/请求路径") 

 

我这里创建了个实体类,使用了实体里面的属性

 

4、在WEB-INF建立一个login.jsp 

重启服务器之后

测试结果如下:

控制台显示:

 

 

 

Guess you like

Origin www.cnblogs.com/xss512/p/10954614.html