【JavaWeb项目】一个众筹网站的开发(二)架构搭建之架构测试

1.dao层和pojo都是使用mbg生成,基本的CRUD以及JavaBean

2.将mbg放在dao层,一旦dao层打包以后mbg就删除掉

一、创建数据库用于测试

数据库名称:scw_0325

SQL:

/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2017/6/12 21:44:22                           */
/*==============================================================*/


drop table if exists t_account_type_cert;

drop table if exists t_advertisement;

drop table if exists t_cert;

drop table if exists t_dictionary;

drop table if exists t_member;

drop table if exists t_member_address;

drop table if exists t_member_cert;

drop table if exists t_member_project_follow;

drop table if exists t_message;

drop table if exists t_order;

drop table if exists t_param;

drop table if exists t_permission;

drop table if exists t_project;

drop table if exists t_project_tag;

drop table if exists t_project_type;

drop table if exists t_return;

drop table if exists t_role;

drop table if exists t_role_permission;

drop table if exists t_tag;

drop table if exists t_type;

drop table if exists t_user;

drop table if exists t_user_role;

/*==============================================================*/
/* Table: t_account_type_cert                                   */
/*==============================================================*/
create table t_account_type_cert
(
   id                   int(11) not null auto_increment,
   accttype             char(1),
   certid               int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_advertisement                                       */
/*==============================================================*/
create table t_advertisement
(
   id                   int(11) not null auto_increment,
   name                 varchar(255),
   iconpath             varchar(255),
   status               char(1),
   url                  varchar(255),
   userid               int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_cert                                                */
/*==============================================================*/
create table t_cert
(
   id                   int(11) not null auto_increment,
   name                 varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_dictionary                                          */
/*==============================================================*/
create table t_dictionary
(
   id                   int(11) not null auto_increment,
   name                 varchar(255),
   code                 varchar(255),
   subcode              varchar(255),
   val                  varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_member                                              */
/*==============================================================*/
create table t_member
(
   id                   int(11) not null auto_increment,
   loginacct            varchar(255) not null,
   userpswd             char(32) not null,
   username             varchar(255) not null,
   email                varchar(255) not null,
   authstatus           char(1) not null,
   usertype             char(1) not null,
   realname             varchar(255),
   cardnum              varchar(255),
   accttype             char(1),
   primary key (id)
);

/*==============================================================*/
/* Table: t_member_address                                      */
/*==============================================================*/
create table t_member_address
(
   id                   int(11) not null auto_increment,
   memberid             int(11),
   address              varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_member_cert                                         */
/*==============================================================*/
create table t_member_cert
(
   id                   int(11) not null auto_increment,
   memberid             int(11),
   certid               int(11),
   iconpath             varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_member_project_follow                               */
/*==============================================================*/
create table t_member_project_follow
(
   id                   int(11) not null auto_increment,
   projectid            int(11),
   memberid             int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_message                                             */
/*==============================================================*/
create table t_message
(
   id                   int(11) not null auto_increment,
   memberid             int(11),
   content              varchar(255),
   senddate             char(19),
   primary key (id)
);

/*==============================================================*/
/* Table: t_order                                               */
/*==============================================================*/
create table t_order
(
   id                   int(11) not null auto_increment,
   memberid             int(11),
   projectid            int(11),
   returnid             int(11),
   ordernum             varchar(255),
   createdate           char(19),
   money                int(11),
   rtncount             int(11),
   status               char(1),
   address              varchar(255),
   invoice              char(1),
   invoictitle          varchar(255),
   remark               varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_param                                               */
/*==============================================================*/
create table t_param
(
   id                   int(11) not null auto_increment,
   name                 varchar(255),
   code                 varchar(255),
   val                  varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_permission                                          */
/*==============================================================*/
create table t_permission
(
   id                   int(11) not null auto_increment,
   pid                  int(11),
   name                 varchar(255),
   icon                 varchar(255),
   url                  varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_project                                             */
/*==============================================================*/
create table t_project
(
   id                   int(11) not null auto_increment,
   name                 varchar(255),
   remark               varchar(255),
   money                bigint (11),
   day                  int(11),
   status               char(1),
   deploydate           char(10),
   supportmoney         bigint(11),
   supporter            int(11),
   completion           int(3),
   memberid             int(11),
   createdate           char(19),
   follower             int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_project_tag                                         */
/*==============================================================*/
create table t_project_tag
(
   id                   int(11) not null auto_increment,
   projectid            int(11),
   tagid                int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_project_type                                        */
/*==============================================================*/
create table t_project_type
(
   id                   int not null auto_increment,
   projectid            int(11),
   typeid               int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_return                                              */
/*==============================================================*/
create table t_return
(
   id                   int(11) not null auto_increment,
   projectid            int(11),
   type                 char(1),
   supportmoney         int(11),
   content              varchar(255),
   count                int(11),
   signalpurchase       int(11),
   purchase             int(11),
   freight              int(11),
   invoice              char(1),
   rtndate              int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_role                                                */
/*==============================================================*/
create table t_role
(
   id                   int(11) not null,
   name                   varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_role_permission                                     */
/*==============================================================*/
create table t_role_permission
(
   id                   int(11) not null auto_increment,
   roleid               int(11),
   permissionid         int(11),
   primary key (id)
);

/*==============================================================*/
/* Table: t_tag                                                 */
/*==============================================================*/
create table t_tag
(
   id                   int(11) not null auto_increment,
   pid                  int(11),
   name                 varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_type                                                */
/*==============================================================*/
create table t_type
(
   id                   int(11) not null auto_increment,
   name                 varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: t_user                                                */
/*==============================================================*/
create table t_user
(
   id                   int not null auto_increment,
   loginacct            varchar(255) not null,
   userpswd             char(32) not null,
   username             varchar(255) not null,
   email                varchar(255) not null,
   createtime           char(19),
   primary key (id)
);

/*==============================================================*/
/* Table: t_user_role                                           */
/*==============================================================*/
create table t_user_role
(
   id                   int(11) not null auto_increment,
   userid               int(11),
   roleid               int(11),
   primary key (id)
);

alter table t_project_tag add constraint FK_Reference_7 foreign key (projectid)
      references t_project (id) on delete restrict on update restrict;

alter table t_project_tag add constraint FK_Reference_8 foreign key (tagid)
      references t_tag (id) on delete restrict on update restrict;

alter table t_project_type add constraint FK_Reference_5 foreign key (projectid)
      references t_project (id) on delete restrict on update restrict;

alter table t_project_type add constraint FK_Reference_6 foreign key (typeid)
      references t_type (id) on delete restrict on update restrict;

alter table t_role_permission add constraint FK_Reference_3 foreign key (roleid)
      references t_role (id) on delete restrict on update restrict;

alter table t_role_permission add constraint FK_Reference_4 foreign key (permissionid)
      references t_permission (id) on delete restrict on update restrict;

alter table t_user_role add constraint FK_Reference_1 foreign key (userid)
      references t_user (id) on delete restrict on update restrict;

alter table t_user_role add constraint FK_Reference_2 foreign key (roleid)
      references t_role (id) on delete restrict on update restrict;

数据库设计图:

二、Mybatis逆向工程

在manager-dao/src/main/java下创建

com.atguigu.scw.manager.dao.test包

MBGTest类

 在dao工程下创建mbg.xml(在工程下,打包时会忽略,因为我们用来测试,不需要生产中使用,只会打包src源码文件夹下的)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/scw_0325" userId="root"
            password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- pojo生成的地方 -->
        <javaModelGenerator targetPackage="com.atguigu.scw.manager.bean"
            targetProject="..\manager-pojo\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- sql映射文件生成的地方 -->
        <sqlMapGenerator targetPackage="mybatis.mapper"
            targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- dao接口生成的地方 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.atguigu.scw.manager.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 只要是数据库对应的pojo,我们都以T开头 -->
        <!-- 指定要逆向的每一张表,用户表 -->
        <table tableName="t_user" domainObjectName="TUser"></table>
        <table tableName="t_user_role" domainObjectName="TUserRole"></table>
        <table tableName="t_type" domainObjectName="TType"></table>
        <table tableName="t_tag" domainObjectName="TTag"></table>
        <table tableName="t_role_permission" domainObjectName="TRolePermission"></table>
        <table tableName="t_role" domainObjectName="TRole"></table>
        <table tableName="t_return" domainObjectName="TReturn"></table>
        <table tableName="t_project_type" domainObjectName="TProjectType"></table>
        <table tableName="t_project_tag" domainObjectName="TProjectTag"></table>
        <table tableName="t_project" domainObjectName="TProject"></table>
        <table tableName="t_permission" domainObjectName="TPermission"></table>
        <table tableName="t_param" domainObjectName="TParam"></table>
        <table tableName="t_order" domainObjectName="TOrder"></table>
        <table tableName="t_message" domainObjectName="TMessage"></table>
        <table tableName="t_member_project_follow" domainObjectName="TMemeberProjectFollow"></table>
        <table tableName="t_member_cert" domainObjectName="TMemberCert"></table>
        <table tableName="t_member_address" domainObjectName="TMemberAddress"></table>
        <table tableName="t_member" domainObjectName="TMemeber"></table>
        <table tableName="t_dictionary" domainObjectName="TDictionary"></table>
        <table tableName="t_cert" domainObjectName="TCert"></table>
        <table tableName="t_advertisement" domainObjectName="TAdvertisement"></table>
        <table tableName="t_account_type_cert" domainObjectName="TAccountTypeCert"></table>
        

    </context>
</generatorConfiguration>

根据上面配置的sql生成的地方,在dao的src/main/resources下创建mybatis.mapper包

在最开头的意为去除注解

 <commentGenerator>
     <property name="suppressAllComments" value="true" />
</commentGenerator>

数据库表t_user,对应的JavaBean对象是TUser

 <table tableName="t_user" domainObjectName="TUser"></table>

编写逆行工程的代码

package com.atguigu.scw.manager.dao.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;


public class MBGTest {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("生成成功!");
    }
}

运行:

 

三、三大框架整合

MyBatis配置文件放在dao层

在src/main/resources的mybatis中创建配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    <!-- 分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>

在mybaits中,setting的的配置参数如下(如果不在配置文件中配置将使用默认值):

设置参数 描述 有效值 默认值
cacheEnabled 该配置影响的所有映射器中配置的缓存的全局开关 true | false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态 true | false false
aggressiveLazyLoading 当启用时,对任意延迟属性的调用会使带有延迟加载属性的对象完整加载;反之,每种属性将会按需加载。 true | false true
multipleResultSetsEnabled 是否允许单一语句返回多结果集(需要兼容驱动)。 true | false true
useColumnLabel 使用列标签代替列名。不同的驱动在这方面会有不同的表现, 具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。 true | false true
useGeneratedKeys 允许 JDBC 支持自动生成主键,需要驱动兼容。 如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。 true | false False
autoMappingBehavior 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。 NONE, PARTIAL, FULL PARTIAL
defaultExecutorType 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。 SIMPLE REUSE BATCH SIMPLE
defaultStatementTimeout 设置超时时间,它决定驱动等待数据库响应的秒数。 Any positive integer Not Set (null)
defaultFetchSize Sets the driver a hint as to control fetching size for return results. This parameter value can be override by a query setting. Any positive integer Not Set (null)
safeRowBoundsEnabled 允许在嵌套语句中使用分页(RowBounds)。 true | false False
mapUnderscoreToCamelCase 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 true | false False
localCacheScope MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。 SESSION | STATEMENT SESSION
jdbcTypeForNull 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER OTHER
lazyLoadTriggerMethods 指定哪个对象的方法触发一次延迟加载。 A method name list separated by commas equals,clone,hashCode,toString
defaultScriptingLanguage 指定动态 SQL 生成的默认语言。 A type alias or fully qualified class name. org.apache.ibatis.scripting.xmltags.XMLDynamicLanguageDriver
callSettersOnNulls 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意基本类型(int、boolean等)是不能设置成 null 的。 true | false false
logPrefix 指定 MyBatis 增加到日志名称的前缀。 Any String Not set
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING Not set
proxyFactory 指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。 CGLIB | JAVASSIST JAVASSIST (MyBatis 3.3 or above)

去web层配置web.xml

<?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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    
  

    <!-- 启动spring容器 -->
    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-*.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    <!-- The front controller of this Spring Web application, responsible for 
        handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 加上字符编码过滤器 -->
    <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>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


</web-app>

创建spring-beans.xml,扫描所有javabean

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 负责包扫描,配置组件等 -->
    <!--1、spring不扫描控制器  -->
    <context:component-scan base-package="com.atguigu.scw.manager">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!--2、数据库  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/scw_0325" ></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        
        <property name="initialSize" value="5"></property>
    </bean>
</beans>

创建spring-tx.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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 配置事务 -->
    <!--Spring启动加载所有spring的配置文件都能自动找到  -->
    <!--1、配置事务管理器  -->
    <bean id="tm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!--2、配置事务切面  -->
    <aop:config>
        <aop:pointcut expression="execution(* com.atguigu.scw.manager.service.*.*(..))" id="txPoint"/>
        <!--事务增强  -->
        <aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"/>
    </aop:config>
    
    <!--3、配置事务增强  -->
    <tx:advice id="myAdvice" transaction-manager="tm">
        <!--事务属性  -->
        <tx:attributes>
            <tx:method name="*"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

</beans>

创建spring-mybatis.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">

    <!-- 配置用mybatis操作数据库 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <!-- 指定数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 指定所有mapperxml的位置 -->
        <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
    </bean>
    
    <!-- 将所有mapper接口的实现类自动加入到ioc容器中  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.scw.manager.dao"></property>
    </bean>

</beans>

springmvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
        
    <!--1、默认就是包含所有  -->    
    <context:component-scan base-package="com.atguigu.scw.manager.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!--2、视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsps/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 映射动态资源,并开启开挂模式 -->
    <mvc:annotation-driven/>
    <!-- 映射静态资源,将静态资源交给tomcat -->
    <mvc:default-servlet-handler/>

</beans>

service层写接口

package com.atguigu.scw.manager.service;

import com.atguigu.scw.manager.bean.TUser;

public interface UserService {

    public TUser getTUserById(Integer id) ;
}

写实现

package com.atguigu.scw.manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atguigu.scw.manager.bean.TUser;
import com.atguigu.scw.manager.dao.TUserMapper;
import com.atguigu.scw.manager.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    TUserMapper userMapper;

    public TUser getUserById(Integer id) {

        return userMapper.selectByPrimaryKey(id);;
    }

}

web层

package com.atguigu.scw.manager.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.atguigu.scw.manager.bean.TUser;
import com.atguigu.scw.manager.service.UserService;

@Controller
public class HelloController {

    @Autowired
    UserService userService;

    @RequestMapping("/hello")
    public String hello(@RequestParam(value = "id", defaultValue = "1") Integer id, Model model) {
        TUser user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "forward:/success.jsp";
    }

}

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>你好</h1>
${user }:<br/>

</body>
</html>

启动

运行成功

猜你喜欢

转载自www.cnblogs.com/aidata/p/11462047.html