您的位置:首页 > 编程语言 > Java开发

纯Java配置SpringMvc&Freemarker&MyBatis

2018-03-05 18:55 447 查看
主要用于纯java整合mybatis,web成用freemarker,页面和之前博客一样



1.pom.xml2.resources文件夹 jdc.properties 与之前博客一样 log4j.properties 与之前博客一样 mybatis-configuration.xml:主要用于配置实体类对应的别名  <?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>
    <!--此文件主要用于配置别名  -->
    <typeAliases>
        <typeAlias alias="User" type="com.niugang.entity.User" />
    </typeAliases>
 
</configuration>
mapper文件夹下放xml文件<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.niugang.dao.UserDao">
<resultMap id="BaseResultMap" type="User">
<result column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
<result column="phone" property="phone" />
</resultMap>
     
<!--查询字段 -->
<sql id="Base_Column_List">
id, name, age,phone
</sql>
<!-- 查询条件 -->
<sql id="queryCondition">
<where>
<if test="id!=null">
and id=#{id}
</if>
<if test="name!=null">
and name=#{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
<if test="phone!=null">
and phone=#{phone}
</if>
</where>
</sql>

<select id="queryList" resultMap="BaseResultMap" parameterType="User">
select
<include refid="Base_Column_List" />
from user
<include refid="queryCondition" />
</select>
<insert id="save" parameterType="User">
insert into user (name,password,age,phone)
values(#{name},#{password},#{age},#{phone})
</insert>
<delete id="delete" parameterType="int">
delete from user where id =#{id}
</delete>
<select id="get" parameterType="int" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id =#{id}
</select>
</mapper>3.WebInitializer .javapackage com.niugang;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/** * 相当于web.xml * AbstractAnnotationConfigDispatcherServletInitializer 源码里面有解释 * 这个是注解形式注册 * DispatcherServlet容器 * @author niugang * */public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { /** * 源码里面与对此方法的解释 配置applicationContext */ @Override protected Class<?>[] getRootConfigClasses() {//指定上下文配置类 return new Class<?>[]{RootConfig.class}; }
@Override protected Class<?>[] getServletConfigClasses() {//指定sprinfgmvc配置类 return new Class<?>[]{SpringMVCconfig.class} ; }
@Override protected String[] getServletMappings() { return new String[]{"/"}; //将DispatcherServlet请求映射的/上 }4.SpringMVCconfig.javapackage com.niugang;
import javax.servlet.ServletContext;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;import org.springframework.web.servlet.view.freemarker.FreeMarkerView;import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;import freemarker.cache.WebappTemplateLoader;
/** * * @author niugang springmvc java配置文件 */@Configuration // 说明此类为配置文件类@EnableWebMvc // 开启springmvc@ComponentScan("com.niugang") // 组件扫描public class SpringMVCconfig extends WebMvcConfigurerAdapter{ /** * freemaker作为视图解析器 * * @return */ @Bean public FreeMarkerViewResolver viewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setContentType("text/html;charset=utf-8"); /* * 如果注释 resolver.setPrefix("/WEB-INF/views/"); * 下面config需要tplCfg.setTemplateLoader(new * WebappTemplateLoader(servletContext,"/WEB-INF/views/")); */ resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".html"); resolver.setViewClass(FreeMarkerView.class); return resolver; } /** * 配置freemarker * @param servletContext * @return */ @Bean public FreeMarkerConfigurer freeMarkerConfigurer(ServletContext servletContext) { FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); @SuppressWarnings("deprecation") freemarker.template.Configuration tplCfg = new freemarker.template.Configuration(); tplCfg.setDefaultEncoding("UTF-8"); tplCfg.setTemplateLoader(new WebappTemplateLoader(servletContext)); freeMarkerConfigurer.setConfiguration(tplCfg); return freeMarkerConfigurer; }
/** * 配置静态资源的处理 对静态资源的请求转发到容器缺省的servlet,而不使用DispatcherServlet */ @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }}5.RootConfig.javapackage com.niugang;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.ComponentScan.Filter;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.FilterType;import org.springframework.context.annotation.Import;import org.springframework.web.servlet.config.annotation.EnableWebMvc;/** * 上下文配置 * @author niugang * */@Configuration@ComponentScan(basePackages={"con.niugang"}, excludeFilters={ @Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class) } )//在上下文中引入jdbc配置文件,事务配置文件@Import({JdbcConfig.class,MybatisConfig.class,TransactionalConfig.class})public class RootConfig { }6.JdbcConfig.javapackage com.niugang;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * jdbc配置文件
 * 
 * @author niugang
 *
 */
@Configuration
/*
 * 
 * @PropertySource注解如何使用,源码里面有例子 即从配置文件中如何获取获取值,源码里面也有解释
 *
 */

@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Autowired
private Environment env;

/**
* 配置数据源

* @return
*/
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getProperty("url"));
dataSource.setDriverClassName(env.getProperty("driverName"));
dataSource.setUsername(env.getProperty("datausername"));
dataSource.setPassword(env.getProperty("password"));
return dataSource;
}

}
7.MybatisConfig.javapackage com.niugang;
import java.io.IOException;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
 * MyBatis配置文件
 * @author niugang
 *
 */
@Configuration
//Use this annotation to register MyBatis mapper interfaces when using Java
//源码里面也有样例

@MapperScan(basePackages="com.niugang.dao")
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();  
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();  
        sqlSessionFactoryBean.setDataSource(dataSource);  
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-configuration.xml"));
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:mapper/*.xml"));  
return sqlSessionFactoryBean;
}

}
8.TransactionalConfig.java

package com.niugang;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 事务配置文件
 * 
 * @author niugang
 *
 */
@Configuration
@EnableTransactionManagement
/*
 * 事务具体配置可以参考 @EnableTransactionManagement里面源码的配置
 */
public class TransactionalConfig {

@Bean
public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}

8.entitypackage com.niugang.entity;
public class User { private int id; private String name; private Integer age; private String phone; private String password;
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
}9.dao层package com.niugang.dao;import java.util.List;import org.springframework.stereotype.Repository;import com.niugang.entity.User;@Repositorypublic interface UserDao { List<User> queryList(User user);
User get(Integer id);
void save(User user);
void delete(Integer id);
}10.service层package com.niugang.service;
import java.util.List;
import javax.annotation.Resource;import javax.transaction.Transactional;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;
import com.niugang.dao.UserDao;import com.niugang.entity.User;
@Servicepublic class UserService {
private static Logger logger = LoggerFactory.getLogger(UserService.class); @Resource private UserDao userDao;
public List<User> queryList(User user) { logger.info("访问queryList方法"); return userDao.queryList(user); } @Transactional public void save(User user) { logger.info("访问save方法"); userDao.save(user); }
public User get(Integer id) { logger.info("访问get方法"); return userDao.get(id); }
public void delete(Integer id) { logger.info("访问delete方法"); userDao.delete(id); }
}11.controllerpackage com.niugang.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.niugang.entity.User;import com.niugang.service.IndexService;import com.niugang.service.UserService;
@Controllerpublic class IndexController {
@Autowired @Qualifier("indexService") //private IndexService indexService;
@Resource private UserService userService; /** * 默认访问的路径 * * @return */ @RequestMapping(value = "/", method = RequestMethod.GET) public String toindex() { return "redirect:index"; }
@RequestMapping(value = "index", method = RequestMethod.GET) public String index(ModelMap map) { map.put("msg", indexService.printMsg()); return "index"; }
@RequestMapping(value = "error") public void error() { throw new RuntimeException("哎呀出错了"); }
@RequestMapping(value = "/list") public String list(ModelMap map) { List<User> list = userService.queryList(null); map.put("users", list); return "list"; }@RequestMapping(value = "/detail/{id}") public String detail(@PathVariable(value = "id") Integer id, ModelMap map) { User user = userService.get(id); map.put("user", user); return "detail"; }
@RequestMapping(value = "toAdd") public String toAdd() { return "add"; }
@RequestMapping(value = "/save") public String save(User user, ModelMap map) { user.setPassword("123456"); userService.save(user); return "redirect:/index"; }
}11.aop包

WebLogAscept.java 用于web层日志记录package com.niugang.aop;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.EnableAspectJAutoProxy;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;
/** * * @author niugang * */@Aspect@Component@EnableAspectJAutoProxy // 启用aoppublic class WebLogAscept {
private Logger logger = LoggerFactory.getLogger(WebLogAscept.class); /** * 方式一 @Pointcut("execution(public * com.niugang.controller..*.*(..))") * public void WebLogAscept() { } * * @Around(value = "WebLogAscept()") public Object * aroundAdvice(ProceedingJoinPoint pjd) throws Throwable { * logger.info("请求前"); Object proceed = pjd.proceed(); * logger.info("请求后"); * * return proceed; //必须得有返回值,否则不能往下执行 } **/ /** * 方式二 在增强上配置匿名切点 * * @param pjd * @return * @throws Throwable */ @Around("execution(public * com.niugang.controller..*.*(..))") public Object aroundAdvice(ProceedingJoinPoint pjd) throws Throwable { logger.info("请求前"); RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes r = (ServletRequestAttributes) requestAttributes; HttpServletRequest request = r.getRequest(); logger.info("url is {}", request.getRequestURL()); logger.info("request params is {}", request.getParameterMap() == null ? "" : request.getParameterMap()); Object proceed = pjd.proceed(); logger.info("请求后");
return proceed; // 必须得有返回值,否则不能往下执行 }
}ExceptionControllerAscept.java 用于异常处理package com.niugang.aop;
import java.io.IOException;
import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Aspect;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.EnableAspectJAutoProxy;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;
/** * controller层统一异常处理 * * @author niugang * */@Aspect@Component@EnableAspectJAutoProxypublic class ExceptionControllerAscept {
private Logger logger = LoggerFactory.getLogger(ExceptionControllerAscept.class); /** * 匿名切点的方式 * @param ex * @throws ServletException * @throws IOException */ @AfterThrowing(value = "execution(public * com.niugang.controller..*.*(..))", throwing = "ex") public ModelAndView aroundAdvice(Exception ex) throws ServletException, IOException {
              /*RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes r = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = r.getRequest();
HttpServletResponse response = r.getResponse();*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
//第一如果是 RuntimeException
if (ex instanceof RuntimeException) {
logger.error("抛出运行时异常{}", ex.getMessage());
modelAndView.addObject("errorMsg", ex.getMessage());
return modelAndView;
}
modelAndView.addObject("errorMsg", "未知异常");
return modelAndView;

}       /*     //自己平台测试用ModelAndView不行实现要想的功能,所以如果上面不行用下面返回jsp代码     @AfterThrowing(value = "execution(public * com.niugang.controller..*.*(..))", throwing = "ex")
public void aroundAdvice(Exception ex) throws ServletException, IOException {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes r = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = r.getRequest();
HttpServletResponse response = r.getResponse();
//第一如果是 RuntimeException
if (ex instanceof RuntimeException) {
logger.error("抛出运行时异常{}", ex.getMessage());
request.setAttribute("errorMsg", ex.getMessage());
//跳转到错误页面
request.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(request, response);
}
}      */
}可能会用上如果用ModelAndView返回freemarker渲染的htmk没有到达预期就用error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    ${errorMsg}
    <a href="javascript:history.back(-1)">返回</a>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息