簡易的springmvc入門程式-springmvc架構的搭建

來源:互聯網
上載者:User

註:springmvc的註解方式從3.1開始需要在tomcat7上運行,tomcat7以下的版本會不支援此種方式,出現檔案找不到的異常。

第一步:配置web.xml

 <!-- 配置springmvc 前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation參數配置的是springmvc載入時的設定檔(配置處理器、映射器、適配器等) 如果不配置contextConfigLocation,預設載入的是/WEB-INF/servelt名稱-serlvet.xml(springmvc-servlet.xml)  --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet>  <servlet-mapping> <servlet-name>springmvc</servlet-name> <!--  第一種:*.action:所有訪問的以.action結尾 的地址 交 由DispatcherServlet進行解析 第二種:/:所有訪問的地址都由DispatcherServlet進行解析,對於靜態檔案的解析,需要配置,不讓DispatcherServlet進行解析 使用此種方式可以實現RESTful風格的url 第三種:/*:這樣配置不對,使用這種配置,最終要轉寄到一個jsp頁面時,仍然會由DispatcherServlet解析jsp地址,不能根據jsp頁面找到handler,會報錯  --> <url-pattern>*.action</url-pattern> </servlet-mapping>
第二步:編輯springmvc.xml檔案,有關springmvc的配置,都在此檔案中 ,包括前端控制器(DispatcherServlet)的配置、處理器適配器(HandlerAdapter)的配置、處理器映射器(HandlerMapping)的配置以及視圖解析器(ViewResolver)的配置等

<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"<span style="background-color: rgb(255, 255, 102);">xmlns:mvc="http://www.springframework.org/schema/mvc"</span>xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd"><!-- 配置Handler --><bean id="itermsController1" name="/queryItems.action" class="com.sky.ssm.controller.ItermsController1" /><!-- 配置Handler2 --><bean id="itermsController2" class="com.sky.ssm.controller.ItermsController2" /><!-- 配置註解的Handler --><!-- 對於註解的Handler可以單個配置 實際開發中,建議使用組件掃描 --><!--  <bean class="com.sky.ssm.controller.ItermsControllerAnnotation1"/> --> <!-- context:component-scan可以掃描controller、service、... ...  這裡讓其掃描controller,指定controller的包 --> <context:component-scan base-package="com.sky.ssm.controller"></context:component-scan><!-- 配置    處理器映射器 所有的處理器映射器都實現了HandlerMapping介面 --><!-- 多個處理器映射器可以並存,前端控制器 判斷url能讓哪個映射器映射,就讓哪個正取的映射器處理--><!-- a:非註解的 --><!-- 此handlerMapping將bean的name作為url進行尋找Handler,因此需要在配置Handler時指定beanname(就是url) --><bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/><!-- 簡單url映射 --><bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><!-- 此handlerMapping對 id為itermsController1的bean進行url映射,url是queryItems1.action --><prop key="/queryItems1.action">itermsController1</prop><prop key="/queryItems2.action">itermsController1</prop><prop key="/queryItems3.action">itermsController2</prop></props></property></bean><!-- b:註解的 --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/><!-- mvc的註解驅動 --><!-- 使用mvc:annotation-driven代替註解的處理器映射器和處理器適配器的配置 mvc:annotation-driven會預設載入很多的參數綁定的方法。  比如json轉換解析器就預設載入了,如果使用mvc:annotation-driven進行配置,就不用配置RequestMappingHandlerMapping和RequestMappingHandlerAdapter  在實際開發中 使用mvc:annotation-driven進行註解的配置 --><!-- <mvc:annotation-driven></mvc:annotation-driven> --><!-- 配置    處理器適配器 所有的處理器適配器都實現HandlerAdapter介面多個適配器可以並存--><!-- a:非註解的 --><!-- 此Adapter要求編寫的handler需要實現Controller介面 --><bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/><!-- 此Adapter要求編寫的handler實現HttpRequestHandler介面--><bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/><!-- b:註解的 --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/><!-- 配置視圖解析器 解析jsp視圖,預設使用jstl標籤,要求classpath下要有jstl的包--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean></beans>
第三步:根據配置編寫響應的視圖和handler

1、設定檔中的幾個handler的編寫

ItermsController1.java

/** * 非註解的Handler開發 * 實現controller介面的處理器 * @author sk * */public class ItermsController1 implements Controller{public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {//調用service尋找資料庫,查詢商品列表,這裡使用待用資料類比List<Items> itemList = new ArrayList<Items>();Items item1 = new Items();item1.setName("聯想筆記本1");item1.setPrice(5000f);item1.setDetail("thinkpad t430聯想膝上型電腦。");Items item2 = new Items();item2.setName("聯想筆記本2");item2.setPrice(5000f);item2.setDetail("thinkpad t430聯想膝上型電腦。");Items item3 = new Items();item3.setName("聯想筆記本3");item3.setPrice(5000f);item3.setDetail("thinkpad t430聯想膝上型電腦。");itemList.add(item1);itemList.add(item2);itemList.add(item3);//返回ModelAndViewModelAndView modelAndView = new ModelAndView();//相當於request的setAttribute,在jsp頁面中通過itemList擷取資料modelAndView.addObject("itemList",itemList );//指定視圖modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");return modelAndView;}}
ItermsController2.java
<pre name="code" class="java">/** * 非註解的Handler開發 * 實現HttpRequestHandler介面的處理器 * @author sk * 通過此種方法可以通過修改response,設定響應的資料格式,比如返回json資料 * response.setCharacterEncoding("utf-8"); *  response.setContentType("application/json;charset=utf-8"); *  response.getWriter().write("json串"); */public class ItermsController2 implements HttpRequestHandler{public void handleRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//調用service尋找資料庫,查詢商品列表,這裡使用待用資料類比List<Items> itemList = new ArrayList<Items>();Items item1 = new Items();item1.setName("聯想筆記本1");item1.setPrice(5000f);item1.setDetail("thinkpad t430聯想膝上型電腦。");Items item2 = new Items();item2.setName("聯想筆記本2");item2.setPrice(5000f);item2.setDetail("thinkpad t430聯想膝上型電腦。");Items item3 = new Items();item3.setName("聯想筆記本3");item3.setPrice(5000f);item3.setDetail("thinkpad t430聯想膝上型電腦。");itemList.add(item1);itemList.add(item2);itemList.add(item3);//設定模型資料request.setAttribute("itemList",itemList);//設定轉寄的視圖request.getRequestDispatcher("/WEB-INF/jsp/items/itemsList.jsp").forward(request, response);}}



<pre name="code" class="java">ItermsControllerAnnotation1.java
/** * 使用註解方式開發Handler * 注意:使用註解的處理器適配器一定要使用註解的處理器映射器,即註解的映射器和適配器需要同時使用 *///使用@Controller標識它是一個控制器@Controllerpublic class ItermsControllerAnnotation1 {//查詢商品列表的方法//@RequestMapping實現對queryItemsAnnotation方法和url進行映射,一個方法對應一個url//一般建議將url和方法名寫成一樣@RequestMapping("/queryItemsAnnotation")public ModelAndView queryItemsAnnotation(){//調用service尋找資料庫,查詢商品列表,這裡使用待用資料類比List<Items> itemList = new ArrayList<Items>();Items item1 = new Items();item1.setName("聯想筆記本1");item1.setPrice(5000f);item1.setDetail("thinkpad t430聯想膝上型電腦。");Items item2 = new Items();item2.setName("聯想筆記本2");item2.setPrice(5000f);item2.setDetail("thinkpad t430聯想膝上型電腦。");Items item3 = new Items();item3.setName("聯想筆記本3");item3.setPrice(5000f);item3.setDetail("thinkpad t430聯想膝上型電腦。");itemList.add(item1);itemList.add(item2);itemList.add(item3);//返回ModelAndViewModelAndView modelAndView = new ModelAndView();//相當於request的setAttribute,在jsp頁面中通過itemList擷取資料modelAndView.addObject("itemList",itemList );//指定視圖modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");return modelAndView;}}


 2、視圖的編寫 

itemsList.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>商品列表</title></head><body><form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">查詢條件:<table width="100%;" border="1"><tr><td><input type="submit" value="查詢"/></td></tr></table>商品列表:<table width="100%;" border="1"><tr><td>商品名稱</td><td>商品價格</td><td>生產日期</td><td>商品描述</td><td>操作</td></tr><c:forEach items="${itemList }" var="item"><tr><td>${item.name }</td><td>${item.price }</td><td><fmt:formatDate value="${item.createtime }" pattern="yyyy-MM-dd HH:mm:ss" /></td><td>${item.detail }</td><td><a href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td></tr></c:forEach></table></form></body></html>

至此,springmvc中註解的和非註解方式的基本配置已經清楚了。下面是項目的結構目錄


因為springmvc為spring架構中的一部分,因此jar包用spring中的jar包就可以了,再加上jstl.jar和commons-logging.jar

部署到tomcat7之後,通過訪問http://localhost:8080/FristSpringmvcProjects/queryItems.action   或者 http://localhost:8080/FristSpringmvcProjects/queryItems1.action  或者 http://localhost:8080/FristSpringmvcProjects/queryItems2.action  或者  http://localhost:8080/FristSpringmvcProjects/queryItemsAnnotation.action url就可以了,其中前3個連結測試的是非註解的配置,最後一個連結 測試的是 註解的配置


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.