纯Java配置SpringMvc整合Spring-Data-JPA
包结构
WebInitializer.java
package 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请求映射的/上 } }
SpringMVCconfig.java
package 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(); } }
RootConfig.java
package 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,JPAConfig.class,TransactionalConfig.class}) public class RootConfig { }
TransactionalConfig.java
package com.niugang; import javax.persistence.EntityManagerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * 事务配置文件 * * @author niugang * */ @Configuration @EnableTransactionManagement /* * 事务具体配置可以参考 @EnableTransactionManagement里面源码的配置 */ public class TransactionalConfig { @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory localContainerEntityManagerFactoryBean) { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(localContainerEntityManagerFactoryBean); return txManager; } }
JPAConfig.java
package com.niugang; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; @Configuration @EnableJpaRepositories public class JPAConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { // 设置是否生成DDL被已经被初始化后,创建/更新所有相关表 HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); // 扫描实体类所在包的 factory.setPackagesToScan("com.niugang.entity"); // factory.setEntityManagerFactoryInterface(EntityManagerFactory.class); factory.setDataSource(dataSource); return factory; } }
JdbcConfig.java
package 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; } }
entity
package com.niugang.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; //javax.persistence.Entity @Entity @Table(name="user") public class User { /** *mysql 自定生成主键 *指示持久性提供者必须分配使用数据库标识列的实体的主键 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id" ,insertable=false,updatable=false) private Integer id; /** * @Column中的name默认和字段名相同 */ @Column(name = "name") private String name; @Column(name = "age") private Integer age; @Column(name = "phone") private String phone; @Column(name = "password") private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getId() { return id; } public void setId(Integer 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; } }
dao
package com.niugang.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.niugang.entity.User; /** * JpaRepository springboot已经自动配置了,也已经注入数据源了 * @author niugang * */ @Repository public interface UserDao extends JpaRepository<User,Integer> { }
service
package com.niugang.service; import java.util.List; import javax.annotation.Resource; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.stereotype.Service; import com.niugang.dao.UserDao; import com.niugang.entity.User; @Service public class UserService { @Resource private UserDao userDao; /** * 查询全部 * * @return */ public List<User> queryList() { return userDao.findAll(); } /** * 保存 * * @param user */ @Transactional public void save(User user) { userDao.save(user); throw new RuntimeException("添加数据错误"); } /** * 添加对象集合 * @param users */ public void save(Iterable<User> users) { userDao.save(users); } /** * 根据id查询 * * @param id * @return */ public User get(int id) { return userDao.getOne(id); } /** * 删除 * * @param id */ public void delete(int id) { userDao.delete(id); } /** * page分页查询 * @return */ public Page<User> queryForPage(Integer page) { /** * PageRequest page起始页从0开始 */ PageRequest pageRequest = null; if (page== null) { pageRequest = new PageRequest(0, 4); } else { pageRequest = new PageRequest((page-1), 4); } Page<User> findAll = userDao.findAll(pageRequest); return findAll; } /** * 不分页排序查询 * @return */ public List<User> queryForSort(){ Order idOrder = new Order(Direction.DESC, "id"); /*List<Order> orders =new ArrayList<Order>(); orders.add(idOrder);*/ return userDao.findAll(new Sort(idOrder)); } }
controller
package com.niugang.controller; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.data.domain.Page; 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.UserService; /** * * @author niugang spring boot helloWrold */ @Controller public class IndexController { @Resource private UserService userService; @RequestMapping(value = "/") public String toIndex(){ return "redirect:index"; } /** * 跳转到登录页面 * * @param map * @return */ @RequestMapping(value = "/login", method = RequestMethod.GET) public String toLogin(ModelMap map) { return "login"; } /** * 登录信息校验 * * @param map * @return */ @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(ModelMap map, String name,String password) { if (StringUtils.isNotBlank(name)&& !name.equals("admin") && StringUtils.isNotBlank(password) && !password.equals("123456")) { map.put("errorMessage", "用户名或密码错误"); return "login"; } return "redirect:index"; } /** * 跳转到index页面 * * @return */ @RequestMapping(value = "/index") public String index(ModelMap map) { List<User> list = userService.queryList(); map.put("users", list); return "index"; } /** * 详情页面 * @param id * @param map * @return */ @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"; } /** * 删除 * @param id * @return */ @RequestMapping(value = "/delete/{id}") public String delete(@PathVariable(value="id") Integer id){ userService.delete(id); return "redirect:/index"; } /** * 跳转到添加页面 * @param map * @return */ @RequestMapping(value = "/save",method = RequestMethod.GET) public String toSave(ModelMap map) { return "add"; } /** * 保存添加信息 * @param user * @return */ @RequestMapping(value = "/save",method = RequestMethod.POST) public String save(User user,ModelMap map){ if(StringUtils.isBlank(user.getName())){ map.put("error", "用户名不能为空"); return "add"; } if(user.getAge()==null){ map.put("error", "非法年龄"); return "add"; } if(StringUtils.isBlank(user.getPhone())){ map.put("error", "手机号不能为空"); return "add"; } user.setPassword("123456"); userService.save(user); return "redirect:/index"; } @RequestMapping(value = "/indexPage") public String indexPage(ModelMap map,Integer page) { Page<User> queryForPage = userService.queryForPage(page); map.put("page", queryForPage); return "index"; } }
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style type="text/css"> table { border-collapse: collapse; margin: 0 auto; } table, td, th { border: 1px solid black; padding: 15px; } </style> </head> <body> <input type="button" value="添加" onclick="add();"> <a href="indexPage">分页查询</a> <table> <thead> <tr> <th>用户名</th> <th>年龄</th> <th>电话</th> <th>操作</th> </tr> </thead> <tbody> <#if users??> <#list users as user> <tr> <td>${user.name}</td> <td>${user.age}</td> <td>${user.phone}</td> <td><a href="javascript:void(0)" onclick="edit('${user.id}')" >编辑</a> <a href="javascript:void(0)" onclick="del('${user.id}')">删除</a> <a href="javascript:void(0)" onclick="detail('${user.id}')">详情</a> </td> </tr> </#list> </#if> <#if page??> <#list page.content as user> <tr> <td>${user.name}</td> <td>${user.age}</td> <td>${user.phone}</td> <td><a href="javascript:void(0)" onclick="edit('${user.id}')" >编辑</a> <a href="javascript:void(0)" onclick="del('${user.id}')">删除</a> <a href="javascript:void(0)" onclick="detail('${user.id}')">详情</a> </td> </tr> </#list> <tr> <td>总页数</td><td>${page.totalPages}</td> <td>当前页面</td><td>${page.number+1}</td> <td>总记录数</td><td>${page.totalElements}</td> </tr> <tr> <td> <#if (page.totalPages gt page.number+1)> <a href="indexPage?page=${page.number+2}">下一页</a> <#if (page.number !=0)> <a href="indexPage?page=${page.number}">上一页</a> </#if> </#if> <#if (page.totalPages lt page.number+2)> <a href="indexPage?page=${page.number}">上一页</a> </#if> </td> </tr> </#if> </tbody> </table> <script type="text/javascript"> function edit(id){ alert(id); } function del(id){ var flag=confirm("你确定要删除此选项吗"); if(flag==true){ window.location.href="delete/"+id; } } function detail(id){ window.location.href="detail/"+id; } function add(){ window.location.href="save"; } </script> </body> </html>
detail.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h2>详情页面</h2> 用户名:<input type="text" readonly value="${user.name!''}"> 年龄:<input type="text" readonly value="${user.age!''}"> 电话:<input type="text" readonly value="${user.phone!''}"> </body> </html>
add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h2>添加</h2> <#if error??> ${error} </#if> <form action="save" method='post'> 用户名:<input type="text" name="name"><p> 年龄:<input type="text" name="age"><p> 手机号:<input type="text" name="phone"><p> <input type="submit" value="提交"> </form> </body> </html>
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>
运行结果
微信公众号