资讯专栏INFORMATION COLUMN

Struts 整合 SpringMVC

Scliang / 990人阅读

Struts 整合 SpringMVC 过程:这篇文章是我在整合过程中所做的记录和笔记

web.xml :筛选器机制过滤

原机制是拦截了所有 url ,即 /*

新机制为了将 structs2 的 url 与 SpringMVC 的 url 区分开来,则修改了拦截属性


   
        struts2
        /*
        REQUEST  
        FORWARD 
    
    
    

   
        struts2
        *.action
        REQUEST 
        FORWARD 
    
    
        struts2
        *.jsp
        REQUEST  
        FORWARD 
    
web.xml struts 整合 SpringMVC

     
    
        contextClass
        
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        
    
    
    
        contextConfigLocation
        spring.config.AppConfig
    
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextClass
            
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            
        
        
        
            contextConfigLocation
            spring.config.MvcConfig
        
    
    
    
        dispatcher
        /km/*
    
    

基于web.xml配置文件的配置属性,需要配置两个Config类:【两个配置的区别】

AppConfig.java

@Configuration
@Import({KmAppConfig.class})
public class AppConfig {

}

MvcConfig.java

@Configuration
@Import({KmMvcConfig.class})
public class MvcConfig {

}

基于Config类,配置具体的应用Config

KmAppConfig.java

@Configuration
@ComponentScan(basePackages = "com.teemlink.km.") //扫描包体
public class KmAppConfig implements TransactionManagementConfigurer,ApplicationContextAware {
private static ApplicationContext applicationContext;

@Autowired
private DataSource dataSource;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    KmAppConfig.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
    return applicationContext;
}

@Bean
public DataSource dataSource() {
    //如何读取配置资源的数据?
    String url = "jdbc:jtds:sqlserver://192.168.80.47:1433/nj_km_dev";
    String username = "sa";
    String password = "teemlink";
    DriverManagerDataSource ds = new DriverManagerDataSource(url, username, password);
    ds.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
    return ds;
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
    return new JdbcTemplate(dataSource);
    
}
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
    return new DataSourceTransactionManager(dataSource);
}
}

KmMvcConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.teemlink.km.**.controller")
public class KmMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

基于SpringMVC 的 Controller - Service - Dao 框架

AbstractBaseController

/**
 * 抽象的RESTful控制器基类
 * @author Happy
 *
 */
@RestController
public abstract class AbstractBaseController {
    
    @Autowired  
    protected HttpServletRequest request;
    
    @Autowired
    protected HttpSession session;
    
    protected Resource success(String errmsg, Object data) {
        return new Resource(0, errmsg, data, null);
    }
    
    protected Resource error(int errcode, String errmsg, Collection errors) {
        return new Resource(errcode, errmsg, null, errors);
    }
    private Resource resourceValue;
    public Resource getResourceValue() {
        return resourceValue;
    }
    public void setResourceValue(Resource resourceValue) {
        this.resourceValue = resourceValue;
    }
    
    /**
     * 资源未找到的异常,返回404的状态,且返回错误信息。
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Resource resourceNotFound(RuntimeException e) {
        return error(404, "Not Found", null);
    }
    /**
     * 运行时异常,服务器错误,返回500状态,返回服务器错误信息。
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Resource error(RuntimeException e) {
        return error(500, "Server Error", null);
    }
    
    /**
     * Restful 接口返回的资源对象
     * 
     */
    @JsonInclude(Include.NON_EMPTY)
    public class Resource implements Serializable {
        private static final long serialVersionUID = 2315158311944949185L;
        private int errcode;
        private String errmsg;
        private Object data;
        private Collection errors;
        public Resource() {}
        
        public Resource(int errcode, String errmsg, Object data, Collection errors) {
            this.errcode = errcode;
            this.errmsg = errmsg;
            this.data = data;
            this.errors = errors;
        }
        public int getErrcode() {
            return errcode;
        }
        public void setErrcode(int errcode) {
            this.errcode = errcode;
        }
        public String getErrmsg() {
            return errmsg;
        }
        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }
        public Object getData() {
            return data;
        }
        public void setData(Object data) {
            this.data = data;
        }
        public Collection getErrors() {
            return errors;
        }
        public void setErrors(Collection errors) {
            this.errors = errors;
        }
    }
}

IService

/**
 *
 * @param 
 */
public interface IService {
    
    /**
     * 创建实例
     * @param entity
     * @return
     * @throws Exception
     */
    public IEntity create(IEntity entity) throws Exception;
    
    /**
     * 更新实例
     * @param entity
     * @return
     * @throws Exception
     */
    public IEntity update(IEntity entity) throws Exception;
    
    /**
     * 根据主键获取实例
     * @param pk
     * @return
     * @throws Exception
     */
    public IEntity find(String pk) throws Exception;
    
    /**
     * 删除实例
     * @param pk
     * @throws Exception
     */
    public void delete(String pk) throws Exception;
    
    /**
     * 批量删除实例
     * @param pk
     * @throws Exception
     */
    public void delete(String[] pk) throws Exception;
    
}

AbstractBaseService

/**
 * 抽象的业务基类
 *
 */
public abstract class AbstractBaseService {
    
    /**
     * @return the dao
     */
    public abstract IDAO getDao();  

    @Transactional
    public IEntity create(IEntity entity) throws Exception {
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(UUID.randomUUID().toString());
        }
        return getDao().create(entity);
    }
    @Transactional
    public IEntity update(IEntity entity) throws Exception {
        return getDao().update(entity);
    }
    public IEntity find(String pk) throws Exception {
        return getDao().find(pk);
    }
    @Transactional
    public void delete(String pk) throws Exception {
        getDao().remove(pk);
    }
    @Transactional
    public void delete(String[] pks) throws Exception {
        for (int i = 0; i < pks.length; i++) {
            getDao().remove(pks[i]);
        }
    }
}

IDAO

/**
 *
 */
public interface IDAO {
    
    public IEntity create(IEntity entity) throws Exception;
    public void remove(String pk) throws Exception;
    public IEntity update(IEntity entity) throws Exception;
    public IEntity find(String id) throws Exception;
    
}

AbstractJdbcBaseDAO

/**
 * 基于JDBC方式的DAO抽象实现,依赖Spring的JdbcTemplate和事务管理支持
 *
 */
public abstract class AbstractJdbcBaseDAO {
    
    
    @Autowired
    public JdbcTemplate jdbcTemplate;
    
    protected String tableName;
    
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    /**
     * 构建分页sql
     * @param sql
     * @param page
     * @param lines
     * @param orderbyFile
     * @param orderbyMode
     * @return
     * @throws SQLException
     */
    protected abstract String buildLimitString(String sql, int page, int lines,
            String orderbyFile, String orderbyMode) throws SQLException ;
    
    
    /**
     * 获取数据库Schema
     * @return
     */
//    protected abstract String getSchema();
    
    /**
     * 获取表名
     * @return
     */
    protected String getTableName(){
        return this.tableName;
    }
    
    /**
     * 获取完整表名
     * @return
     */
    public String getFullTableName() {
        return getTableName().toUpperCase();
    }
    
    
}

测试框架

基本测试框架

 /**
 * 单元测试基类,基于Spring提供bean组件的自动扫描装配和事务支持
 *
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = KmAppConfig.class)
@Transactional
public class BaseJunit4SpringRunnerTest {

}  

具体实现:(以Disk为例)

public class DiskServiceTest extends BaseJunit4SpringRunnerTest {
    
    @Autowired
    DiskService service;
    
    @Before
    public void setUp() throws Exception {
        
    }
    @After
    public void tearDown() throws Exception {
    }
    
    @Test
    public void testFind() throws Exception{
        Disk disk = (Disk) service.find("1");
        Assert.assertNotNull(disk);
    }
    
    @Test
    @Commit
    public void testCreate() throws Exception{
        Disk disk = new Disk();
        disk.setName("abc");
        disk.setType(1);
        disk.setOrderNo(0);
        disk.setOwnerId("123123");
        service.create(disk);
        Assert.assertNotNull(disk.getId());
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67437.html

相关文章

  • Java3y文章目录导航

    摘要:前言由于写的文章已经是有点多了,为了自己和大家的检索方便,于是我就做了这么一个博客导航。 前言 由于写的文章已经是有点多了,为了自己和大家的检索方便,于是我就做了这么一个博客导航。 由于更新比较频繁,因此隔一段时间才会更新目录导航哦~想要获取最新原创的技术文章欢迎关注我的公众号:Java3y Java3y文章目录导航 Java基础 泛型就这么简单 注解就这么简单 Druid数据库连接池...

    KevinYan 评论0 收藏0
  • SpringMVCSpringMVC启动初始化过程

    摘要:当容器启动或终止应用时,会触发事件,该事件由来处理。监听器的作用就是启动容器时,自动装配的配置信息。初始化在架构中,负责请求分发,起到控制器的作用。   公司项目使用 struts2 作为控制层框架,为了实现前后端分离,计划将 struts2 切换为 SpringMVC ,因此,这段时间都在学习新的框架,《Spring实战》是一本好书,里面对 Spring 的原理实现以及应用都说得很透...

    Bowman_han 评论0 收藏0
  • 面试题:SpringMVCStruts2的区别

    摘要:的入口是,而是这里要指出,和是不同的。以前认为是的一种特殊,这就导致了二者的机制不同,这里就牵涉到和的区别了。开发效率和性能高于。的实现机制有以自己的机制,用的是独立的方式。 1、Struts2是类级别的拦截, 一个类对应一个request上下文,SpringMVC是方法级别的拦截,一个方法对应一个request上下文,而方法同时又跟一个url对应,所以说从架构本身上SpringMVC...

    isaced 评论0 收藏0
  • SpringMVC入门就这么简单

    摘要:也就是说映射器就是用于处理什么样的请求提交给处理。这和是一样的提交参数的用户名编号提交配置处理请求注册映射器包框架接收参数设置无参构造器,里边调用方法,传入要封装的对象这里的对象就表示已经封装好的了对象了。 什么是SpringMVC? SpringMVC是Spring家族的一员,Spring是将现在开发中流行的组件进行组合而成的一个框架!它用在基于MVC的表现层开发,类似于struts...

    SKYZACK 评论0 收藏0
  • Java后端

    摘要:,面向切面编程,中最主要的是用于事务方面的使用。目标达成后还会有去构建微服务,希望大家多多支持。原文地址手把手教程优雅的应用四手把手实现后端搭建第四期 SpringMVC 干货系列:从零搭建 SpringMVC+mybatis(四):Spring 两大核心之 AOP 学习 | 掘金技术征文 原本地址:SpringMVC 干货系列:从零搭建 SpringMVC+mybatis(四):Sp...

    joyvw 评论0 收藏0

发表评论

0条评论

Scliang

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<