近期 项目中刚接触了SpringMVC,就把这几天看的跟实践的东西写出来吧。
一、首先,先来了解一下SpringMVC究竟是个什么样的框架?
Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想。将web层进行职责解耦。基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发。
二、SpringMVC的工作原理:
1. client请求提交到DispatcherServlet
2. 由DispatcherServlet控制器查询一个或多个HandlerMapping,找到处理请求的Controller
3. DispatcherServlet将请求提交到Controller
4. Controller调用业务逻辑处理后。返回ModelAndView
5. DispatcherServlet查询一个或多个ViewResoler视图解析器,找到ModelAndView指定的视图
6. 视图负责将结果显示到客户端
三、了解了springmvc的工作原理之后,我们自己动手来搭建一下吧:
1. 在创建好的mavenproject上增加springmvc所依赖的jar包:
<span style="white-space:pre"> </span><dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.8.RELEASE</version> </dependency>
2. 配置web.xml,配置前段控制器DispatcherServlet
<span style="white-space:pre"> </span><servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3. 在web-inf 下创建springmvc配置文件。[servletname]-servlet.xml
如上面的配置,文件名称必须为dispatcher -servlet.xml
<!-- 默认的注解映射的支持 --> <mvc:annotation-driven/> <!-- 自己主动扫描的包名 --> <context:component-scan base-package="com.acxiom"/> <!-- 对静态资源文件的訪问 --> <mvc:resources location="/resources/" mapping="/resources/**" /> <!-- spring MVC为@Controllers分发请求 --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 视图解释类 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value=""></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 从请求和响应读取/编写字符串 --> <bean id="stringHttpMessage" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean>
4. 配置HandlerMapping 依据benaname找到相应Conntroller( 能够省略)
<bean class="org.springframework.web.servlet.mvc.support.ControllerBeanNameHandlerMapping"></bean>
5. 创建JSP页面,须要发出请求的页面
6. 创建自己的Controller继承AbstractController重写handleRequestInternal
在这里,我们着重来学习下页面參数的传递与接收。
Controller中传递请求參数:
1)第一种 通过request对象 或者 session对象
@RequestMapping(value="/add1.do") public String add(HttpServletRequest request){ String userNumber = request.getParameter("userNumber"); String passWord = request.getParameter("passWord"); System.out.println("userNumber:"+userNumber+" passWord:"+passWord); return "user_add1"; }
2)另外一种 參数字段跟页面字段一致
<span style="white-space:pre"> </span>@RequestMapping(value="/add2.do") public String add(String userNumber,Integer passWord){ System.out.println("<span style="font-family: Arial, Helvetica, sans-serif;">userNumber</span>:"+userNumber+" passWord:"+passWord); return "user_add2"; }这样的方式假设页面字段跟參数字段不一致的话。能够通过@RequestParam 设置别名,如页面字段为number,实际使用參数为userNumber,见以下代码:
<span style="white-space:pre"> </span>@RequestMapping(value="/add2.do") public String add(@RequestParam(value="number")String userNumber,Integer passWord){ System.out.println("userNumber:"+userNumber+" passWord:"+passWord); return "user_add2"; }
3)第三种 通过对象方式,要求表单字段要跟pojo类字段一致,假设页面有复选框,pojo类中定义数组。
@RequestMapping(value="/add3.do") public String add3(UserInfo user){ System.out.println(user); return "user_add3"; }跟strut2的差别在于 假设是strut2在页面要使用类似于user.userId,可是spring不须要,加了反而会取不到值。
返回数据到页面:
1)第一种 通过request对象setAttribute 。也能够使用session对象
@RequestMapping(value="/add1.do") public String add(HttpServletRequest request){ String userNumber = request.getParameter("userNumber"); String passWord = request.getParameter("passWord"); System.out.println("userNumber:"+userNumber+" passWord:"+passWord); String str = "userNumber:"+userNumber+" passWord:"+passWord; request.setAttribute("user", str); return "user_add1"; }
2)另外一种 ModelAndView
@RequestMapping(value="/add2.do") public ModelAndView add2(){ ModelAndView mav = new ModelAndView("user_add2"); mav.addObject("userId", 1001); mav.addObject("userName", "张三"); return mav; }
3)第三种 通过Model对象
@RequestMapping(value="/add3.do") public String add3(Model model){ model.addAttribute("personId", 9527); model.addAttribute("personName", "唐伯虎"); return "user_add3"; }
4)第四种 通过map
@RequestMapping(value="/add4.do") public String add4(Integer personId,String userName,Map map){ System.out.println(personId); System.out.println(userName); map.put("personId", 9527); map.put("personName", "唐伯虎"); return "user_add4"; }FAQ: 假设要返回一个json对象怎么实现呢?
首先在springmvc-servlet.xml中配置:
<!-- 用于将对象转化为JSON --> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringHttpMessage"/> <ref bean="jsonConverter"/> </list> </property> </bean>
然后在controller中注入ResponseBody讲返回对象作为json返回到页面
@RequestMapping("/ajaxUser2.do") public @ResponseBody UserInfo ajaxUser(Integer userId){ System.out.println("编号:"+userId); UserInfo user = new UserInfo(); user.setUserId(userId); user.setUserName("张三"); user.setUserAge(18); return user; }