搭建SpringMVC框架web
1.添加jar包spring
jsp-api.jar
servlet-api.jar
jstl.jar
commons-logging-1.1.1.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jarexpress
2.定義Controller和建立JSP頁面api
Controller須要實現Controller接口mvc
/** * 自定義的Controller須要實現Controller接口 * */ public class HelloController implements Controller{ @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { //調用類來進行處理 System.out.println("-----hello controller-------"); //建立一個ModelAndView對象 該對象最後被視圖渲染器渲染爲指定視圖 ModelAndView mv = new ModelAndView(); //設置視圖名稱 ----最後解析爲指定的頁面 mv.setViewName("hello"); //添加結果數據 該數據能夠在頁面中經過el表達式獲取 mv.addObject("msg", "first spring mvc app"); return mv; } }
3.配置app
須要配置HandlerMapping映射器和HandlerAdapter適配器和Conteroller,還需配置視圖渲染器
框架
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置handlerMapper 映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- 配置Controller 自定義控制器 --> <bean name="/hello.do" class="cn.sxt.controller.HelloController"/> <!-- 配置handerAdapter 適配器 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- 配置視圖渲染器 --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!-- 將視圖名 渲染後視圖的前綴 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 渲染後視圖的後綴 --> <property name="suffix" value=".jsp"/> <!-- 例:視圖名爲:hello 渲染後:/WEB-INF/jsp/hello.jsp 該頁面--> </bean> </beans>
4.代碼結構jsp
5.配置項目訪問路徑ide
6.啓動Tomcat訪問http://localhost:8080/hello/hello.dospa
first spring mvc app