SpringMvc+Spring+MyBatis+Maven整合教程(2)(待修改)

加入 SpringMVC 部分:

1、写控制器

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/{id}")
    public String user(@PathVariable(value = "id") String id,Map<String,String> map){
        System.out.printf("id " + id);
        User user = userService.sayHello(id);
        map.put("name",user.getUserRealName());
        map.put("info","web.xml 版本信息也很重要");
        return "hello";
    }
}

2、写 web.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>Archetype Created Web Application</display-name>

    <!-- 引入 Spring 的配置文件,让 Web 项目启动 Spring 的配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 引入 SpringMVC 的配置文件 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3、springmvc 的配置文件 spring-mvc.xml

<context:component-scan base-package="com.liwei.controller">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

其实以上两步就简单完成了代码的编写,可以使用 jetty 容器进行测试了:

<plugins>
    <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
    </plugin>
</plugins>

下面我们尝试加入日志组件:

1、 GAV 依赖

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2、log4j.properties 文件片段

log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n

注意事项:

1、注意让 web 项目集成 Spring 的监听器的配置;

<!-- 引入 Spring 的配置文件,让 Web 项目启动 Spring 的配置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2、web.xml 的版本号会影响你在 jsp 页面里面是否能够使用 EL 表达式。

3、MyBatis 自动生成代码插件的用法。

参考资料:

SpringMVC + spring3.1.1 + hibernate4.1.0 集成及常见问题总结 - 开涛的博客(欢迎关注我的公众号[博客头像二维码]) - ITeye技术网站 http://jinnianshilongnian.iteye.com/blog/1423971

改进版的测试方法(第 1 版)

public class TestMybatis {

    private ApplicationContext ac;
    private UserServiceI userService;

    @Before
    public void before(){
        ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
        userService = (UserServiceI)ac.getBean("userService");
    }

    @Test
    public void test1(){
        User u = userService.getUserById("1");
        System.out.println(u.getUserRealName());
    }
}

改进版的测试方法(第 2 版)
在 GAV 中加入 spring-test。表示结合了 spring 的 test 模块。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring.xml","classpath:spring-mybatis.xml"})
public class TestMybatis {


    private UserServiceI userService;

    @Resource
    public void setUserService(UserServiceI userService) {
        this.userService = userService;
    }


    @Test
    public void test1(){
        User u = userService.getUserById("1");
        System.out.println(u.getUserRealName());
    }
}

接下来我们引入 spring-mvc 的 GAV 和配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
    <context:component-scan base-package="com.writing.manager.controller" />

    <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
            </list>
        </property>
    </bean>

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
        <property name="maxUploadSize">
            <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>

</beans>

配置了上面的 json 片段,就须要引入 jackson 的 GAV。搜索
jackson-mapper-asl。
因为用到了文件上传,所以还要加入 commons-fileupload。

既然是 web 项目,我们在启动的时候,就要加上 springmvc 的配置。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>mybatis</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
    </context-param>
    <filter>
        <description>字符集过滤器</description>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <description>字符集编码</description>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <description>spring监听器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <!-- spring mvc servlet -->
    <servlet>
        <description>spring mvc servlet</description>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <description>spring mvc 配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 配置session超时时间,单位分钟 -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

编译 maven 项目。
SpringMvc+Spring+MyBatis+Maven整合教程(2)(待修改)_第1张图片
发布到 tomcat 中。

你可能感兴趣的:(maven,mybatis,springMVC)