一、.首先建立maven工程,参考http://blog.csdn.net/dearlhb/article/details/19755345
二、.搭建ssmm的环境
2.1添加相关jar包。
1.到http://search.maven.org/网站搜索spring核心包,spring-core。。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
2.添加mybatis的jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
3.添加整合spring和mybatis的jar包,搜索mybatis-spring。之前使用过1.1.1版本,加上配置会加载上需要的spring等jar包,升级到1.2.2之后不会再加载这些jar,所以还需手动添加上。其还需要mybatis,spring-core,spring-tx,spring-jdbc,spring-context。相关jar包。。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- spring相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
5.添加单元测试junit
<!-- 单元测试junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
由于junit仅在测试环境中使用,所以需按如下添加其作用域。
<!-- 单元测试junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
6.由于使用的是mybatis,其官方提供了自动生成代码的工具(mybatis-generator-core-1.3.2.jar),通过该jar包可以实现自动生成mybatis的entity,sqlmap及dao的操作。你可以通过命令行方式,也可以通过配置maven实现,如下采用添加maven插件实现。mybatis generator配置参考;http://blog.csdn.net/isea533/article/details/42102297
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!--允许覆盖生成的文件 -->
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
其生成类的xml配置如下:generatorConfig.xml
<pre name="code" class="html"><?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>
<classPathEntry location="F:\apache-maven-3.2.1\repo\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar" />
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="'"/>
<property name="endingDelimiter" value="'"/>
<plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"></plugin>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<!--plugin type="PaginationPlugin"></plugin-->
<!-- 去除自动生成的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="false" />
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/luckyssmm"
userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="lucky.ssmm.sys.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成的映射文件包名和位置 -->
<sqlMapGenerator targetPackage="sys.sqlmap" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="lucky.ssmm.sys.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
<table tableName="sys_user" domainObjectName="User" />
<!--table tableName="sys_user_role" domainObjectName="Menu" /-->
<table tableName="sys_role" domainObjectName="Role" />
<!--table tableName="sys_role_menu" domainObjectName="Resource" /-->
<table tableName="sys_menu" domainObjectName="Menu" />
<!--table tableName="sys_role_office" domainObjectName="RoleResource" /-->
<table tableName="sys_office" domainObjectName="Office" />
<table tableName="sys_area" domainObjectName="Area" />
<table tableName="sys_dict" domainObjectName="Dict" />
<table tableName="sys_mdict" domainObjectName="Mdict" />
<table tableName="sys_log" domainObjectName="Log" />
</context>
</generatorConfiguration>
项目 右键--》run as --》 maven bulid --》弹出对话框 --》在goals中输入mybatis-generator:generate 或者 点击select --》选择你的mybatis插件 --》apply --》run
选择项目 按 F5 刷新项目 出现生成的代码
2.2添加spring配置文件1. 在src/main/rescource添加spring配置文件,spring.xml
引用数据库配置文件config.properties
配置自动扫描service服务,递归扫描lucky.ssmm.service包中@Service注解,自动注入相应的bean.否则的话需要手写bean,,,<bean id="userService" class="lucky.ssmm.service.****"></bean>等。所以使用注解将方便很多。
<?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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan base-package="lucky.ssmm.service" />
</beans>
2.添加数据库配置文件config.properties..主要为数据库配置,及其他项目配置
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc_username=sypro
#jdbc_password=sypro
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/luckyssmm?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=root
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=sa
#jdbc_password=123456
#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=sypro
#jdbc_password=sypro
#jndiName=java:comp/env/dataSourceName
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=true
sessionInfoName=sessionInfo
uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
3.由于在引用数据源的时候,本项目将采用druid阿里巴巴开发的数据源插件,所以需引用druid的包。
<!-- druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
4.由于是整合mybatis,所以还需要spring整合mybatis的文件,在src/main/rescource添加spring-mybatis.xml的配置文件。
(1)因为mybatis需要连接数据源,所以需要配置其数据源连接信息。
由于使用的druid的数据源,所以bean的dataSource的class需写为com.alibaba.druid.pool.DruidDataSource。。。
配置中的$变量值,即为config.properties中的配置信息。
<!-- JNDI方式配置数据源 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->
<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
mybatis的配置:
添加mybatis的sqlSessionFactory的工厂管理
制定dataSource的数据源。
配置mybatis的sql映射的xml文件。通过自动扫描完成。
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath:lucky/ssmm/mapping/*.xml" />
</bean>
通过sqlSessionFactory管理dao中的mapper对象。
还是通过spring自动扫描包实现滴。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="lucky.ssmm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
配置事务管理器。
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
配置事务的拦截方式;
</pre><pre name="code" class="html"> <!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* lucky.ssmm.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
druid的配置,不需要可以不用配置:
<!-- 配置druid监控spring jdbc -->
<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns">
<list>
<value>lucky.ssmm.service.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
</aop:config>
以上spring,mybatis整合以完毕。
如下下单元测试,测试配置是否可用:
首先建立service包。lucky.ssmm.sys.service和lucky.ssmm.sys.service.impl。
然后分别建立测试接口与类。实现一个通过id获取用户的方法,代码如下:
import lucky.ssmm.sys.model.User;
public interface UserServiceI {
public User getUserById(String ids);
}
<pre name="code" class="html">import lucky.ssmm.sys.dao.UserMapper;
import lucky.ssmm.sys.model.User;
import lucky.ssmm.sys.service.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserServiceI {
private UserMapper userMapper;
public UserMapper getUserMapper() {
return userMapper;
}
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public User getUserById(String id) {
return userMapper.selectByPrimaryKey(id);
}
}
如下编写junit测试类,在src/test/java中建立lucky.ssmm.test包,并建立TestMybatis.java,代码如下:
import lucky.ssmm.sys.model.User;
import lucky.ssmm.sys.service.UserServiceI;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMybatis {
@Test
public void test1() {
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] { "spring.xml", "spring-mybatis.xml" });
UserServiceI userService = (UserServiceI)ac.getBean("userService");
User u = userService.getUserById("0");
System.out.println(MessageFormat.format("获取的用户{0}", u));
}
}
这样,测试代码已经完成,如下即需要运行,通过运行测试,发现,junit并没有通过,抛出异常,还缺少其他相关包,所以通过提示,依次添加到pom中,
Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.tools.PointcutDesignatorHandler
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 38 more
通过如上错误,到maven库中查找org.aspectj,将如下jar添加到pom中,在测:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
添加如上包后,单元测试通过。
如下简单修改了一下单元测试:
import lucky.ssmm.sys.model.User;
import lucky.ssmm.sys.service.UserServiceI;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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("0");
System.out.println(MessageFormat.format("获取的用户{0}", u));
}
}
如下修改使用sptring-test的单元测试,需先添加spring-test的jar依赖,代码如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
如下采用sptring的单元测试实现:
import java.text.MessageFormat;
import lucky.ssmm.sys.model.User;
import lucky.ssmm.sys.service.UserServiceI;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)// 类似extends SpringJUnit4ClassRunner
@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" })
public class TestSpringMybatis {
private UserServiceI userService;
public UserServiceI getUserService() {
return userService;
}
@Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
}
@Test
public void test1() {
User u = userService.getUserById("0");
System.out.println(MessageFormat.format("获取的用户{0}", u.getName()));
}
}
以上已经测试完spring+mybatis的整合,如下开始添加springmvc的依赖spring-webmvc。。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
添加完之后,需要增加spring-mvc的配置,在src/main/resources添加spring-mvc.xml的配置:
1.添加spring自动扫描controller包的配置:
<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="lucky.ssmm" />
2.添加spring返回json的配置信息:
<!-- 避免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>
2.1由于使用了
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
的json插件,所以还需添加如下依赖:(jackson-mapper-asl)
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
3.固定的springmvc配置,如下添加即可:
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean>
4.添加模型视图的前后缀配置:
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />
5.添加文件上传的配置信息:
<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>
5.1由于使用了文件上传的功能,所以还需要添加apache的commons-fileupload的依赖包:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
三、整合springmvc,如要使用springmvc,肯定是在项目启动的时候使用的,所以必须配置到web.xml中。
1.首先定义spring的配置文件:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
2.添加字符集过滤器:
<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>
3.添加spring的监听器,固定写好:
<listener>
<!--description>spring监听器</description-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
4.添加spring防内存溢出,不是必须项:
<!-- 防止spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
5.重点。。。。配置springmvc的servlet。。。
<!-- 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>
6.配置session超时:
<!-- 配置session超时时间,单位分钟 -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
如上即算整合完毕。。。
编写页面测试controller。。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>${user.name}
</body>
</html>
添加controller方法:新建lucky.ssmm.sys.controller包并添加UserController.java的类:
import javax.servlet.http.HttpServletRequest;
import lucky.ssmm.sys.model.User;
import lucky.ssmm.sys.service.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/userController")
public class UserController {
private UserServiceI userService;
public UserServiceI getUserService() {
return userService;
}
@Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
}
@RequestMapping("/showUser")
public String showUser(String id, HttpServletRequest request) {
User u = userService.getUserById(id);
return "showUser";
}
}
如上由于是HttpServletRequest所以还需添加javax.servlet的相关依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
如上,测试springmvc的环境也完成,所以将系统部署到tomcat中启动,检查是否有问题。
经测试发现:spring-mvc.xml的该配置的类找不到。所以就更新了maven的依赖,换做其他依赖配置。
错误配置:
<!-- 避免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>
修改后:
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
并修改maven依赖,去除之前添加的jackson-mapper-asl的依赖,添加如下依赖:
原:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
修改后:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${com.fasterxml.jackson.core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${com.fasterxml.jackson.core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${com.fasterxml.jackson.core.version}</version>
</dependency>
修改后,再次启动服务,即可正常运行。。。。
打开测试页面:http://localhost:8080/luckyssmm/userController/showUser.do?id=0,检查
运行时发现${user.name}竟然没有解析,,通过检查修改了jsp页面:加了这个属性:isELIgnored="false"
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
再次测试,已正常。。
四、修改支持Springmvc构造RESTful设置。。
修改controller的方法为如下即可:
@RequestMapping("/showUser/{id}")
public String showUser(@PathVariable String id, HttpServletRequest request) {
User u = userService.getUserById(id);
request.setAttribute("user", u);
return "showUser";
}
五、配置log4j
添加log4j的jar依赖:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
配置log4j.properties:
log4j.rootLogger=DEBUG,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c]%m%n
log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=mybatis.log
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
在项目中尽量少用sysout等输出语句,最后改用log输出,所以如下添加一个log4e的eclipse插件:
更新站点:http://log4e.jayefem.de/update
使用:右键代码Log4e即可自动生成。。
1.添加fastjson的jar依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.6</version>
</dependency>
通过该插件可以方便输出对象信息等。
使用如下:
logger.info(JSON.toJSONString(u));
需要格式化日期可用如下方式:
logger.info(JSON.toJSONStringWithDateFormat(u, "yyyy-MM-dd HH:mm:ss"));
六、修改mybatis的mapper配置
1.创建多表关联的配置:
(1.1),此配置实现的是N+1的sql查询关联,性能与效果不是很好,只是学习,不可作为正式开发使用
<resultMap id="UserResultMap" type="lucky.ssmm.sys.model.User"
extends="BaseResultMap">
<collection property="roleList" column="id" javaType="list"
select="selectUserRole">
</collection>
</resultMap>
<select id="selectUserRole" resultType="lucky.ssmm.sys.model.Role"
parameterType="java.lang.String">
SELECT
sys_role.id,
sys_role.office_id,
sys_role.`name`,
sys_role.enname,
sys_role.role_type,
sys_role.data_scope,
sys_role.is_sys,
sys_role.useable,
sys_role.create_by,
sys_role.create_date,
sys_role.update_by,
sys_role.update_date,
sys_role.remarks,
sys_role.del_flag
FROM
sys_role
LEFT JOIN sys_user_role
ON sys_role.id =
sys_user_role.role_id
<where>
<choose>
<when test="id != null and id !='' ">sys_user_role.user_id = #{id}</when>
<otherwise>1=2</otherwise>
</choose>
</where>
</select>
(1.2),推荐使用该方法,关联sql直接写好。
<resultMap type="lucky.ssmm.sys.model.User" id="UserResultMap2"
extends="BaseResultMap">
<collection property="roleList" javaType="list"
ofType="lucky.ssmm.sys.model.Role" >
<id property="id" column="role.id" />
<result column="role.name" property="name"/>
</collection>
</resultMap>
<select id="selectUserAll" resultMap="UserResultMap2">
SELECT
sys_user.id,
sys_user.company_id,
sys_user.office_id,
sys_user.login_name,
sys_user.`password`,
sys_user.`no`,
sys_user.`name`,
sys_user.email,
sys_user.phone,
sys_user.mobile,
sys_user.user_type,
sys_user.photo,
sys_user.login_ip,
sys_user.login_date,
sys_user.login_flag,
sys_user.create_by,
sys_user.create_date,
sys_user.update_by,
sys_user.update_date,
sys_user.remarks,
sys_user.del_flag,
sys_role.office_id,
sys_role.`name` 'role.name',
sys_role.enname 'role.enname',
sys_role.role_type,
sys_role.data_scope,
sys_role.is_sys,
sys_role.useable,
sys_role.create_by,
sys_role.create_date,
sys_role.update_by,
sys_role.update_date,
sys_role.remarks,
sys_role.del_flag,
sys_role.id 'role.id'
FROM
sys_user
JOIN sys_user_role ON
sys_user.id = sys_user_role.user_id
JOIN sys_role ON
sys_user_role.role_id = sys_user_role.user_id
</select>
如上两种方式还需在User中添加如下属性:
private List<Role> roleList = Lists.newArrayList(); // 拥有角色列表