首页 > 代码库 > SpringMVC轻松学习-环境搭建(二)

SpringMVC轻松学习-环境搭建(二)

基于spring2.5的采用XML配置的spring MVC项目

注:本项目全部基于XML配置。同时,集成了hibernate。采用的是:spring MVC+hibernate+spring的开发架构。

1.      建立web项目

2.      导入jar(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包为hibernate相关jar)

上面是SpringMVC的所有包,我将这些jar包放在了我的百度云盘中,当然你也可以去百度搜索,下面就是正文了。。。。

?下面我们先配置web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">>
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/hib-config.xml,/WEB-INF/web-config.xml,/WEB-INF/service-config.xml,/WEB-INF/dao-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

配置说明:

  • 核心控制器为org.springframework.web.servlet.DispatcherServlet
  • 然后就是控制的是*.do的进行过滤,这些和Struts2的其实是一样的。
  • 然后就是<init-param>里面的是Spring的配置文件
  • <load-on-startup>项目被加载的时候就启动他的初始化方法
  • 这里的配置文件web-config.xml其实和struts2-config.xml一样的作用

下面介绍web-config.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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-2.5.xsd">
     
    <!-- Controller方法调用规则定义 -->
    <bean id="paraMethodResolver"
        class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="paramName" value="action"/>
        <property name="defaultMethodName" value="list"/>
    </bean>
   
   <!-- 页面View层基本信息设定 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"/>
        <!--<property name="prefix" value="http://www.mamicode.com/myjsp/"/>-->
        <property name="suffix" value=".jsp"/>
    </bean>
 
<!-- servlet映射列表,所有控制层Controller的servlet在这里定义 -->
    <bean id="urlMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="user.do">userController</prop>
            </props>
        </property>
    </bean>
 
<bean id="userController" class="com.sxt.action.UserController">
    <property name="userService" ref="userService"></property>
</bean>
</beans>

view层:包括前缀和后缀,其中后缀是说,我们返回一个如a,则后面就直接是.jsp,直接给你配置a.jsp;前缀的话,如返回的是a,则默认给你添加一个前缀为/myjsp/a.jsp,这些都是默认的







之后是service-config.xml,主要是配置业务逻辑层的bean

1
2
3
4
5
6
7
8
9
10
11
12
<?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-2.5.xsd">
 
    <bean id="userService" class="com.sxt.service.UserService">
        <property name="userDao" ref="userDao"></property>
    </bean>
     
</beans>

下面是hib-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?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"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  http://www.springframework.org/schema/context  
   http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
    <context:component-scan  base-package="com.sxt"/>  
    <!-- 支持aop注解 -->
    <aop:aspectj-autoproxy />
     
         
    <bean id="dataSource" 
            class="org.apache.commons.dbcp.BasicDataSource"
            <property name="driverClassName" 
                value="com.mysql.jdbc.Driver"
            </property
            <property name="url" value="jdbc:mysql://localhost:3306/myhib"></property
            <property name="username" value="root"></property
            <property name="password" value="123456"></property>
    </bean
 
   <bean id="sessionFactory" 
       class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
           <property name="dataSource"
               <ref bean="dataSource" /> 
           </property>
           <property name="hibernateProperties"
               <props
                <!-- key的名字前面都要加hibernate. -->
                   <prop key="hibernate.dialect"
                       org.hibernate.dialect.MySQLDialect 
                   </prop
                   <prop key="hibernate.show_sql">true</prop>
                   <prop key="hibernate.hbm2ddl.auto">update</prop>
               </props>
           </property>
        <property name="packagesToScan">
            <value>com.sxt.po</value>
        </property>
   </bean
 
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
 
<!--配置一个JdbcTemplate实例--> 
<bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">  
     <property name="dataSource" ref="dataSource"/>  
</bean
 
 
<!-- 配置事务管理 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<aop:config>
    <aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager" >
    <tx:attributes>
        <tx:method name="find*"  read-only="true" propagation="NOT_SUPPORTED"  />
        <!-- get开头的方法不需要在事务中运行 。
        有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
        <tx:method name="*"/>    <!-- 其他方法在实务中运行 -->
    </tx:attributes>
</tx:advice>
 
</beans>


dao-config.xml

1
2
3
4
5
6
7
8
9
10
11
<?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-2.5.xsd">
     
    <bean id="userDao" class="com.sxt.dao.UserDao">
      <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>
</beans>

包的结构为下面:

user.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.sxt.po;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String uname;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
}

UserDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.sxt.dao;
 
import org.springframework.orm.hibernate3.HibernateTemplate;
 
import com.sxt.po.User;
 
public class UserDao {
    private HibernateTemplate hibernateTemplate;
     
    public void add(User u){
        System.out.println("UserDao.add()");
        hibernateTemplate.save(u);
    }
 
    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }
 
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
     
}

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.sxt.service;
 
import com.sxt.dao.UserDao;
import com.sxt.po.User;
 
public class UserService {
     
    private UserDao userDao;
     
    public void add(String uname){
        System.out.println("UserService.add()");
        User u = new User();
        u.setUname(uname);
        userDao.add(u);
    }
 
    public UserDao getUserDao() {
        return userDao;
    }
 
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
     
}

UserController.java 这里一般是叫controller,而且是实现controller接口

我们可以看见接口controller的实现是怎样的

其实controller是实现的HttpServletRequest和HttpServletResponse方法,很像servlet一样。

ModelAndView是MVC中的M和V就是数据和视图,比如我们跳转到ok.jsp中有页面还得有数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.sxt.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
import com.sxt.service.UserService;
 
public class UserController implements Controller {
 
    private UserService userService;
     
    @Override
    public ModelAndView handleRequest(HttpServletRequest req,
            HttpServletResponse resp) throws Exception {
        System.out.println("HelloController.handleRequest()");
        req.setAttribute("a", "aaaa");
        userService.add(req.getParameter("uname"));
        return new ModelAndView("index");
    }
 
    public UserService getUserService() {
        return userService;
    }
 
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
 
     
}

controller层中我们返回的是new ModelAndView("index");这就对应我们之前说的前缀和后缀的问题,这里就会跳转到index.jsp中

    运行测试:

http://locahost:8080/springmvc01/user.do?uname=zhangsan

 

结果:数据库中增加zhangsan的记录。页面跳转到index.jsp上,显示:












来自为知笔记(Wiz)