SpringMVC框架基本原理

        SpringMVC基本框架图:


SpringMVC基本框架图

        SpringMVC注解:

把类声明为Spring容器的bean文件,可以再其他地方调用。

@Controllers声明控制层;

@Service声明服务层;

@Repository声明持久层(数据传输层DAO)。

@RequestMapping把一个POJO声明为Spring里的Controller,如果不声明要写Controller类就要从Spring的Controller类继承,并重新handleRequest方法。

@RequestMapping(value="*.htm",method=RequestMethod.GET)属性value声明Controller处理的请求,method声明处理请求的类型,可声明在类头上,也可声明在方法头上;

@RequestParam绑定参数与请求参数

例如:public String Controller(@RequestParam("id") int topicId, User user)

把参数topicId与请求的参数“id”绑定,id的值传入topicId。


Spring常用注解

@AutoWired根据类型自动装配,可放在属性上,set方法上,构造方法上,与@AutoWired配套使用的是@Qualifier。按名字自动装配,

例如@AutoWired

@Qualifier("userDAO") UserDAO userDAO

@Resource 与@AutoWired类似

默认按名字匹配,有两个属性name,type;

如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常;

如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常;

如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常;

如果既没有指定name,又没有指定type,则自动按照byName方式进行;

如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配。


DispatcherServlet

SpringMVC中前端控制器是org,springframework,web,servlet,DispatcherServlet

负责将请求分配给控制对象,所以使用SpringMVC的第一步是在web.xml中定义DispatcherServlet

<servlet>
    <servlet-name>spring<servlet-name>
    <servlet-class>org.springframework,web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>spring</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
可加上contextConfigLocation的初始化参数,用来舍子Bean定义文件的位置和名称,默认使用"Servlet(名称)-servlet.xml"如本例的spring-servlet.xml
<servlet>
    <servlet-name>spring<servlet-name>
    <servlet-class>org.springframework,web.servlet.DispatcherServlet</servlet-class>
<init-class>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-config.xml,/WEB-INFO/spring-config.xml</param-value> //<strong><span style="color:#cc0000;">两个bean文件来源</span></strong>
</init-param>
</servlet>

spring-servlet.xml模板

<?xml version="1.0" encoding="UTF-8"?>
<!-- Bean头部 -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    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
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    <!-- 加载权限设置 -->
    <bean id="security" class="com.boaotech.util.Security"
        p:contextConfigLocation="WEB-INF/security.xml" />
    <!-- 加载菜单项 -->
    <bean id="menus" class="com.boaotech.util.Menus"
        p:contextConfigLocation="WEB-INF/menus.xml" p:security-ref="security" />

    <!-- Json返回格式化转换 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
    <!-- 设置全局日期参数的字符串表示格式 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
        <property name="webBindingInitializer"> 
            <bean class="com.boaotech.util.CommonBindingInitializer"/> 
        </property>
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/>
            </list>
        </property>
    </bean> 
    <!-- 激活@Controller模式 -->
    <mvc:annotation-driven />
    <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能  需要更改-->
    <context:component-scan base-package="com.boaotech.zhaotaoerp" />
    <context:annotation-config/>
    <!-- 激活计划任务注解 -->
    <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
    <task:scheduler id="myScheduler" pool-size="1"/>
    <task:executor id="myExecutor" pool-size="1"/>
    <!-- 配置拦截器 -->
    <mvc:interceptors>
        <bean id="authorizeInterceptor" class="com.boaotech.util.AuthorizeInterceptor" />
    </mvc:interceptors>
    <!-- 类名到视图名的自动映射 -->
    <!-- bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/ -->
    <!-- FreeMarker配置文件 -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">5</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="locale">zh_CN</prop>
            </props>
        </property>
    </bean>
    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"
        p:cache="true" p:prefix="" p:suffix=".ftl"
        p:contentType="text/html;charset=UTF-8"
        p:exposeRequestAttributes="true" p:exposeSessionAttributes="true"
        />
    <!-- bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp" / -->
</beans>

spring 3.0 application-conext.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:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    <!-- 数据库配置 -->
    <context:property-placeholder location="WEB-INF/mysql.properties, WEB-INF/bonecp.properties"/>
    <!-- 激活@Required 和 @Autowired注解功能 -->
    <context:annotation-config/>
    <!-- 加载中文字符串转拼音的bean -->
    <!-- bean id="cnToSpell" class="com.boaotech.util.CnToSpell" / -->
    <!-- 缓存配置 -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:configLocation="WEB-INF/ehcache.xml" p:shared="true"/>
    <!-- 数据库源配置 -->
    <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"
        p:driverClass="${jdbc.driverClassName}"
        p:jdbcUrl="${jdbc.url}"
        p:username="${jdbc.username}"
        p:password="${jdbc.password}"
        p:idleConnectionTestPeriod="${bonecp.idleConnectionTestPeriod}"
        p:idleMaxAge="${bonecp.idleMaxAge}"
        p:partitionCount="${bonecp.partitionCount}"
        p:minConnectionsPerPartition="${bonecp.minConnectionsPerPartition}"
        p:maxConnectionsPerPartition="${bonecp.maxConnectionsPerPartition}"
        p:acquireIncrement="${bonecp.acquireIncrement}"
        p:poolAvailabilityThreshold="${bonecp.poolAvailabilityThreshold}"
        p:connectionTimeout="${bonecp.connectionTimeout}"
        p:statementsCacheSize="${bonecp.statementsCacheSize}"
        p:releaseHelperThreads="${bonecp.releaseHelperThreads}"
        p:statementReleaseHelperThreads="${bonecp.statementReleaseHelperThreads}"
        p:disableJMX="true" />
    <!-- 使用iBatis作为持久层 -->
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"
        p:configLocation="WEB-INF/sqlmap-config.xml"
        p:dataSource-ref="dataSource"/>
    <!-- 声明事务管理bean -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
            p:dataSource-ref="dataSource" />
    <!-- 激活@Transactional 和 @ManagedOperation 注解,事物管理功能 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
</beans>


Controller层

    @Controller //将类声明为Spring容器里的Bean,Spring调用时实例化

    @RequestMapping(“index.htm”)//声明这个Controller处理的请求是什么

public class IndexController{

@RequestMapping(method = RequestMethod.GET)  //请求的方法默认为get

public String doGet(){

return "index";     //返回“index”,交由ViewResolver解析,返回调用 “/WEB-INF/index.jsp"

}

}


//处理post请求的Controller

@Controller

@RequestMapping(value="index.htm",method = RequestMethod.POST)

public String doPost(String username, String password, ModeMap modelMap) throws Exception{  //ModelMap,String提供的集合可以传递数据到返回的jsp页面

modelMap.addAttribute("name",username); //把username以键值对的形式存入ModelMap,在index.jsp中用request对象接收

return "index";

}


Service层

注:面向接口编程,降低各层之间的耦合度

public interface UserService{
    boolean login(String user,String pwd) throws Exception;
}
@Service("userService")
public UserServiceImpl implements UserSerivce{
        //实现接口方法
        boolean login(String user,String pwd) throws Exception{
        return true;
}

DAO层

<strong>public interface UserDAO{
       public User selectByname(String user) throws Exception;
}
@Repository("userDAO")
public userDAOImpl implements UserDAO{
//实现接口方法
        public User selectByname(String user){
        return null;
    }
}</strong>




  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值