对于简单的Java Web项目,我们的项目仅仅包含几个jsp页面,由于项目比较小,我们通常可以通过链接方式进行jsp页面间的跳转。

但是如果是一个中型或者大型的项目,上面那种方式就会带来许多维护困难,代码复用率低等问题。因此,我们推荐使用MVC模式。

一 MVC概念

1、什么是MVC

MVC的全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计模式。它是用一种业务逻辑、数据与界面显示分离的方法来组织代码,将众多的业务逻辑聚集到一个部件里面,在需要改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑,达到减少编码的时间。

MVC开始是存在于桌面程序中的,M是指业务模型,V是指用户界面,C则是控制器。

使用的MVC的目的:在于将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。比如Windows系统资源管理器文件夹内容的显示方式,下面两张图中左边为详细信息显示方式,右边为中等图标显示方式,文件的内容并没有改变,改变的是显示的方式。不管用户使用何种类型的显示方式,文件的内容并没有改变,达到M和V分离的目的。

在网页当中:

  • V:即View视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。在视图中其实没有真正的处理发生,它只是作为一种输出数据并允许用户操纵的方式;
  • M:即model模型是指模型表示业务规则。在MVC的三个部件中,模型拥有最多的处理任务。被模型返回的数据是中立的,模型与数据格式无关,这样一个模型能为多个视图提供数据,由于应用于模型的代码只需写一次就可以被多个视图重用,所以减少了代码的重复性;
  • C:即controller控制器是指控制器接受用户的输入并调用模型和视图去完成用户的需求,控制器本身不输出任何东西和做任何处理。它只是接收请求并决定调用哪个模型构件去处理请求,然后再确定用哪个视图来显示返回的数据;

下图说明了三者之间的调用关系:

用户首先在界面中进行人机交互,然后请求发送到控制器,控制器根据请求类型和请求的指令发送到相应的模型,模型可以与数据库进行交互,进行增删改查操作,完成之后,根据业务的逻辑选择相应的视图进行显示,此时用户获得此次交互的反馈信息,用户可以进行下一步交互,如此循环。

常见的服务器端MVC框架有:Struts、Spring MVC、ASP.NET MVC、Zend Framework、JSF;常见前端MVC框架:vue、angularjs、react、backbone;由MVC演化出了另外一些模式如:MVP、MVVM。

注意:我们应该避免用户通过浏览器直接访问jsp页面。

2、MVC举例一(jsp+servlet+javabean)

最典型的MVC就是jsp+servlet+javabean模式:

  • Serlvet作为控制器,用来接收用户提交的请求,然后获取请求中的数据,将之转换为业务模型需要的数据模型,然后调用业务模型相应的业务方法进行更新(这一块也就是Model层所做的事情),同时根据业务执行结果来选择要返回的视图;
  • JavaBean作为模型,既可以作为数据模型来封装业务数据(对应实体类),又可以作为业务逻辑模型来包含应用的业务操作(对应Action类)。其中,数据模型用来存储或传递业务数据,而业务逻辑模型接收到控制器传过来的模型更新请求后,执行特定的业务逻辑处理,然后返回相应的执行结果;实践中会采用一个实体类来持有模型状态,并将业务逻辑放到一个Action类中。
  • JSP作为表现层,负责提供页面为用户展示数据,提供相应的表单(Form)来用于用户的请求,并在适当的时候(点击按钮)向控制器发出请求来请求模型进行更新;

每个控制器中可以定义多个请求URL,每个用户请求都发送给控制器,请求中的URL标识出对应的Action。Action代表了Web应用可以执行的一个操作。一个提供了Action的Java对象称为Action对象。一个Action类型可以支持多个Action(在Spring MVC以及Struts2中),或一个Action(在struts1中)。

注意:Struts1、Spring MVC和JavaServer Fces使用Servlet作为控制器,而Struts2使用Filter作为控制器。

3、MVC举例二(Struts2框架)

Struts2框架:Struts2是基于MVC的轻量级的web应用框架。Struts2的应用范围是Web应用,注重将Web应用领域的日常工作和常见问题抽象化,提供一个平台帮助快速的完成Web应用开发。基于Struts2开发的Web应用自然就能实现MVC,Struts2着力于在MVC的各个部分为开发提供相应帮助。

下面通过代码来简单解释一下(这里只是简单使用):

Login.html(位于WebContent下)

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <form id="form1" name="form1" action="/action/Login.action" method="post">
  9. 登录<br>
  10. 用户名:<input name="username" type="text"><br>
  11. 密码:<input name="password" type="password"><br>
  12. <input type="submit" value="登录">
  13. </form>
  14. </body>
  15. </html>

LoginAction.Java(位于包com.dc365.s2下)

  1. if(username.equals("1") && password.equals("1")) {
  2. return "Success";
  3. }
  4. return "Error";

struts.xml(位于src下)

  1. <struts>
  2. <package name="default" namespcase="/action" extends="struts-default">
  3. <action name="Login" class="com.dc365.s2.LoginAction">
  4. <result name="Success">Success.jsp</result>
  5. <result name="Error">Error.jsp</result>
  6. </action>
  7. </package>
  8. </struts>

注意:除了上面代码,还需要在web.xml里面配置前端过滤器FilterDispatcher。

用户首先在Login.html中输入用户名和密码,点击登陆,用户请求(请求路径为/action/Login.action)首先到达前端控制器FilterDispatcher,FilterDispatcher根据用户请求的URL和配置在struts.xml找到对应的Login,然后根据对应的class的路径进入相应的login.Java,在这里判断之后,返回success或error,然后根据struts.xml中的result值,指向相应的jsp页面。

  • 控制器——filterdispatcher:从上面这张图来看,用户请求首先到达前端控制器FilterDispatcher。FilterDispatcher负责根据用户提交的URL和struts.xml中的配置,来选择合适的动作(Action),让这个Action来处理用户的请求。FilterDispatcher其实是一个过滤器(Filter,servlet规范中的一种web组件),它是Struts2核心包里已经做好的类,不需要我们去开发,只是要在项目的web.xml中配置一下即可。FilterDispatcher体现了J2EE核心设计模式中的前端控制器模式。
  • 动作——Action:在用户请求经过FilterDispatcher之后,被分发到了合适的动作Action对象。Action负责把用户请求中的参数组装成合适的数据模型,并调用相应的业务逻辑进行真正的功能处理,获取下一个视图展示所需要的数据。Struts2的Action,相比于别的web框架的动作处理,它实现了与Servlet API的解耦,使得Action里面不需要再直接去引用和使用HttpServletRequest与HttpServletResponse等接口。因而使得Action的单元测试更加简单,而且强大的类型转换也使得我们少做了很多重复的工作。
  • 视图——Result:视图结果用来把动作中获取到的数据展现给用户。在Struts2中有多种优秀的结果展示方式,常规的jsp,模板freemarker、velocity,还有各种其它专业的展示方式,如图表jfreechart、报表JasperReports、将XML转化为HTML的XSLT等等。而且各种视图结果在同一个工程里面可以混合出现。

4、MVC优点

  • 耦合性低:视图层和业务层分离,这样就允许更改视图层代码而不用重新编译模型和控制器代码,同样,一个应用的业务流程或者业务规则的改变只需要改动MVC的模型层即可。因为模型与控制器和视图相分离,所以很容易改变应用程序的数据层和业务规则;
  • 重用性高:MVC模式允许使用各种不同样式的视图来访问同一个服务器端的代码,因为多个视图能共享一个模型,它包括任何WEB(HTTP)浏览器或者无线浏览器(wap),比如,用户可以通过电脑也可通过手机来订购某样产品,虽然订购的方式不一样,但处理订购产品的方式是一样的。由于模型返回的数据没有进行格式化,所以同样的构件能被不同的界面使用;
  • 部署快,生命周期成本低:MVC使开发和维护用户接口的技术含量降低。使用MVC模式使开发时间得到相当大的缩减,它使程序员(Java开发人员)集中精力于业务逻辑,界面程序员(HTML和JSP开发人员)集中精力于表现形式上;
  • 可维护性高:分离视图层和业务逻辑层也使得WEB应用更易于维护和修改;

5、MVC缺点

  • 完全理解MVC比较复杂:由于MVC模式提出的时间不长,加上同学们的实践经验不足,所以完全理解并掌握MVC不是一个很容易的过程;
  • 调试困难:因为模型和视图要严格的分离,这样也给调试应用程序带来了一定的困难,每个构件在使用之前都需要经过彻底的测试;
  • 不适合小型,中等规模的应用程序:在一个中小型的应用程序中,强制性的使用MVC进行开发,往往会花费大量时间,并且不能体现MVC的优势,同时会使开发变得繁琐;
  • 增加系统结构和实现的复杂性:对于简单的界面,严格遵循MVC,使模型、视图与控制器分离,会增加结构的复杂性,并可能产生过多的更新操作,降低运行效率;
  • 视图与控制器间的过于紧密的连接并且降低了视图对模型数据的访问:视图与控制器是相互分离,但却是联系紧密的部件,视图没有控制器的存在,其应用是很有限的,反之亦然,这样就妨碍了他们的独立重用;依据模型操作接口的不同,视图可能需要多次调用才能获得足够的显示数据。对未变化数据的不必要的频繁访问,也将损害操作性能;

6、具体案例

接下来我们将会演示基于MVC框架的4个不同的示例:

  • 第一个采用Servlet作为控制器;
  • 第二个采用Filter作为控制器;
  • 第三个引入校验器组件来校验用户输入数据的合法性;
  • 第四个采用了一个自制的依赖注入器。在实际的应用中,我们应该使用Spring。

二 MVC案例(Serlvet作为控制器)

创建一个名为appdesign1的Dynamic Web Project项目,Servlet版本选择3.0,其功能设定为输入一个产品信息。具体为:

  • 用户填写产品表单并提交;
  • 保存产品并展示一个完成页面,显示已经保存的产品信息;

示例应用支持如下两个action(每个action对应一个URL):

  • 展示”添加产品“表单,其对应的URL包含字符串input-product;
  • 保存产品并返回完成界面,对应的URL包含字符串save-product;

示例应用由如下组件组成:

  • 一个Product类,作为product的领域对象;
  • 一个ProductForm类,封装了HTML表单的输入项;
  • 一个ControllerServlet,本示例应用的控制器;
  • 一个SaveProdtcuAction类;
  • 两个jsp页面(ProductForm.jsp和ProductDetails.jsp)作为视图;
  • 一个CSS文件,定义了两个jsp页面的显示风格。

示例应用目录结构如下:

注意:由于我们采用的是Servlet3.0版本,web.xml可以不需要,具体可以参考博客Servlet2.5版本和Servlet3.0版本

项目右键属性、部署路径设置如下:

1、Product类

Product类是一个封装了产品信息的JavaBean。Product类包含三个属性:name,description和price:

  1. package appdesign1.model;
  2.  
  3. import java.io.Serializable;
  4. import java.math.BigDecimal;
  5.  
  6. public class Product implements Serializable {
  7.  
  8. private static final long serialVersionUID = 748392348L;
  9. private String name;
  10. private String description;
  11. private BigDecimal price;
  12.  
  13. public String getName() {
  14. return name;
  15. }
  16.  
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20.  
  21. public String getDescription() {
  22. return description;
  23. }
  24.  
  25. public void setDescription(String description) {
  26. this.description = description;
  27. }
  28.  
  29. public BigDecimal getPrice() {
  30. return price;
  31. }
  32.  
  33. public void setPrice(BigDecimal price) {
  34. this.price = price;
  35. }
  36. }

Product类实现了java.io.Serializable接口,其实例可以安全地将数据保存到HttpSession中。根据Serializable的要求,Product类实现了一个serialVersionUID 属性。

2、ProductForm表单类

表单类与HTML表单相对应,是后者在服务器的代表。ProductForm类看上去同Product类相似,这就引出一个问题:ProductForm类是否有存在的必要:

  1. package appdesign1.form;
  2.  
  3. public class ProductForm {
  4. private String name;
  5. private String description;
  6. private String price;
  7.  
  8. public String getName() {
  9. return name;
  10. }
  11. public void setName(String name) {
  12. this.name = name;
  13. }
  14. public String getDescription() {
  15. return description;
  16. }
  17. public void setDescription(String description) {
  18. this.description = description;
  19. }
  20. public String getPrice() {
  21. return price;
  22. }
  23. public void setPrice(String price) {
  24. this.price = price;
  25. }
  26. }

实际上,通过表单对象可以将ServletRequest中的表单信息传递给其它组件,比如校验器Validator(后面会介绍,主要用于检查表单输入数据是否合法)。如果不使用表单对象,则应将ServletRequest传递给其它组件,然而ServletRequest是一个Servlet层的对象,是不应当暴露给应用的其它层。

另一个原因是,当数据校验失败时,表单对象将用于保存和显示用户在原始表单上的输入。

注意:大部分情况下,一个表单类不需要事先Serializable接口,因为表单对象很少保存在HttpSession中。

3、ControllerServlet类

ContrlooerServlet类继承自javax.servlet.http.HttpServlet类。其doGet()和doPost()方法最终调用process()方法,该方法是整个Servlet控制器的核心。

可能有人好奇,为何Servlet控制器命名为ControllerServlet,实际上,这里遵从了一个约定:所有Servlet的类名称都带有Servlet后缀。

  1. package appdesign1.controller;
  2. import java.io.IOException;
  3.  
  4. import javax.servlet.RequestDispatcher;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. import appdesign1.action.SaveProductAction;
  12. import appdesign1.form.ProductForm;
  13. import appdesign1.model.Product;
  14. import java.math.BigDecimal;
  15. //Servlet3.0使用注解指定访问Servlet的URL
  16. @WebServlet(name = "ControllerServlet", urlPatterns = {
  17. "/input-product", "/save-product" })
  18. public class ControllerServlet extends HttpServlet {
  19.  
  20. private static final long serialVersionUID = 1579L;
  21.  
  22. @Override
  23. public void doGet(HttpServletRequest request,
  24. HttpServletResponse response)
  25. throws IOException, ServletException {
  26. process(request, response);
  27. }
  28.  
  29. @Override
  30. public void doPost(HttpServletRequest request,
  31. HttpServletResponse response)
  32. throws IOException, ServletException {
  33. process(request, response);
  34. }
  35.  
  36. private void process(HttpServletRequest request,
  37. HttpServletResponse response)
  38. throws IOException, ServletException {
  39.  
  40. String uri = request.getRequestURI();
  41. /*
  42. * uri is in this form: /contextName/resourceName,
  43. * for example: /appdesign1/input-product.
  44. * However, in the event of a default context, the
  45. * context name is empty, and uri has this form
  46. * /resourceName, e.g.: /input-product
  47. */
  48. int lastIndex = uri.lastIndexOf("/");
  49. String action = uri.substring(lastIndex + 1);
  50.  
  51. // execute an action 根据不同的uri执行不同的action
  52. String dispatchUrl = null;
  53. if ("input-product".equals(action)) {
  54. // no action class, just forward
  55. dispatchUrl = "/jsp/ProductForm.jsp";
  56. } else if ("save-product".equals(action)) {
  57. // create form 创建一个表单对象、保存表单信息
  58. ProductForm productForm = new ProductForm();
  59. // populate action properties
  60. productForm.setName(request.getParameter("name"));
  61. productForm.setDescription(
  62. request.getParameter("description"));
  63. productForm.setPrice(request.getParameter("price"));
  64.  
  65. // create model 创建一个Model类
  66. Product product = new Product();
  67. product.setName(productForm.getName());
  68. product.setDescription(productForm.getDescription());
  69. try {
  70. product.setPrice(new BigDecimal(productForm.getPrice()));
  71. } catch (NumberFormatException e) {
  72. }
  73. // execute action method 保存表单
  74. SaveProductAction saveProductAction =
  75. new SaveProductAction();
  76. saveProductAction.save(product);
  77.  
  78. // store model in a scope variable for the view
  79. request.setAttribute("product", product);
  80. dispatchUrl = "/jsp/ProductDetails.jsp";
  81. }
  82.  
  83. //请求转发
  84. if (dispatchUrl != null) {
  85. RequestDispatcher rd =
  86. request.getRequestDispatcher(dispatchUrl);
  87. rd.forward(request, response);
  88. }
  89. }
  90. }

ControllerServlet的process()方法处理所有输入请求。首先是获取URI和action名称:

  1. String uri = request.getRequestURI();
  2. int lastIndex = uri.lastIndexOf("/");
  3. String action = uri.substring(lastIndex + 1);

在本示例中,action值只会是input-product或sava-product。

接着,当action值为sava-product,process()方法执行如下步骤:

  • 创建并更根据请求参数创建一个ProductForm表单对象。save-product操作涉及3个属性:name,description、price。然后创建一个product对象,并通过表单对象设置相应属性;
  • 执行针对product对象的业务逻辑,保存表单;
  • 转发请求到视图(jsp页面),显示输入的表单信息。

process()方法中判断action的if代码块如下:

  1. if ("input-product".equals(action)) {
  2. // no action class, just forward
  3. dispatchUrl = "/jsp/ProductForm.jsp";
  4. } else if ("save-product".equals(action)) {
  5. ....
  6. }

对于input-product,无需任何操作;而针对save-product,则创建一个ProductForm对象和Product对象,并将前者的属性值复制到后者。

再次,process()方法实例化SavaProductAction类,并调用其save()方法:

  1. // create form 创建一个表单对象、保存表单信息
  2. ProductForm productForm = new ProductForm();
  3. // populate action properties
  4. productForm.setName(request.getParameter("name"));
  5. productForm.setDescription(
  6. request.getParameter("description"));
  7. productForm.setPrice(request.getParameter("price"));
  8.  
  9. // create model 创建一个Model类
  10. Product product = new Product();
  11. product.setName(productForm.getName());
  12. product.setDescription(productForm.getDescription());
  13. try {
  14. product.setPrice(new BigDecimal(productForm.getPrice()));
  15. } catch (NumberFormatException e) {
  16. }
  17. // execute action method 保存表单
  18. SaveProductAction saveProductAction =
  19. new SaveProductAction();
  20. saveProductAction.save(product);

然后,将Product对象放入HttpServletRequest对象中,以便对应的视图可以访问到:

  1. // store model in a scope variable for the view
  2. request.setAttribute("product", product);
  3. dispatchUrl = "/jsp/ProductDetails.jsp";

最后,process()方法转到视图,如果action是input-product,则转到ProductForm.jsp页面,否则转到ProductDetails.jsp页面:

  1. //请求转发
  2. if (dispatchUrl != null) {
  3. RequestDispatcher rd =
  4. request.getRequestDispatcher(dispatchUrl);
  5. rd.forward(request, response);
  6. }

4、Action类

这个应用这有一个action类,负责将一个product对象持久化,例如数据库。这个action类名为SaveProductAction:

  1. package appdesign1.action;
  2.  
  3. import appdesign1.model.Product;
  4.  
  5. public class SaveProductAction {
  6. public void save(Product product) {
  7. // insert Product to the database
  8. }
  9. }

在这个示例中,SaveProductAction类的save()方法是一个空实现。

5、视图

示例应用包含两个jsp页面。第一个页面ProductForm.jsp对应input-product操作,第二个页面ProductDetails.jsp对应sava-product操作。

ProductForm.jsp:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Add Product Form</title>
  5. <style type="text/css">@import url(css/main.css);</style>
  6. </head>
  7. <body>
  8. <form method="post" action="save-product">
  9. <h1>Add Product
  10. <span>Please use this form to enter product details</span>
  11. </h1>
  12. <label>
  13. <span>Product Name :</span>
  14. <input id="name" type="text" name="name"
  15. placeholder="The complete product name"/>
  16. </label>
  17. <label>
  18. <span>Description :</span>
  19. <input id="description" type="text" name="description"
  20. placeholder="Product description"/>
  21. </label>
  22. <label>
  23. <span>Price :</span>
  24. <input id="price" name="price" type="number" step="any"
  25. placeholder="Product price in #.## format"/>
  26. </label>
  27. <label>
  28. <span>&nbsp;</span>
  29. <input type="submit"/>
  30. </label>
  31. </form>
  32. </body>
  33. </html>

注意:不要用HTML table标签来布局表单,使用CSS。

ProductDetails.jsp:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Save Product</title>
  5. <style type="text/css">@import url(css/main.css);</style>
  6. </head>
  7. <body>
  8. <div id="global">
  9. <h4>The product has been saved.</h4>
  10. <p>
  11. <h5>Details:</h5>
  12. Product Name: ${product.name}<br/>
  13. Description: ${product.description}<br/>
  14. Price: $${product.price}
  15. </p>
  16. </div>
  17. </body>
  18. </html>

ProductForm页面包含了一个HTML表单。ProductDetails页面通过EL表达式语言访问HttpServletRequest所包含的product对象。

此外,该实例存在一个问题,即用户可以直接通过浏览器访问这两个jsp页面,我们可以通过以下方式避免这种直接访问:

  • 将jsp页面都放在WEB-INF目录下。WEB-INF目录下的任何文件和子目录都受保护、无法通过浏览器直接访问,但控制器仍然可以转发请求到这些页面;
  • 利用一个servlet filter过滤jsp页面;
  • 在部署描述符中为jsp压面增加安全限制。这种方式相对简单,无需编写filter代码;

main.css:

  1. form {
  2. margin-left:auto;
  3. margin-right:auto;
  4. max-width: 450px;
  5. background: palegreen;
  6. padding: 25px 15px 25px 10px;
  7. border:1px solid #dedede;
  8. font: 12px Arial;
  9. }
  10. h1 {
  11. padding: 20px;
  12. display: block;
  13. border-bottom:1px solid grey;
  14. margin: -20px 0px 20px 0px;
  15. color: mediumpurple;
  16. }
  17. h1>span {
  18. display: block;
  19. font-size: 13px;
  20. }
  21. label {
  22. display: block;
  23. }
  24. label>span {
  25. float: left;
  26. width: 20%;
  27. text-align: right;
  28. margin: 14px;
  29. color: mediumpurple;
  30. font-weight:bold;
  31. }
  32. input[type="text"], input[type="number"] {
  33. border: 1px solid #dedede;
  34. height: 30px;
  35. width: 70%;
  36. font-size: 12px;
  37. border-radius: 3px;
  38. margin: 5px;
  39. }
  40. input[type="submit"] {
  41. background: mediumseagreen;
  42. font-weight: bold;
  43. border: none;
  44. padding: 8px 20px 8px 20px;
  45. color: black;
  46. border-radius: 5px;
  47. cursor: pointer;
  48. margin-left:4px;
  49. }
  50. input[type="submit"]:hover {
  51. background: red;
  52. color: yellow;
  53. }

6、测试应用

将项目部署到tomcat服务器,然后启动服务器,假设示例应用运行在本机的8000端口上,则可以通过如下URL访问应用:

  1. http://localhost:8008/appdesign1/input-product

完成表单输入后,表单提交到如下服务器URL上:

  1. http://localhost:8008/appdesign1/save-product

三 MVC案例(Filter作为控制器)

虽然Servlet是MVC框架中最常见的控制器,但是过滤器也可以充当控制器。Struts2就是使用过滤器作为控制器,是因为该过滤波器也可用于提供静态页面。

Filter是在Servlet 2.3之后增加的新功能,当需要限制用户访问某些资源或者在处理请求时提前处理某些资源的时候,就可以使用过滤器完成。
过滤器是以一种组件的形式绑定到WEB应用程序当中的,与其他的WEB应用程序组件不同的是,过滤器是采用了“链”的方式进行处理的。
在Servlet中,如果要定义一个过滤器,则直接让一个类实现javax.servlet.Filter接口即可,此接口定义了三个操作方法:
    1. public void init(FilterConfig filterConfig) throws ServletException
    1. public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException
    1. public void destroy();
FilterChain接口的主要作用是将用户的请求向下传递给其他的过滤器或者是Servlet:
    1. public void doFilter(ServletRequest request,ServletResponse response) throws IOException,ServletException
在FilterChain接口中依然定义了一个同样的doFilter()方法,这是因为在一个过滤器后面可能存在着另外一个过滤器,也可能是请求的最终目标(Servlet),这样就通过FilterChain形成了一个“过滤链”的操作,所谓的过滤链就类似于生活中玩的击鼓传花游戏 。

注意:过滤器没有作为欢迎页面(即仅仅在浏览器地址栏中输入域名)的权限,仅输入域名时不会调用过滤器分派器。

下面我们采用一个名为FilterDispactcher的过滤器替代appdesign1项目中的Servlet控制器,项目命名为appdesign2,目录结构如下:

  1. package appdesign2.filter;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.RequestDispatcher;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.ServletRequest;
  9. import javax.servlet.ServletResponse;
  10. import javax.servlet.annotation.WebFilter;
  11. import javax.servlet.http.HttpServletRequest;
  12.  
  13. import appdesign2.action.SaveProductAction;
  14. import appdesign2.form.ProductForm;
  15. import appdesign2.model.Product;
  16. import java.math.BigDecimal;
  17.  
  18. //Servlet3.0新增了注解的特性,指定过滤器的访问URL
  19. @WebFilter(filterName = "DispatcherFilter",
  20. urlPatterns = { "/*" })
  21. public class DispatcherFilter implements Filter {
  22.  
  23. //过滤器初始化
  24. @Override
  25. public void init(FilterConfig filterConfig)
  26. throws ServletException {
  27. }
  28.  
  29. //过滤器销毁
  30. @Override
  31. public void destroy() {
  32. System.out.println("** 过滤器销毁。");
  33. }
  34.  
  35. //执行过滤操作
  36. @Override
  37. public void doFilter(ServletRequest request,
  38. ServletResponse response, FilterChain filterChain)
  39. throws IOException, ServletException {
  40. System.out.println("** 执行doFilter()方法之前。");
  41.  
  42. HttpServletRequest req = (HttpServletRequest) request;
  43. String uri = req.getRequestURI();
  44. /*
  45. * uri is in this form: /contextName/resourceName, for
  46. * example /appdesign2/input-product. However, in the
  47. * case of a default context, the context name is empty,
  48. * and uri has this form /resourceName, e.g.:
  49. * /input-product
  50. */
  51. // action processing
  52. int lastIndex = uri.lastIndexOf("/");
  53. String action = uri.substring(lastIndex + 1);
  54. String dispatchUrl = null;
  55. if ("input-product".equals(action)) {
  56. // do nothing
  57. dispatchUrl = "/jsp/ProductForm.jsp";
  58. } else if ("save-product".equals(action)) {
  59. // create form
  60. ProductForm productForm = new ProductForm();
  61. // populate action properties
  62. productForm.setName(request.getParameter("name"));
  63. productForm.setDescription(
  64. request.getParameter("description"));
  65. productForm.setPrice(request.getParameter("price"));
  66.  
  67. // create model
  68. Product product = new Product();
  69. product.setName(productForm.getName());
  70. product.setDescription(product.getDescription());
  71. try {
  72. product.setPrice(new BigDecimal(productForm.getPrice()));
  73. } catch (NumberFormatException e) {
  74. }
  75. // execute action method
  76. SaveProductAction saveProductAction =
  77. new SaveProductAction();
  78. saveProductAction.save(product);
  79.  
  80. // store model in a scope variable for the view
  81. request.setAttribute("product", product);
  82. dispatchUrl = "/jsp/ProductDetails.jsp";
  83. }
  84. // forward to a view
  85. if (dispatchUrl != null) {
  86. RequestDispatcher rd = request
  87. .getRequestDispatcher(dispatchUrl);
  88. rd.forward(request, response);
  89. } else {
  90. // let static contents pass
  91. filterChain.doFilter(request, response);
  92. }
  93. System.out.println("** 执行doFilter()方法之后。");
  94. }
  95. }

doFilter()方法的内容同appdesign1中的process()方法。

由于过滤器的过滤目标是包括静态内容在内的所有网址,因此,若没有相应的action,则需要调用filterChain.doFilter();

  1. else {
  2. // let static contents pass
  3. filterChain.doFilter(request, response);
  4. }

要测试应用,将项目配置到tomcat服务器,启动服务器,并在浏览器输入如下URL:

  1. http://localhost:8008/appdesign2/input-product

四 表单输入校验器

在Web应用执行action时,很重要的一个步骤就是进行输入校验。检验的内容可以是简单的,如检查一个输入是否为空,也可以是复杂的,如检验信用卡号。实际上,因为校验工作如此重要,Java社区专门发布了JSR 303 Bean Validation以及JSR 349 Bean Validation 1.1版本,将Java世界的输入校验进行标准化。现代的MVC框架通常同时支持编程式和声明式两种校验方式。在编程式中,需要通过编码进行用户输入校验;而在声明式中,则需要提供包含校验规则的XML文档或者属性文件。

注意:即使您可以使用HTML5或JavaScript执行客户端输入校验,也不要依赖它,因为精明的用户可以轻松地绕过它。始终执行服务器端输入验证!

本节的新应用(appdesign3)扩展自appdesign1,但是多了一个ProductValidator类:

1、ProductValidator类

  1. package appdesign3.validator;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import appdesign3.form.ProductForm;
  5.  
  6. //对表单进行输入校验
  7. public class ProductValidator {
  8.  
  9. public List<String> validate(ProductForm productForm) {
  10. List<String> errors = new ArrayList<>();
  11. //商品名不能为空
  12. String name = productForm.getName();
  13. if (name == null || name.trim().isEmpty()) {
  14. errors.add("Product must have a name");
  15. }
  16. //商品价格不能为空、也不能是非法数字
  17. String price = productForm.getPrice();
  18. if (price == null || price.trim().isEmpty()) {
  19. errors.add("Product must have a price");
  20. } else {
  21. try {
  22. Float.parseFloat(price);
  23. } catch (NumberFormatException e) {
  24. errors.add("Invalid price value");
  25. }
  26. }
  27. return errors;
  28. }
  29. }

注意:ProductValidator类中有一个操作ProductForm对象的validate()方法,确保产品的名字非空,其价格是一个合理的数字。validate()方法返回一个包含错误信息的字符串列表,若返回一个空列表,则表示输入合法。

现在需要让控制器使用这个校验器了,ControllerServlet代码如下:

  1. package appdesign3.controller;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.RequestDispatcher;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import appdesign3.action.SaveProductAction;
  11. import appdesign3.form.ProductForm;
  12. import appdesign3.model.Product;
  13. import appdesign3.validator.ProductValidator;
  14. import java.math.BigDecimal;
  15.  
  16. //Servlet3.0使用注解指定访问Servlet的URL
  17. @WebServlet(name = "ControllerServlet", urlPatterns = {
  18. "/input-product", "/save-product" })
  19. public class ControllerServlet extends HttpServlet {
  20.  
  21. private static final long serialVersionUID = 98279L;
  22.  
  23. @Override
  24. public void doGet(HttpServletRequest request,
  25. HttpServletResponse response)
  26. throws IOException, ServletException {
  27. process(request, response);
  28. }
  29.  
  30. @Override
  31. public void doPost(HttpServletRequest request,
  32. HttpServletResponse response)
  33. throws IOException, ServletException {
  34. process(request, response);
  35. }
  36.  
  37. private void process(HttpServletRequest request,
  38. HttpServletResponse response)
  39. throws IOException, ServletException {
  40.  
  41. String uri = request.getRequestURI();
  42. /*
  43. * uri is in this form: /contextName/resourceName,
  44. * for example: /appdesign1/input-product.
  45. * However, in the case of a default context, the
  46. * context name is empty, and uri has this form
  47. * /resourceName, e.g.: /input-product
  48. */
  49. int lastIndex = uri.lastIndexOf("/");
  50. String action = uri.substring(lastIndex + 1);
  51.  
  52. // execute an action 根据不同的uri执行不同的action
  53. String dispatchUrl = null;
  54. if ("input-product".equals(action)) {
  55. // no action class, there is nothing to be done
  56. dispatchUrl = "/jsp/ProductForm.jsp";
  57. } else if ("save-product".equals(action)) {
  58. // instantiate action class 创建一个表单对象、保存表单信息
  59. ProductForm productForm = new ProductForm();
  60. // populate action properties
  61. productForm.setName(
  62. request.getParameter("name"));
  63. productForm.setDescription(
  64. request.getParameter("description"));
  65. productForm.setPrice(request.getParameter("price"));
  66.  
  67. // validate ProductForm 表单输入校验
  68. ProductValidator productValidator = new
  69. ProductValidator();
  70. List<String> errors =
  71. productValidator.validate(productForm);
  72. if (errors.isEmpty()) { //表单输入正确
  73. // create Product from ProductForm 创建一个Model类
  74. Product product = new Product();
  75. product.setName(productForm.getName());
  76. product.setDescription(
  77. productForm.getDescription());
  78. product.setPrice(new BigDecimal(productForm.getPrice()));
  79.  
  80. // no validation error, execute action method 保存表单
  81. SaveProductAction saveProductAction = new
  82. SaveProductAction();
  83. saveProductAction.save(product);
  84.  
  85. // store action in a scope variable for the view
  86. request.setAttribute("product", product);
  87. dispatchUrl = "/jsp/ProductDetails.jsp";
  88. } else { //表单输入有误,重新加载该页面
  89. request.setAttribute("errors", errors);
  90. request.setAttribute("form", productForm);
  91. dispatchUrl = "/jsp/ProductForm.jsp";
  92. }
  93. }
  94.  
  95. // forward to a view 请求转发
  96. if (dispatchUrl != null) {
  97. RequestDispatcher rd =
  98. request.getRequestDispatcher(dispatchUrl);
  99. rd.forward(request, response);
  100. }
  101. }
  102. }

新版的ControllerServlet类添加了初始化ProductValidator类,并调用了validate()方法的代码:

  1. // validate ProductForm 表单输入校验
  2. ProductValidator productValidator = new
  3. ProductValidator();
  4. List<String> errors =
  5. productValidator.validate(productForm);

validate()方法接受一个ProductForm参数,它分装了输入到HTML表单的产品信息。如果不用ProductForm,则应将ServletRequest传递给校验器。

如果校验成功,validate()方法返回一个空列表,在这种情况下,将创建一个产品并传递给SaveProductAction,然后,控制器将Product对象存储在ServletRequest中,并转发到ProductDetails.jsp页面,显示产品的详细信息。如果校验失败,控制器将错误列表和ProductForm对象存储在ServletRequest中,并返回到ProductForm.jsp中。

  1. if (errors.isEmpty()) { //表单输入正确
  2. // create Product from ProductForm 创建一个Model类
  3. Product product = new Product();
  4. product.setName(productForm.getName());
  5. product.setDescription(
  6. productForm.getDescription());
  7. product.setPrice(new BigDecimal(productForm.getPrice()));
  8.  
  9. // no validation error, execute action method 保存表单
  10. SaveProductAction saveProductAction = new
  11. SaveProductAction();
  12. saveProductAction.save(product);
  13.  
  14. // store action in a scope variable for the view
  15. request.setAttribute("product", product);
  16. dispatchUrl = "/jsp/ProductDetails.jsp";
  17. } else { //表单输入有误,重新加载该页面
  18. request.setAttribute("errors", errors);
  19. request.setAttribute("form", productForm);
  20. dispatchUrl = "/jsp/ProductForm.jsp";
  21. }
  22. }

2、ProductForm.jsp

现在,需要修改appdesign3应用的ProductForm.jsp页面,使其可以显示错误信息以及错误的输入:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Add Product Form</title>
  5. <style type="text/css">@import url(css/main.css);</style>
  6. </head>
  7. <body>
  8. <form method="post" action="save-product">
  9. <h1>Add Product
  10. <span>Please use this form to enter product details</span>
  11. </h1>
  12. ${empty requestScope.errors? "" : "<p id='errors'>"
  13. += "Error(s)!"
  14. += "<ul>"}
  15. <!--${requestScope.errors.stream().map(
  16. x -> "--><li>"+=x+="</li><!--").toList()}-->
  17. ${empty requestScope.errors? "" : "</ul></p>"}
  18. <label>
  19. <span>Product Name :</span>
  20. <input id="name" type="text" name="name"
  21. placeholder="The complete product name"
  22. value="${form.name}"/>
  23. </label>
  24. <label>
  25. <span>Description :</span>
  26. <input id="description" type="text" name="description"
  27. placeholder="Product description"
  28. value="${form.description}"/>
  29. </label>
  30. <label>
  31. <span>Price :</span>
  32. <input id="price" name="price" type="number" step="any"
  33. placeholder="Product price in #.## format"
  34. value="${form.price}"/>
  35. </label>
  36. <label>
  37. <span>&nbsp;</span>
  38. <input type="submit"/>
  39. </label>
  40. </form>
  41. </body>
  42. </html>

3、测试应用

将项目配置到tomcat服务器,启动服务器,并在浏览器输入如下URL:

  1. http://localhost:8008/appdesign3/input-product

若产品表单提交了无效数据,页面将显示错误信息,如下:

五 自制的依赖注入

什么是依赖注入技术?如果不了解的话,可以参考博客:Spring MVC -- Spring框架入门(IoC和DI)

示例appdesign4使用了一个自制的依赖注入器。在实际的应用中,我们应该使用Spring。该示例用来生成pdf。它有两个action:

  • form:没有action类,只是将请求转发到用来输入一些文本的表单;
  • pdf:生成pdf文件并使用PDFAction类,PDFAction类依赖于PDFService类;

该应用的目录结构如下:

1、PDFAction类和PDFService

PDFAction类:

  1. package action;
  2.  
  3. import service.PDFService;
  4.  
  5. public class PDFAction {
  6. private PDFService pdfService;
  7. public void setPDFService(PDFService pdfService) {
  8. this.pdfService = pdfService;
  9. }
  10. public void createPDF(String path, String input) {
  11. pdfService.createPDF(path, input);
  12. }
  13. }

PDFService类:

  1. package service;
  2.  
  3. import util.PDFUtil;
  4.  
  5. public class PDFService {
  6. public void createPDF(String path, String input) {
  7. PDFUtil.createDocument(path, input);
  8. }
  9. }

PDFService使用了PDFUtil类,PDFUtil最终采用了apache pdfbox库来创建pdf文档,如果对创建pdf的具体代码有兴趣,可以进一步查看PDFUtil类。

  1. package util;
  2.  
  3. import org.apache.pdfbox.pdmodel.PDDocument;
  4. import org.apache.pdfbox.pdmodel.PDPage;
  5. import org.apache.pdfbox.pdmodel.common.PDRectangle;
  6. import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
  7. import org.apache.pdfbox.pdmodel.font.PDFont;
  8. import org.apache.pdfbox.pdmodel.font.PDType1Font;
  9.  
  10. public class PDFUtil {
  11. public static void createDocument(String path, String input) {
  12. PDDocument doc = null;
  13. try {
  14. doc = new PDDocument();
  15. PDFont font = PDType1Font.HELVETICA;
  16. PDPage page = new PDPage();
  17. doc.addPage(page);
  18. float fontSize = 12.0f;
  19.  
  20. PDRectangle pageSize = page.getMediaBox();
  21. float centeredXPosition = (pageSize.getWidth() - fontSize
  22. / 1000f) / 2f;
  23. float stringWidth = font.getStringWidth(input);
  24.  
  25. PDPageContentStream contentStream = new PDPageContentStream(doc, page);
  26. contentStream.setFont(font, fontSize);
  27. contentStream.beginText();
  28. contentStream.moveTextPositionByAmount(centeredXPosition, 600);
  29. contentStream.drawString(input);
  30. contentStream.endText();
  31. contentStream.close();
  32. doc.save(path);
  33. doc.close();
  34. } catch (Exception ex) {
  35. ex.printStackTrace();
  36. }
  37. }
  38. }

这里的关键在于,PDFAction需要一个PDFService来完成它的工作,换句话说,PDFAction依赖于PDFService。没有依赖注入,你必须在PDFAction类中实例化PDFService类,这将使PDFAction更不可测试。除此之外,如果需要更改PDFService的实现,必须重新编译PDFAction。

使用依赖注入,每个组件都有注入它的依赖项,这使得测试每个组件更容易。对于在依赖注入环境中的类,必须使其支持注入。一种方法是为每个依赖关系创建一个set方法。例如,PDFAction类有一个setPDFService方法,可以调用它来传递PDFService。注入也可以通过构造方法或者类属性进行。

一旦所有的类都支持注入,则可以选择一个依赖注入框架并将其导入项目。比如Spring框架、Google Guice、Weld和PicoContainer是一些好的选择。

2、DependencyInjector类

appdesign4应用使用DependencyInjector类来代替依赖注入框架(在实际应用中,我们应该使用一个合适的框架)。这个类专为appdesign4应用设计,利用Java的反射机制来实现(不懂的可以参考博客:Java基础 -- 深入理解Java类型信息(Class对象)与反射机制),可以容易的实例化。一旦实例化,必须调用其start()方法来执行初始哈,使用后,应调其shutdown()方法来释放资源。在此示例中,start()和shutdown()都没有实现。

  1. package util;
  2.  
  3. import action.PDFAction;
  4. import service.PDFService;
  5.  
  6. public class DependencyInjector {
  7.  
  8. public void start() {
  9. // initialization code
  10. }
  11.  
  12. public void shutDown() {
  13. // clean-up code
  14. }
  15.  
  16. /*
  17. * Returns an instance of type. type is of type Class
  18. * and not String because it's easy to misspell a class name
  19. */
  20. public Object getObject(Class type) {
  21. if (type == PDFService.class) {
  22. return new PDFService();
  23. } else if (type == PDFAction.class) {
  24. PDFService pdfService = (PDFService)
  25. getObject(PDFService.class);
  26. PDFAction action = new PDFAction();
  27. action.setPDFService(pdfService);
  28. return action;
  29. }
  30. return null;
  31. }
  32. }

要从DependencyInjector获取对象,需要调用其getObject()方法,并传递目标类对应的Class对象,DependencyInjector支持两种类型,即PDFAction和PDFService。例如,要获取PDFAction实例,你可以通过传递PDFAction.class来调用getObject():

  1. PDFAction pdfAction = (PDFAction) dependencyInjector
  2. .getObject(PDFAction.class);

DependencyInjector(和所有依赖注入框架)的优雅之处在于它返回的对象注入了依赖。如果返回的对象所依赖的对象也有依赖,则所依赖的对象也会注入其自身的依赖。例如,从DependencyInjector获取的PDFAction已包含PDFService。无需在PDFAction类中自己创建PDFService。

3、ControllerServlet

appdesign4应用的Servlet控制器如下所示。请注意:在其init()方法中实例化DependencyInjector,并在其destroy()方法中调用DependencyInjector的shutdown()方法。Servlet不再创建它自身的依赖项,相反,它从DependencyInjector获取这些依赖。

  1. package servlet;
  2.  
  3. import action.PDFAction;
  4. import java.io.IOException;
  5. import javax.servlet.ReadListener;
  6. import javax.servlet.RequestDispatcher;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;
  13. import util.DependencyInjector;
  14.  
  15. //Servlet3.0使用注解指定访问Servlet的URL
  16. @WebServlet(name = "ControllerServlet", urlPatterns = {
  17. "/form", "/pdf"})
  18. public class ControllerServlet extends HttpServlet {
  19. private static final long serialVersionUID = 6679L;
  20. private DependencyInjector dependencyInjector;
  21.  
  22. @Override
  23. public void init() {
  24. //实例化DependencyInjector
  25. dependencyInjector = new DependencyInjector();
  26. dependencyInjector.start();
  27. }
  28.  
  29. @Override
  30. public void destroy() {
  31. //关闭DependencyInjector实例
  32. dependencyInjector.shutDown();
  33. }
  34. protected void process(HttpServletRequest request,
  35. HttpServletResponse response)
  36. throws ServletException, IOException {
  37. ReadListener r = null;
  38. String uri = request.getRequestURI();
  39. /*
  40. * uri is in this form: /contextName/resourceName,
  41. * for example: /app10a/product_input.
  42. * However, in the case of a default context, the
  43. * context name is empty, and uri has this form
  44. * /resourceName, e.g.: /product_input
  45. */
  46. int lastIndex = uri.lastIndexOf("/");
  47. String action = uri.substring(lastIndex + 1);
  48.  
  49. if ("form".equals(action)) {
  50. String dispatchUrl = "/jsp/Form.jsp";
  51. RequestDispatcher rd =
  52. request.getRequestDispatcher(dispatchUrl);
  53. rd.forward(request, response);
  54. } else if ("pdf".equals(action)) {
  55. //创建pdf文档
  56. HttpSession session = request.getSession(true);
  57. String sessionId = session.getId();
  58. //利用dependencyInjector创建PDFAction对象
  59. PDFAction pdfAction = (PDFAction) dependencyInjector
  60. .getObject(PDFAction.class);
  61. String text = request.getParameter("text");
  62. //设置pdf在磁盘上文件路径E:\tomcat\wtpwebapps\appdesign4\result\sessionId.pdf
  63. String path = request.getServletContext()
  64. .getRealPath("/result/") + sessionId + ".pdf";
  65. //System.out.println(path);
  66. //生成pdf文件,保存在path路径下
  67. pdfAction.createPDF(path, text);
  68.  
  69. // redirect to the new pdf
  70. StringBuilder redirect = new
  71. StringBuilder();
  72. redirect.append(request.getScheme() + "://"); // http://
  73. redirect.append("localhost"); // http://localhost
  74. int port = request.getLocalPort();
  75. if (port != 80) {
  76. redirect.append(":" + port); // http://localhost:8008
  77. }
  78. String contextPath = request.getContextPath(); // /appdesign4
  79. if (!"/".equals(contextPath)) {
  80. redirect.append(contextPath); // http://localhost:8008/appdesign4
  81. }
  82. redirect.append("/result/" + sessionId + ".pdf");
  83. //System.out.println(redirect.toString());
  84. response.sendRedirect(redirect.toString());
  85. }
  86. }
  87.  
  88. @Override
  89. protected void doGet(HttpServletRequest request,
  90. HttpServletResponse response)
  91. throws ServletException, IOException {
  92. process(request, response);
  93. }
  94.  
  95. @Override
  96. protected void doPost(HttpServletRequest request,
  97. HttpServletResponse response)
  98. throws ServletException, IOException {
  99. process(request, response);
  100. }
  101.  
  102. }

Servlet控制器支持两种URL模式:

  • form:对于表单模式,Servlet控制器将请求转发到表单/jsp/Form.jsp;
  • pdf:对于pdf模式,Servlet控制器使用DependencyInjector创建PDFAction对象,并调用其createDocument()方法生成pdf文档,保存在当前项目的result文件夹下。此方法有两个参数:文件保存在磁盘上的路径和文本输入。所有PDF存储在应用项目目录下的result文件夹中,用户的会话标识符用做文件名,而文本输入作为pdf文件的内容;最后,重定向到生成的pdf文件,以下是创建重定向URL并将浏览器重定向到新URL的代码:
    1. // redirect to the new pdf
    2. StringBuilder redirect = new
    3. StringBuilder();
    4. redirect.append(request.getScheme() + "://"); // http://
    5. redirect.append("localhost"); // http://localhost
    6. int port = request.getLocalPort();
    7. if (port != 80) {
    8. redirect.append(":" + port); // http://localhost:8008
    9. }
    10. String contextPath = request.getContextPath(); // /appdesign4
    11. if (!"/".equals(contextPath)) {
    12. redirect.append(contextPath); // http://localhost:8008/appdesign4
    13. }
    14. redirect.append("/result/" + sessionId + ".pdf");
    15. //System.out.println(redirect.toString());
    16. response.sendRedirect(redirect.toString());

4、PDFActionTest和PdfBoxTest

该应用提供了两个测试类PDFActionTest和PdfBoxTest,由于依赖注入器,appdesign4中的每个组件都可以独立测试,比如可以运行PDFActionTest类来测试类的createDocument()方法。

PDFActionTest类:

  1. package test;
  2.  
  3. import action.PDFAction;
  4. import util.DependencyInjector;
  5.  
  6. public class PDFActionTest {
  7. public static void main(String[] args) {
  8. //创建DependencyInjector对象
  9. DependencyInjector dependencyInjector = new DependencyInjector();
  10. dependencyInjector.start();
  11. //利用DependencyInjector创建PDFAction对象
  12. PDFAction pdfAction = (PDFAction) dependencyInjector.getObject(
  13. PDFAction.class);
  14. //生成pdf文档
  15. pdfAction.createPDF("E:/tomcat/wtpwebapps/appdesign4/result/1.pdf",
  16. "Testing PDFAction....");
  17. dependencyInjector.shutDown();
  18. }
  19. }

输出如下:

PdfBoxTest类:

  1. package test;
  2. import util.PDFUtil;
  3.  
  4. public class PdfBoxTest {
  5. public static void main(String[] args) {
  6. PDFUtil.createDocument("E:/tomcat/wtpwebapps/appdesign4/result/2.pdf",
  7. "Tod late");
  8. }
  9. }

输出如下:

5、视图

Form.jsp:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Add Product Form</title>
  5. <style type="text/css">@import url(css/main.css);</style>
  6. </head>
  7. <body>
  8. <form method="post" action="pdf">
  9. <h1>Create PDF
  10. <span>Please use this form to enter the text</span>
  11. </h1>
  12. <label>
  13. <span>Text :</span>
  14. <input type="text" name="text"
  15. placeholder="Text for PDF"/>
  16. </label>
  17. <label>
  18. <span>&nbsp;</span>
  19. <input type="submit"/>
  20. </label>
  21. </form>
  22. </body>
  23. </html>

main.css:

  1. form {
  2. margin-left:auto;
  3. margin-right:auto;
  4. max-width: 450px;
  5. background: palegreen;
  6. padding: 25px 15px 25px 10px;
  7. border:1px solid #dedede;
  8. font: 12px Arial;
  9. }
  10. h1 {
  11. padding: 20px;
  12. display: block;
  13. border-bottom:1px solid grey;
  14. margin: -20px 0px 20px 0px;
  15. color: mediumpurple;
  16. }
  17. h1>span {
  18. display: block;
  19. font-size: 13px;
  20. }
  21. label {
  22. display: block;
  23. }
  24. label>span {
  25. float: left;
  26. width: 20%;
  27. text-align: right;
  28. margin: 14px;
  29. color: mediumpurple;
  30. font-weight:bold;
  31. }
  32. input[type="text"], input[type="number"] {
  33. border: 1px solid #dedede;
  34. height: 30px;
  35. width: 70%;
  36. font-size: 12px;
  37. border-radius: 3px;
  38. margin: 5px;
  39. }
  40. input[type="submit"] {
  41. background: mediumseagreen;
  42. font-weight: bold;
  43. border: none;
  44. padding: 8px 20px 8px 20px;
  45. color: black;
  46. border-radius: 5px;
  47. cursor: pointer;
  48. margin-left:4px;
  49. }
  50. input[type="submit"]:hover {
  51. background: red;
  52. color: yellow;
  53. }

6、应用测试

将项目配置到tomcat服务器,启动服务器,并在浏览器输入如下URL来测试应用:

  1. http://localhost:8008/appdesign4/form

应用将展示一个表单:

如果在文本字段中输入一些内容并按提交按钮,服务器将创建一个pdf文件并发送重定向到浏览器:

请注意:重定向网址将采用此格式:

  1. http://localhost:8008/appdesign4/result/sessionId.pdf

参考文章

[1]MVC简介(部分转载)

[2]Spring MVC 学习总结(一)——MVC概要与环境配置(IDea与Eclipse示例)(推荐)

[3]Spring MVC 学习总结(三)——请求处理方法Action详解

[4]Spring MVC学习指南

[5]java基础篇---Servlet过滤器

Spring MVC -- MVC设计模式(演示4个基于MVC框架的案例)的更多相关文章

  1. 基于MVC设计模式的Web应用框架:struts2的简单搭建(一)

    Struts2的初步介绍 Struts2是apache项目下的一个web 框架,普遍应用于阿里巴巴.京东等互联网.政府.企业门户网站.虽然之前存在了很大的安全漏洞,在2013年让苹果.中国移动.中国联 ...

  2. iOS 基于MVC设计模式的基类设计

    iOS 基于MVC设计模式的基类设计 https://www.jianshu.com/p/3b580ffdae00

  3. Struts2是一个基于MVC设计模式的Web应用框架

    Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互. Struts ...

  4. ASP.NET Core 6框架揭秘实例演示[02]:基于路由、MVC和gRPC的应用开发

    ASP.NET Core可以视为一种底层框架,它为我们构建出了基于管道的请求处理模型,这个管道由一个服务器和多个中间件构成,而与路由相关的EndpointRoutingMiddleware和Endpo ...

  5. iOS中MVC等设计模式详解

    iOS中MVC等设计模式详解 在iOS编程,利用设计模式可以大大提高你的开发效率,虽然在编写代码之初你需要花费较大时间把各种业务逻辑封装起来.(事实证明这是值得的!) 模型-视图-控制器(MVC)设计 ...

  6. MVC的设计模式在JavaWeb中的实现

    JSP开发模式 jsp开发模式的发展 1.模式1:(适合小型项目的技术的开发)     a.第一版本号,纯jsp(封装数据.处理数据,显示数据)     b.第二版本号,Jsp+JavaBean.   ...

  7. 【Unity】基于MVC模式的背包系统 UGUI实现

    前言 本文基于MVC模式,用UGUI初步实现了背包系统. Control层包括了点击和拖拽两种逻辑. 博文首发:http://blog.csdn.net/duzixi 下载地址:https://git ...

  8. 服务器文档下载zip格式 SQL Server SQL分页查询 C#过滤html标签 EF 延时加载与死锁 在JS方法中返回多个值的三种方法(转载) IEnumerable,ICollection,IList接口问题 不吹不擂,你想要的Python面试都在这里了【315+道题】 基于mvc三层架构和ajax技术实现最简单的文件上传 事件管理

    服务器文档下载zip格式   刚好这次项目中遇到了这个东西,就来弄一下,挺简单的,但是前台调用的时候弄错了,浪费了大半天的时间,本人也是菜鸟一枚.开始吧.(MVC的) @using Rattan.Co ...

  9. iOS 基于 MVC 的项目重构总结

    关于MVC的争论 关于MVC的争论已经有非常多,对此我的观点是:对于iOS开发中的绝大部分场景来说,MVC本身是没有问题的,你觉得的MVC的问题,一定是你自己理解的问题(资深架构师请自己主动忽略本文) ...

随机推荐

  1. 原生ajax解析&封装原生ajax函数

    前沿:对于此篇随笔,完是简要写了几个重要的地方,具体实现细节完在提供的源码做了笔记 <一>ajax基本要点介绍--更好的介绍ajax 1. ajax对象中new XMLHttpReques ...

  2. Reprint: CMake or Make

    CMake vs Make https://prateekvjoshi.com/2014/02/01/cmake-vs-make/ Programmers have been using CMake ...

  3. Codeforces H. Malek Dance Club(找规律)

    题目描述: Malek Dance Club time limit per test 1 second memory limit per test 256 megabytes input standa ...

  4. Celery(异步任务,定时任务,周期任务)

    1.什么是Celery Celery是基于Python实现的模块,用于异步.定时.周期任务的. 组成结构: 1.用户任务 app 2.管道broker 用于存储任务 官方推荐 redis/rabbit ...

  5. Python语言程序设计(3)--字符串类型及操作--time库进度条

    1.字符串类型的表示: 三引号可做注释,注释其实也是字符串 2.字符串的操作符 3.字符串处理函数 输出:

  6. CentOS7.6 yum方式安装redis最新版

    sudo yum install -y http://rpms.famillecollet.com/enterprise/remi-release-7.rpm sudo yum --enablerep ...

  7. 002——keil-Error: L6915E: Library reports error: __use_no_semihosting was requested解决

    ..\OBJ\KEY.axf: Error: L6915E: Library reports error: __use_no_semihosting was requested, but _ttywr ...

  8. codeforces1276A As Simple as One and Two

    C.As Simple as One and Two A. As Simple as One and Two time limit per test 3 seconds memory limit pe ...

  9. 防火墙firewalld

    增加外部可访问的端口 启动: systemctl start firewalld 查看状态: systemctl status firewalld 停止: systemctl stop firewal ...

  10. 开源项目 08 IOC Autofac

    using Autofac; using System; using System.Collections.Generic; using System.Linq; using System.Text; ...