基于springmvc mybatis junit搭建分工程,分模块的web工程框架(三)

11 篇文章 0 订阅
6 篇文章 0 订阅

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
	 */
	@ExceptionHandler
	public 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{
	@Resource
	private UserService userService;

	@RequestMapping("/showUser")
	@ResponseBody
	public 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;

/**
 * 切面
 * 
 */
@Component
public 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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://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.xsd
		http://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的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
	<bean
		class="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());

	@Autowired
	UserController userController;

	@Test
	public 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
#db
ds.driverClassName=org.postgresql.Driver
ds.url=jdbc:postgresql://localhost:5432/postgres
ds.username=postgres
ds.password=11111111
#ds.url=jdbc:postgresql://10.20.130.25:7440/toaasset
#ds.username=assetopr
#ds.password=paic1234
#durid datasource
ds.initialSize=2
ds.minIdle=5
ds.maxActive=5
#ds.filters=stat,config
ds.filters=stat
ds.maxWait=60000
ds.timeBetweenEvictionRunsMillis=60000
ds.minEvictableIdleTimeMillis=300000
ds.validationQuery=SELECT 1
ds.testWhileIdle=true
ds.testOnBorrow=false
ds.testOnReturn=false
jdbc-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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值