下面的例子說(shuō)明了如何使用 Spring MVC 框架來(lái)編寫(xiě)一個(gè)簡(jiǎn)單的基于 web 的應(yīng)用程序,它可以處理它的內(nèi)置控制器產(chǎn)生的一個(gè)或多個(gè)異常。為了開(kāi)始使用它,讓我們?cè)谇‘?dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來(lái)開(kāi)發(fā)一個(gè)動(dòng)態(tài)的基于表單的 Web 應(yīng)用程序:
步驟 | 描述 |
---|---|
1 | 創(chuàng)建一個(gè)名稱(chēng)為 HelloWeb 的動(dòng)態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的 src 文件夾中創(chuàng)建一個(gè)包 com.tutorialspoint。 |
2 | 將上面提到的 Spring 和其他庫(kù)拖拽到文件夾 WebContent/WEB-INF/lib 中。 |
3 | 在 com.tutorialspoint 包下創(chuàng)建一個(gè) Java 類(lèi) Student,StudentController 和 SpringException。 |
4 | 在 WebContent/WEB-INF 文件夾下創(chuàng)建 Spring 的配置文件 Web.xml 和 HelloWeb-servlet.xml。 |
5 | 在 WebContent/WEB-INF 文件夾下創(chuàng)建名稱(chēng)為 jsp 的子文件夾。在這個(gè)子文件夾下創(chuàng)建視圖文件 student.jsp,result.jsp,error.jsp 和 ExceptionPage.jsp。 |
6 | 最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。 |
這里是 Student.java 文件的內(nèi)容:
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
下面是 SpringException.java 文件的內(nèi)容:
package com.tutorialspoint;
public class SpringException extends RuntimeException{
private String exceptionMsg;
public SpringException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg(){
return this.exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
下面是 StudentController.java 文件的內(nèi)容。這里,你需要使用 @ExceptionHandler 注解一個(gè) service 方法,你可以指定要處理的一個(gè)或多個(gè)異常。如果你要指定一個(gè)以上的異常,那么你可以使用逗號(hào)分隔這些值。
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
@ExceptionHandler({SpringException.class})
public String addStudent( @ModelAttribute("HelloWeb")Student student,
ModelMap model) {
if(student.getName().length() < 5 ){
throw new SpringException("Given name is too short");
}else{
model.addAttribute("name", student.getName());
}
if( student.getAge() < 10 ){
throw new SpringException("Given age is too low");
}else{
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}
下面是 Spring Web 配置文件 web.xml 的內(nèi)容
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring Exception Handling</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
下面是另一個(gè) Spring Web 配置文件 HelloWeb-servlet.xml 的內(nèi)容
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.tutorialspoint" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <bean class="org.springframework.web.servlet.handler. SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="com.tutorialspoint.SpringException"> ExceptionPage </prop> </props> </property> <property name="defaultErrorView" value="error"/> </bean> </beans>
在這里,你指定 ExceptionPage 作為一個(gè)異常視圖,以便 SpringException 發(fā)生,如果有任何其他類(lèi)型的異常發(fā)生,那么一個(gè)通用的視圖 error 會(huì)發(fā)生。
下面是 Spring 視圖文件 student.jsp 的內(nèi)容:
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring MVC Exception Handling</title> </head> <body> <h2>Student Information</h2> <form:form method="POST" action="/HelloWeb/addStudent"> <table> <tr> <td><form:label path="name">Name</form:label></td> <td><form:input path="name" /></td> </tr> <tr> <td><form:label path="age">Age</form:label></td> <td><form:input path="age" /></td> </tr> <tr> <td><form:label path="id">id</form:label></td> <td><form:input path="id" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Submit"/> </td> </tr> </table> </form:form> </body> </html>
下面是 Spring 視圖文件 error.jsp 的內(nèi)容:
<html> <head> <title>Spring Error Page</title> </head> <body> <p>An error occured, please contact webmaster.</p> </body> </html>;
下面是 Spring 視圖文件 ExceptionPage.jsp 的內(nèi)容。在這里,你將通過(guò) ${exception} 訪問(wèn)異常實(shí)例。
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring MVC Exception Handling</title> </head> <body> <h2>Spring MVC Exception Handling</h2> <h3>${exception.exceptionMsg}</h3> </body> </html>
下面是 Spring 視圖文件 result.jsp 的內(nèi)容:
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted Student Information</h2> <table> <tr> <td>Name</td> <td>${name}</td> </tr> <tr> <td>Age</td> <td>${age}</td> </tr> <tr> <td>ID</td> <td>${id}</td> </tr> </table> </body> </html>
最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫(kù)的列表。你僅僅需要將這些文件拖拽到 WebContent/WEB-INF/lib 文件夾中。
commons-logging-x.y.z.jar
org.springframework.asm-x.y.z.jar
org.springframework.beans-x.y.z.jar
org.springframework.context-x.y.z.jar
org.springframework.core-x.y.z.jar
org.springframework.expression-x.y.z.jar
org.springframework.web.servlet-x.y.z.jar
org.springframework.web-x.y.z.jar
一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用 Export > WAR File 選項(xiàng),并且在 Tomcat 的 webapps 文件夾中保存你的 HelloWeb.war 文件。
現(xiàn)在啟動(dòng)你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問(wèn) webapps 文件夾中的其他 web 頁(yè)面?,F(xiàn)在嘗試訪問(wèn)該 URL http://localhost:8080/SpringWeb/student。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:
輸入如上圖所示的值,然后單擊提交按鈕。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果: