基于springmvc mybatis junit搭建分工程,分模块的web工程框架(三)
来源:互联网 发布:矩阵的f范数怎么求 编辑:程序博客网 时间:2024/04/30 13:17
1在src/main/java下
BaseController.java统一处理异常
package com.macow.home.first.controller;import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.ExceptionHandler;import com.macow.home.first.msg.CommonResonse;public abstract class BaseController {/** * 异常统一管理 第一种方式: implements HandlerExceptionResolver 第二种方式: @ExceptionHandler * * @param request * @param e * @return */@ExceptionHandlerpublic CommonResonse<String> exception(HttpServletRequest request,Exception e) {CommonResonse<String> resp = new CommonResonse<String>();resp.setRespCode(e.getMessage());resp.setRespMsg(e.getMessage());// 添加自己的异常处理逻辑,如日志记录 request.setAttribute("exceptionMessage", e.getMessage());// 根据不同的异常类型进行不同处理return resp;}}
UserController.java控制器
package com.macow.home.first.controller;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.macow.home.first.entity.User;import com.macow.home.first.msg.CommonResonse;import com.macow.home.first.service.UserService;import com.macow.home.first.vo.UserVo;@Controller@RequestMapping("/user")public class UserController extends BaseController{@Resourceprivate UserService userService;@RequestMapping("/showUser")@ResponseBodypublic CommonResonse<User> select(UserVo userVo) {CommonResonse<User> response=new CommonResonse<User>();List<User> uList = this.userService.select(userVo);response.setResult(uList);return response;}}AspectShow.java切面类
package com.macow.home.first.controller.aop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.springframework.stereotype.Component;/** * 切面 * */@Componentpublic class AspectShow {public void doAfter(JoinPoint jp) {System.out.println("----------->>>Ending method:<<<---------- "+ jp.getTarget().getClass().getName() + "."+ jp.getSignature().getName());}public Object doAround(ProceedingJoinPoint pjp) throws Throwable {long time = System.currentTimeMillis();Object retVal = pjp.proceed();time = System.currentTimeMillis() - time;System.out.println("--------->>>process time: " + time + " ms");return retVal;}public void doBefore(JoinPoint jp) {System.out.println("----------->>>Begin method:<<<---------- "+ jp.getTarget().getClass().getName() + "."+ jp.getSignature().getName());}public void doThrowing(JoinPoint jp, Throwable ex) {System.out.println("----------->>>method Throwable<<<----------" + jp.getTarget().getClass().getName()+ "." + jp.getSignature().getName() + " throw exception");System.out.println("----------->>>Throwable: "+ex.getMessage()+"<<<----------");}}
2在src/main/resources
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" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><import resource="spring-dao.xml" /><import resource="spring-service.xml" /><import resource="spring-mvc.xml" /><beans profile="dev" ><context:property-placeholder location="classpath*:jdbc-dev.properties" /></beans><beans profile="sit" ><context:property-placeholder location="classpath*:jdbc-sit.properties" /></beans></beans>spring-mvc.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:task="http://www.springframework.org/schema/task"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --><context:component-scan base-package="com.macow.home.first.*" /><!--避免IE执行AJAX时,返回JSON出现下载文件 --><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>text/plain;charset=UTF-8</value><value>text/json;charset=UTF-8</value></list></property></bean><!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="mappingJacksonHttpMessageConverter" /></list></property></bean><!-- 定义跳转的文件的前后缀 ,视图模式配置 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean><!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 默认编码 --><property name="defaultEncoding" value="utf-8" /><!-- 文件大小最大值 --><property name="maxUploadSize" value="10485760" /><!-- 内存中的最大值 --><property name="maxInMemorySize" value="40960" /></bean><!-- 默认的注解映射的支持 --> <!-- <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> --><!-- <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!--不设置则默认为classpath下的 ValidationMessages.properties --> <property name="validationMessageSource" ref="validatemessageSource"/> </bean> <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:ValidationMessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean> <!-- 拦截器 --> <!-- <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.wei.controller.intercepter.ValidateParamIntercepter" /> </mvc:interceptor> </mvc:interceptors> --> <aop:aspectj-autoproxy/> <aop:config proxy-target-class="true"> <aop:aspect ref="aspectShow"> <!--配置com.wei.controller包下所有类或接口的所有方法--> <aop:pointcut id="aopService" expression="execution( * com.macow.home.first.controller..*(..))" /> <aop:before pointcut-ref="aopService" method="doBefore"/> <aop:after pointcut-ref="aopService" method="doAfter"/> <aop:around pointcut-ref="aopService" method="doAround"/> <aop:after-throwing pointcut-ref="aopService" method="doThrowing" throwing="ex"/> </aop:aspect> </aop:config> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans>
logback.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration><configuration><!-- 常量:指定日志路径 --><property name="LOG_DIR" value="D:logs/" /><!-- 常量:应用名称 --><property name="APP_NAME" value="wei-web" /><!-- 控制台输出 --><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><layout class="ch.qos.logback.classic.PatternLayout"><Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{0} line%L - %msg%n</Pattern></layout><Encoding>UTF-8</Encoding></appender><!-- 默认的业务日志 --><root level="debug"><appender-ref ref="STDOUT" /></root></configuration>
ValidationMessages.properties
password.is.null=PWD can not null
3在src/test/java下
package com.macow.home.first.controller;import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.macow.home.first.entity.User;import com.macow.home.first.msg.CommonResonse;import com.macow.home.first.vo.UserVo;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("/spring-context.xml")@ActiveProfiles(value = "dev")public class UserControllerTest {private Logger logger = LoggerFactory.getLogger(this.getClass());@AutowiredUserController userController;@Testpublic void testSelect() {UserVo user = new UserVo();user.setName("小白");user.setPassword("2313213");CommonResonse<User> selectList = userController.select(user);for (User u : selectList.getResult()) {logger.info("---------->" + u.getName() + "<---------");}logger.info("---------->testSelect end<---------");}}
4在src/test/resources下
jdbc-dev.properties
#dbds.driverClassName=org.postgresql.Driverds.url=jdbc:postgresql://localhost:5432/postgresds.username=postgresds.password=11111111#ds.url=jdbc:postgresql://10.20.130.25:7440/toaasset#ds.username=assetopr#ds.password=paic1234#durid datasourceds.initialSize=2ds.minIdle=5ds.maxActive=5#ds.filters=stat,configds.filters=statds.maxWait=60000ds.timeBetweenEvictionRunsMillis=60000ds.minEvictableIdleTimeMillis=300000ds.validationQuery=SELECT 1ds.testWhileIdle=trueds.testOnBorrow=falseds.testOnReturn=falsejdbc-sit.properties和上面的内容一样
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" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><import resource="spring-dao.xml" /><import resource="spring-service.xml" /><import resource="spring-mvc.xml" /><beans profile="dev"><context:property-placeholder location="classpath*:jdbc-dev.properties" /></beans><beans profile="sit"><context:property-placeholder location="classpath*:jdbc-sit.properties" /></beans></beans>
5web.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_3_0.xsd"version="3.0"><display-name>macow-web</display-name><!-- Spring和mybatis的配置文件 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context.xml</param-value></context-param><!-- 切换环境 --><context-param> <param-name>spring.profiles.active</param-name> <param-value>sit</param-value> </context-param> <!-- 编码过滤器 --><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><async-supported>true</async-supported><init-param><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><!-- Spring监听器 --><listener><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><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><async-supported>true</async-supported></servlet><servlet-mapping><servlet-name>SpringMVC</servlet-name><!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --><url-pattern>/</url-pattern></servlet-mapping><welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list></web-app>
工程结构图
6浏览器端测试是否发布成功
直接访问http://localhost:8080/macow-web/user/showUser
1 0
- 基于springmvc mybatis junit搭建分工程,分模块的web工程框架(三)
- 基于springmvc mybatis junit搭建分工程,分模块的web工程框架(一)
- 基于springmvc mybatis junit搭建分工程,分模块的web工程框架(二)
- SpringMVC+Spring+Mybatis三大框架的整合流程(基于maven工程)
- Spring+SpringMVC+MyBatis框架一个简单工程的搭建实例
- maven 分模块 分工程构建项目
- maven 分模块、分工程管理
- Maven分模块分工程管理
- Maven 分模块、分工程管理
- 快速搭建简单的springMvc框架的动态web工程
- 建立基于maven 的springmvc mybatis工程
- 搭建Spring+SpringMVC+MyBatis工程
- MyBatis+JUnit测试Dao(Mapper)的用例实现( 不启动web工程 且 未使用SpringMVC管理MyBatis时 )
- 如何搭建SSM(SpringMvc+mybatis+Spring)java web工程
- SSM(SpringMvc+mybatis+Spring)java web搭建工程
- maven搭建ssm分模块框架+dubbo (myeclipse版) (三)
- 基于MAVEN的SSM(SPRING,SPRINGMVC,MYBATIS)整合的WEB工程
- eclipse搭建maven web 工程,和集成springmvc+mybatis的一些问题
- HTTP的基本原理
- Iptables 使用方法
- objc非主流代码技巧
- 谈谈yii2-gii如何自定义模板
- SSH密钥认证原理
- 基于springmvc mybatis junit搭建分工程,分模块的web工程框架(三)
- Delphi COM编程技术六(DCOM技术)
- iOS应用程序状态图
- MFC界面库BCGControlBar新版功能详解四:示例和其他功能
- 我已经写了48年代码了,我感觉我还能写下去
- okhttp是android平台最好的网络库
- cobar实现mysql分片及分片集之内双节点之间的高可用
- window下使用命令行创建symfony项目
- 如何优化C语言代码(程序员必读)