我是靠谱客的博主 酷炫小蜜蜂,最近开发中收集的这篇文章主要介绍SpringMvc 3.2配置指南,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1.springmvc框架介绍。
Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的。

另外还有一种基于组件的、事件驱动的Web框架在此就不介绍了,如Tapestry、JSF等。

Spring Web MVC也是服务到工作者模式的实现,但进行可优化。前端控制器是DispatcherServlet;应用控制器其实拆为处理器映射器(Handler Mapping)进行处理器管理和视图解析器(View Resolver)进行视图管理;页面控制器/动作/处理器为Controller接口(仅包含ModelAndView handleRequest(request, response) 方法)的实现(也可以是任何的POJO类);支持本地化(Locale)解析、主题(Theme)解析及文件上传等;提供了非常灵活的数据验证、格式化和数据绑定机制;提供了强大的约定大于配置(惯例优先原则)的契约式编程支持。
2.所需jar包
从spring官网上下载spring mvc3.2版本,导入所有jar包,另外还需要一些支持包,aop相关、log4j、commons-logging等等,总之如果报错请与下面列出的jar包相比较,如果缺少再添加。
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.4.jar
aspectjweaver-1.6.8.jar
cglib-2.2.2.jar
commons-dbcp-1.4.jar
commons-logging-1.1.1.jar
commons-pool-1.3.jar
jackson-core-asl-1.9.7.jar
jackson-core-lgpl-1.9.7.jar
jackson-mapper-asl-1.9.7.jar
jackson-mapper-lgpl-1.9.7.jar
javassist-3.15.0-GA.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
mybatis-3.2.2.jar
mybatis-spring-1.2.1.jar
mysql-connector-java-5.0.8-bin.jar
org.springframework.aop-3.0.5.RELEASE.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-3.2.0.RELEASE.jar
spring-aspects-3.2.0.RELEASE.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-context-support-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
spring-instrument-3.2.0.RELEASE.jar
spring-instrument-tomcat-3.2.0.RELEASE.jar
spring-jdbc-3.2.0.RELEASE.jar
spring-jms-3.2.0.RELEASE.jar
spring-orm-3.2.0.RELEASE.jar
spring-oxm-3.2.0.RELEASE.jar
spring-struts-3.2.0.RELEASE.jar
spring-test-3.2.0.RELEASE.jar
spring-tx-3.2.0.RELEASE.jar
spring-web-3.2.0.RELEASE.jar
spring-webmvc-3.2.0.RELEASE.jar
spring-webmvc-portlet-3.2.0.RELEASE.jar

3.开发环境搭建(不罗嗦,开整)
web.xml配置如下:
如果有不懂的可留言,或者自行百度,学习本来就是一件自主的事。。。。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- 配置spring上下文监视器 -->
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

   <!-- 配置上下文参数加载配置文件 -->
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:*-context.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
     </filter>
     <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
     </filter-mapping>
     <servlet>
        <servlet-name>SpringMVCServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:web-context.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVCServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

文档结构图如下:
这里写图片描述

spring-context.xml配置如下:

<?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.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"/>
        <property name="maxActive" value="5" />
        <property name="maxIdle" value="3" />
        <property name="maxWait" value="1000" />
        <property name="defaultAutoCommit" value="true" />
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="60" />
    </bean>
     <!-- 创建SqlSessionFactory,同时指定数据源 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
         <property name="configLocation" value="classpath:mybatis-config.xml"></property>  
    </bean> 
</beans>

transaction-context.xml:配置如下:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource"/>
    </bean>
    <aop:config>
        <aop:advisor id="managerTx" advice-ref="txAdvice"
         pointcut="within(com.lzf.code.service..*Service) &amp;&amp; execution( * *(..))" order="1"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">      
        <tx:attributes>
            <tx:method name="load*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="crud*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="schedule*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="do*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>
</beans>

user-context.xml:配置如下:

<?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:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd" >
    <!-- 用户Dao-->
    <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
        <property name="mapperInterface" value="com.lzf.code.dao.UserDao" />  
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
    </bean>
  <!-- 扫描数据访问层,组装数据访问接口实现类 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.lzf.code"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
  </bean>

</beans>

web-context.xml配置如下:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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">

    <!-- 启动扫描Code下所有的controller --> 
    <context:component-scan base-package="com.lzf.code"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>

     <!-- 避免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.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <prop key="org.springframework.web.servlet.PageNotFound">error/pageNotFound</prop>  
                <prop key="org.springframework.dao.DataAccessException">error/dataAccessFailure</prop>  
                <prop key="org.springframework.transaction.TransactionException">error/dataAccessFailure</prop>  
            </props>
        </property>
    </bean>
     <!-- jsp页面解析器,当Controller返回XXX字符串时,先通过拦截器,然后该类就会在/WEB-INF/pages/目录下,查找XXX.jsp文件-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

log4j配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="appender" class="org.apache.log4j.ConsoleAppender">
        <param name="threshold" value="ERROR"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="[cmall] %p [%t] %c{1}.%M(%L) | %m%n"/>
        </layout>
    </appender>

      <!--  
    <appender name="actionAppender" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="/opt/logs/ActionsError.log"/>
        <param name="Append" value="true"/>
        <param name="threshold" value="INFO"/>
        <param name="DatePattern" value="'.'yyyy-MM-dd'.txt'"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
        </layout>
    </appender>  

    <category name="com">
        <priority value="ERROR"/>
        <appender-ref ref="appender"/>
    </category>

    <category name="com.ibatis">
        <priority value="ERROR"/>
        <appender-ref ref="appender"/>
    </category>

    </category>
     -->
    <category name="com.ibatis">
        <priority value="DEBUG"/>
        <appender-ref ref="appender"/>
    </category>

    <category name="java.sql">
        <priority value="DEBUG"/>
        <appender-ref ref="appender"/>
    </category>

    <category name="com">
        <priority value="DEBUG"/>
        <appender-ref ref="appender"/>
    </category>    

  <!-- 
    <category name="com">
        <priority value="DEBUG"/>
        <appender-ref ref="actionAppender"/>
    </category>   -->

    <root>
        <level value="ERROR" />
        <appender-ref ref="appender"/>
    </root>
</log4j:configuration>

详细的目录结构图再看一下。

user.java:

package com.lzf.code.vo;

public class User {
    //用户ID
    private int user_id;
    //用户姓名
    private String user_name;

    private String credits;

    //用户密码
    private String password;

    private String last_visit;

    private String last_id;

    public int getUser_id() {
        return user_id;
    }

    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getCredits() {
        return credits;
    }

    public void setCredits(String credits) {
        this.credits = credits;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLast_visit() {
        return last_visit;
    }

    public void setLast_visit(String last_visit) {
        this.last_visit = last_visit;
    }

    public String getLast_id() {
        return last_id;
    }

    public void setLast_id(String last_id) {
        this.last_id = last_id;
    }
}

UserDao.java:

package com.lzf.code.dao;

import com.lzf.code.vo.User;


public interface UserDao {

    //根据id获取用户信息
    public User getUserInfo(int id);

}

UserService.java:

package com.lzf.code.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.JavaScriptUtils;

import com.lzf.code.dao.UserDao;
import com.lzf.code.vo.User;

@Service
@RequestMapping(value="/user")
public class UserService {
    @Autowired
    private UserDao userDao;

    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String login(){
        return "/user/success";
    }

    @RequestMapping(value="/json",method=RequestMethod.GET)
    public @ResponseBody List<User>test(){
        List<User>userlist =new ArrayList<User>();
        User user1 =new User();
        /*user1.setId(0);
        user1.setName("jack");
        user1.setPassword("abc");
        userlist.add(user1);
        User user2 =new User();
        user2.setId(0);
        user2.setName("tom");
        user2.setPassword("abc");
        userlist.add(user2);*/
        return userlist;
    }

    @RequestMapping(value="/add",method=RequestMethod.GET)
    public ModelAndView add(@RequestParam(value="username",required=true,defaultValue="lzf")String username) {
        User user = userDao.getUserInfo(1);
        ModelAndView mv =null;
        if(user!=null){
            System.out.println(user.getUser_name());
            mv = new ModelAndView("/user/addSuccess");
            mv.addObject("info","该用户姓名为:"+user.getUser_name());
        }else{
            mv = new ModelAndView("/user/addSuccess");
            mv.addObject("info","该用户不存在!");

        }
        return mv;
    }
}

UserDao.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.lzf.code.dao.UserDao">
    <select id="getUserInfo" parameterType="int" resultType="Userinfo">
        select * from t_user where user_id = #{id}
    </select>
</mapper>

主要配置就这么多,涉及简单的环境搭建,与mybaits整合,使用log4j作为日志管理。

有疑问的地方可以留言或者百度,或者添加qq:957633749,也可发邮件:957633749@qq.com

最后

以上就是酷炫小蜜蜂为你收集整理的SpringMvc 3.2配置指南的全部内容,希望文章能够帮你解决SpringMvc 3.2配置指南所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部