實例詳解SpringMVC入門使用
MVC模式(Model-View-Controller)是軟件工程中的一種軟件架構模式,把軟件系統(tǒng)分為三個基本部分:模型(Model),視圖(View)和控制器(Controller).通過分層使開發(fā)的軟件結構更清晰,從而達到開發(fā)效率的提高,可維護性和擴展性得到提高.Spring提供的MVC框架是在J2EE Web開發(fā)中對MVC模式的一個實現(xiàn),本文通過實例講解一下Spring MVC 的使用.
先來看一個HTTP request在Spring的MVC框架是怎么被處理的:(圖片來源于Spring in Action)

1,DispatcherServlet是Spring MVC的核心,它的本質是一個實現(xiàn)了J2EE標準中定義的HttpServlet,通過在web.xml配置<servlet-mapping>,來實現(xiàn)對request的監(jiān)聽.
<servlet> <servlet-name>springTestServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springTestServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
** 以.do結尾的request都會由springTestServlet來處理.
2,3,當接受到request的時候,DispatcherServlet根據(jù)HandlerMapping的配置(HandlerMapping的配置文件默認根據(jù)<servlet-name>的值來決定,這里會讀取springTestServlet-servlet.xml來獲得HandlerMapping的配置信息),調用相應的Controller來對request進行業(yè)務處理.
<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/login.do">loginController</prop> </props> </property> </bean> <bean id="loginController" class="com.test.spring.mvc.contoller.LoginController"> <property name="sessionForm"> <value>true</value> </property> <property name="commandName"> <value>loginCommand</value> </property> <property name="commandClass"> <value>com.test.spring.mvc.commands.LoginCommand</value> </property> <property name="authenticationService"> <ref bean="authenticationService"/> </property> <property name="formView"> <value>login</value> </property> <property name="successView"> <value>loginDetail</value> </property> </bean>
** 以login.do結尾的request由loginController來處理.<property name="formView">配置的是Controller接收到HTTP GET請求的時候需要顯示的邏輯視圖名,本例是顯示login.jsp,<property name="successView">配置的是在接收到HTTP POST請求的時候需要顯示的邏輯視圖名,在本例中即login.jsp提交的時候需要顯示名為loginDetail的邏輯視圖.
4,Controller進行業(yè)務處理之后,返回一個ModelAndView對象.
return new ModelAndView(getSuccessView(),"loginDetail",loginDetail);
5,6,DispatcherServlet根據(jù)ViewResolver的配置(本例是在springTestServlet-servlet.xml文件中配置)將邏輯view轉換到真正要顯示的View,如JSP等.
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"> <value>/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean>
**其作用是將Controller中返回的ModleAndView解析到具體的資源(JSP文件),如上例中的return new ModelAndView(getSuccessView();按照上面ViewResolver配置,會解析成/jsp/loginDetail.jsp.規(guī)則為prefix+ModelAndView的第二個參數(shù)+suffix.
示例的完整代碼如下:
1web.xml:
<?xml version="1.0" encoding="UTF-8"?> <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> prjSpring3</display-name> <servlet> <servlet-name>springTestServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springTestServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springTest-services.xml</param-value> </context-param> <jsp-config> <taglib> <taglib-uri>/spring</taglib-uri> <taglib-location>/WEB-INF/spring.tld</taglib-location> </taglib> </jsp-config> </web-app>
2,springTestServlet-servlet.xml的內容如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/login.do">loginController</prop> </props> </property> </bean> <bean id="loginController" class="com.test.spring.mvc.contoller.LoginController"> <property name="sessionForm"> <value>true</value> </property> <property name="commandName"> <value>loginCommand</value> </property> <property name="commandClass"> <value>com.test.spring.mvc.commands.LoginCommand</value> </property> <property name="authenticationService"> <ref bean="authenticationService"/> </property> <property name="formView"> <value>login</value> </property> <property name="successView"> <value>loginDetail</value> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"> <value>/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3,springTest-services.xml的內容:
<bean id="authenticationService" class="com.test.spring.mvc.services.AuthenticationService"/>
4,Java代碼:
public class LoginController extends SimpleFormController {
org.springframework.web.servlet.DispatcherServlet t;
protected ModelAndView onSubmit(Object command) throws Exception{
LoginCommand loginCommand = (LoginCommand) command;
authenticationService.authenticate(loginCommand);
LoginDetail loginDetail = authenticationService.getLoginDetail(loginCommand.getUserId());
return new ModelAndView(getSuccessView(),"loginDetail",loginDetail);
}
private AuthenticationService authenticationService;
public AuthenticationService getAuthenticationService() {
return authenticationService;
}
public void setAuthenticationService(
AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
....
public class LoginCommand {
private String userId;
private String password;
....
public class LoginDetail {
private String userName;
public class AuthenticationService {
public void authenticate(LoginCommand command) throws Exception{
if(command.getUserId()!= null && command.getUserId().equalsIgnoreCase("test")
&& command.getPassword()!= null && command.getPassword().equalsIgnoreCase("test")){
}else{
throw new Exception("User id is not authenticated");
}
}
public LoginDetail getLoginDetail(String userId){
return new LoginDetail(userId);
}
}
5,JSP文件:放在web-inf的jsp文件夾內
login.jsp:
<html><head>
<title>Login to Spring Test</title></head>
<body>
<h1>Please enter your userid and password.</h1>
<form method="post" action="login.do">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td alignment="right" width="20%">User id:</td>
<td width="20%"><input type="text" name="userId" value="test"></td>
<td width="60%">
</tr>
<tr>
<td alignment="right" width="20%">Password:</td>
<td width="20%"><input type="password" name="password" value="test"></td>
<td width="60%">
</tr>
</table>
<br>
<input type="submit" alignment="center" value="login">
</form>
</body>
</html>
loginDetail.jsp:
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<html><head>
<title>Login to Spring Test</title></head>
<body>
<h1>Login Details:</h1>
<br/>
Login as: <c:out value ="${loginDetail.userName}"/>
<br/>
<a href="/S3/login.do" rel="external nofollow" >logout</a>
</body>
</html>
在瀏覽器的地址欄輸入http://localhost:8080/XXX/login.do進入login.jsp頁面.
對配置的一些擴充點:
1為HandlerMapping和Controller的配置指定文件名稱.
<servlet>
<servlet-name>springTestServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/xxx.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
2,加入對MVC注解的支持:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.test.spring.mvc.contoller" />
<mvc:annotation-driven />
@Controller
public class AnnotationController {
@RequestMapping("annotation.do")
protected void test(HttpServletRequest request,
HttpServletResponse response) throws Exception{
response.getWriter().println("test Spring MVC annotation");
}
3,注解和SimpleFormController同時使用需要在DispatcherServlet對應的servlet配置文件(本例是springTestServlet-servlet.xml)里面配置:
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> 否則會發(fā)生下面的異常: javax.servlet.ServletException: No adapter for handler [com.test.spring.mvc.contoller.LoginController@6ac615]: Does your handler implement a supported interface like Controller? org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:982) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:770) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
在WEB應用中的context配置文件通過下面的方式load,ContextLoaderListener是一個實現(xiàn)了ServletContextListener的listener,
它能夠訪問<context-param>而得到配置文件的路徑,加載后初始化了一個WebApplicationContext,并且將其作為Attribute放在了servletContext中,
所有可以訪問servletContext的地方則可以訪問WebApplicationContext.
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/springTest-services.xml, classpath:conf/jndiDSAppcontext.xml </param-value> </context-param>
到此這篇關于實例詳解SpringMVC入門使用的文章就介紹到這了,更多相關SpringMVC詳解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java對數(shù)組實現(xiàn)選擇排序算法的實例詳解
這篇文章主要介紹了Java對數(shù)組實現(xiàn)選擇排序算法的實例,選擇排序的比較次數(shù)為 O(N^2)而交換數(shù)為O(N),需要的朋友可以參考下2016-04-04
解決出現(xiàn) java.lang.ExceptionInInitializerError錯誤問題
這篇文章主要介紹了解決出現(xiàn) java.lang.ExceptionInInitializerError錯誤問題的相關資料,需要的朋友可以參考下2017-01-01
springBoot整合shiro如何解決讀取不到@value值問題
這篇文章主要介紹了springBoot整合shiro如何解決讀取不到@value值問題,具有很好的參考價值,希望對大家有所幫助,2023-08-08
深入解析Java的Spring框架中的混合事務與bean的區(qū)分
這篇文章主要介紹了Java的Spring框架中的混合事務與bean的區(qū)分,Spring是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2016-01-01
dockerfile-maven-plugin極簡教程(推薦)
這篇文章主要介紹了dockerfile-maven-plugin極簡教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
SpringBoot中MybatisX插件的簡單使用教程(圖文)
MybatisX 是一款基于 IDEA 的快速開發(fā)插件,方便在使用mybatis以及mybatis-plus開始時簡化繁瑣的重復操作,本文主要介紹了SpringBoot中MybatisX插件的簡單使用教程,感興趣的可以了解一下2023-06-06

