首页 技术 正文
技术 2022年11月15日
0 收藏 788 点赞 4,818 浏览 7789 个字

现 在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理下载地址  

  一、Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0)

  1. jar包引入

  Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar

 
 Hibernate
3.6.8:hibernate3.jar、hibernate-jpa-2.0-api-1.0.1.Final.jar、antlr-
2.7.6.jar、commons-collections-3.1、dom4j-1.6.1.jar、javassist-
3.12.0.GA.jar、jta-1.1.jar、slf4j-api-1.6.1.jar、slf4j-nop-1.6.4.jar、相应数据库的
驱动jar包

  2. web.xml配置(部分)

  1. <!– Spring MVC配置 –>
  2. <!– ====================================== –>
  3. <servlet>
  4. <servlet-name>spring</servlet-name>
  5. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  6. <!– 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
  7. <init-param>
  8. <param-name>contextConfigLocation</param-name>
  9. <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
  10. </init-param>
  11. –>
  12. </load-on-startup>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>spring</servlet-name>
  16. <url-pattern>*.do</url-pattern>
  17. </servlet-mapping>
  18. <!– Spring配置 –>
  19. <!– ====================================== –>
  20. <listener>
  21. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  22. </listener>
  23. <!– 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 –>
  24. <context-param>
  25. <param-name>contextConfigLocation</param-name>
  26. <param-value>classpath:config/applicationContext.xml</param-value>
  27. </context-param>

  3. spring-servlet.xml配置

 
 spring-servlet这个名字是因为上面web.xml中<servlet-name>标签配的值为
spring(<servlet-name>spring</servlet-name>),再加上“-servlet”后缀而
形成的spring-servlet.xml文件名,如果改为springMVC,对应的文件名则为springMVC-servlet.xml。

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3. xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:p=”http://www.springframework.org/schema/p”
  4. xmlns:context=”http://www.springframework.org/schema/context”
  5. xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  7. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  8. http://www.springframework.org/schema/context <a href=”http://www.springframework.org/schema/context/spring-context-3.0.xsd”>http://www.springframework.org/schema/context/spring-context-3.0.xsd</a>”>
  9. <!– 启用spring mvc 注解 –>
  10. <context:annotation-config />
  11. <!– 设置使用注解的类所在的jar包 –>
  12. <context:component-scan base-package=”controller”></context:component-scan>
  13. <!– 完成请求和注解POJO的映射 –>
  14. <bean class=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter” />
  15. <!– 对转向页面的路径解析。prefix:前缀, suffix:后缀 –>
  16. <bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver” p:prefix=”/jsp/” p:suffix=”.jsp” />
  17. </beans>

  4. applicationContext.xml配置下载地址

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3. xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  4. xmlns:aop=”http://www.springframework.org/schema/aop”
  5. xmlns:tx=”http://www.springframework.org/schema/tx”
  6. xsi:schemaLocation=”
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd”>
  10. <!– 采用hibernate.cfg.xml方式配置数据源 –>
  11. <bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
  12. <property name=”configLocation”>
  13. <value>classpath:config/hibernate.cfg.xml</value>
  14. </property>
  15. </bean>
  16. <!– 将事务与Hibernate关联 –>
  17. <bean id=”transactionManager” class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
  18. <property name=”sessionFactory”>
  19. <ref local=”sessionFactory”/>
  20. </property>
  21. </bean>
  22. <!– 事务(注解 )–>
  23. <tx:annotation-driven transaction-manager=”transactionManager” proxy-target-class=”true”/>
  24. <!– 测试Service –>
  25. <bean id=”loginService” class=”service.LoginService”></bean>
  26. <!– 测试Dao –>
  27. <bean id=”hibernateDao” class=”dao.HibernateDao”>
  28. <property name=”sessionFactory” ref=”sessionFactory”></property>
  29. </bean>
  30. </beans>

  二、详解

  Spring MVC与Struts从原理上很相似(都是基于MVC架构),都有一个控制页面请求的Servlet,处理完后跳转页面。看如下代码(注解)下载地址   :

  1. package controller;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import entity.User;
  7. @Controller  //类似Struts的Action
  8. public class TestController {
  9. @RequestMapping(“test/login.do”)  // 请求url地址映射,类似Struts的action-mapping
  10. public String testLogin(@RequestParam(value=”username”)String username, String password, HttpServletRequest request) {
  11. // @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)
  12. // @RequestParam可简写为:@RequestParam(“username”)
  13. if (!”admin”.equals(username) || !”admin”.equals(password)) {
  14. return “loginError”; // 跳转页面路径(默认为转发),该路径不需要包含spring-servlet配置文件中配置的前缀和后缀
  15. }
  16. return “loginSuccess”;
  17. }
  18. @RequestMapping(“/test/login2.do”)
  19. public ModelAndView testLogin2(String username, String password, int age){
  20. // request和response不必非要出现在方法中,如果用不上的话可以去掉
  21. // 参数的名称是与页面控件的name相匹配,参数类型会自动被转换
  22. ) {
  23. return new ModelAndView(“loginError”); // 手动实例化ModelAndView完成跳转页面(转发),效果等同于上面的方法返回字符串
  24. }
  25. return new ModelAndView(new RedirectView(“../index.jsp”));  // 采用重定向方式跳转页面
  26. // 重定向还有一种简单写法
  27. // return new ModelAndView(“redirect:../index.jsp”);
  28. }
  29. @RequestMapping(“/test/login3.do”)
  30. public ModelAndView testLogin3(User user) {
  31. // 同样支持参数为表单对象,类似于Struts的ActionForm,User不需要任何配置,直接写即可
  32. String username = user.getUsername();
  33. String password = user.getPassword();
  34. int age = user.getAge();
  35. ) {
  36. return new ModelAndView(“loginError”);
  37. }
  38. return new ModelAndView(“loginSuccess”);
  39. }
  40. @Resource(name = “loginService”)  // 获取applicationContext.xml中bean的id为loginService的,并注入
  41. private LoginService loginService;  //等价于spring传统注入方式写get和set方法,这样的好处是简洁工整,省去了不必要得代码
  42. @RequestMapping(“/test/login4.do”)
  43. public String testLogin4(User user) {
  44. if (loginService.login(user) == false) {
  45. return “loginError”;
  46. }
  47. return “loginSuccess”;
  48. }
  49. }

  以上4个方法示例,是一个Controller里含有不同的请求url,也可以采用一个url访问,通过url参数来区分访问不同的方法,代码下载地址   如下:

  1. package controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. @Controller
  6. @RequestMapping(“/test2/login.do”)  // 指定唯一一个*.do请求关联到该Controller
  7. public class TestController2 {
  8. @RequestMapping
  9. public String testLogin(String username, String password, int age) {
  10. // 如果不加任何参数,则在请求/test2/login.do时,便默认执行该方法
  11. ) {
  12. return “loginError”;
  13. }
  14. return “loginSuccess”;
  15. }
  16. @RequestMapping(params = “method=1”, method=RequestMethod.POST)
  17. public String testLogin2(String username, String password) {
  18. // 依据params的参数method的值来区分不同的调用方法
  19. // 可以指定页面请求方式的类型,默认为get请求
  20. if (!”admin”.equals(username) || !”admin”.equals(password)) {
  21. return “loginError”;
  22. }
  23. return “loginSuccess”;
  24. }
  25. @RequestMapping(params = “method=2”)
  26. public String testLogin3(String username, String password, int age) {
  27. ) {
  28. return “loginError”;
  29. }
  30. return “loginSuccess”;
  31. }
  32. }

  其实RequestMapping在Class上,可看做是父Request请求url,而RequestMapping在方法上的可看做是子Request请求url下载地址   ,父子请求url最终会拼起来与页面请求url进行匹配,因此RequestMapping也可以这么写:

  1. package controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. @Controller
  5. @RequestMapping(“/test3/*”)  // 父request请求url
  6. public class TestController3 {
  7. @RequestMapping(“login.do”)  // 子request请求url,拼接后等价于/test3/login.do
  8. public String testLogin(String username, String password, int age) {
  9. ) {
  10. return “loginError”;
  11. }
  12. return “loginSuccess”;
  13. }
  14. }

  三、结束语

 
 掌握以上这些Spring
MVC就已经有了很好的基础了,几乎可应对与任何开发,在熟练掌握这些后,便可更深层次的灵活运用的技术,如多种视图技术,例如
Jsp、Velocity、Tiles、iText 和 POI。Spring MVC框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,405
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898