8-3智能商贸day2前端

it2024-07-09  78

1.课程介绍 1.准备Service层 2.集成SpringMVC(Controller层) 3.添加EasyUI展示主页面 4.完成一个数据的查询功能 5.完成删除功能 6.增加数据 7.修改数据 8.数据验证功能

springdatajpa的扩展–抽取

抽取一个BaseRepository – 写三个方法

@NoRepositoryBean public interface BaseRepository<T,ID extends Serializable> extends JpaRepository<T,ID>, JpaSpecificationExecutor<T> { //根据Query拿到分页对象(分页) Page findPageByQuery(BaseQuery baseQuery); //根据Query拿到对应的所有数据(不分页) List<T> findByQuery(BaseQuery baseQuery); //根据jpql与对应的参数拿到数据 List findByJpql(String jpql,Object... values); }

然后实现BaseRepositoryImpl

public class BaseRepositoryImpl<T,ID extends Serializable> extends SimpleJpaRepository<T,ID> implements BaseRepository<T,ID> { //让spring把entityManager给我注入过来 --factoryBean private final EntityManager entityManager; //必需要实现父类的这个构造器 public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) { super(domainClass, em); this.entityManager = em; } //分页查询的方法 @Override public Page findPageByQuery(BaseQuery baseQuery) { //得到Sort Sort sort = baseQuery.createSort(); //条件 Specification spec = baseQuery.createSpecification(); //分页 Pageable pageable = new PageRequest(baseQuery.getJpaPage(),baseQuery.getPageSize() , sort); //查询 Page<T> page = super.findAll(spec,pageable); return page; } //不分页 @Override public List<T> findByQuery(BaseQuery baseQuery) { Sort sort = baseQuery.createSort(); Specification specs = baseQuery.createSpecification(); //条件和排序 List<T> list = super.findAll(specs,sort); return list; } //select o from Employee o where o.username=? and o.email=? //xxx 111@email.com 2 @Override public List findByJpql(String jpql, Object... values) { //得到query对象 Query query = entityManager.createQuery(jpql); //设值 for (int i = 0; i < values.length; i++) { query.setParameter(i+1,values[i] ); } return query.getResultList(); }

然后管理起来自己用

二,创建web前端结构 完成Service层 创建IBaseService

public interface IBaseService<T,ID extends Serializable> { //新增和修改 void save(T t); //删除 --Long void delete(ID id); //查询 T findOne(ID id); //查询所有 List<T> findAll(); //根据Query拿到分页对象(分页) Page findPageByQuery(BaseQuery baseQuery); //根据Query拿到对应的所有数据(不分页) List<T> findByQuery(BaseQuery baseQuery); //根据jpql与对应的参数拿到数据 List findByJpql(String jpql,Object... values); }

创建BaseServiceImpl

@Transactional(propagation = Propagation.SUPPORTS,readOnly = true) public class BaseServiceImpl<T,ID extends Serializable> implements IBaseService<T,ID> { //spring 4之后 支持泛型的注解 @Autowired private BaseRepository<T,ID> baseRepository; @Override @Transactional public void save(T t) { baseRepository.save(t); } @Override @Transactional public void delete(ID id) { baseRepository.delete(id); } @Override public T findOne(ID id) { return baseRepository.findOne(id); } @Override public List<T> findAll() { return baseRepository.findAll(); } @Override public Page findPageByQuery(BaseQuery baseQuery) { return baseRepository.findPageByQuery(baseQuery); } @Override public List<T> findByQuery(BaseQuery baseQuery) { return baseRepository.findByQuery(baseQuery); } @Override public List findByJpql(String jpql, Object... values) { return baseRepository.findByJpql(jpql,values); } }

创建IEmployeeService

public interface IEmployeeService extends IBaseService<Employee,Long> { }

创建EmployeeServiceImpl

@Service public class EmployeeServiceImpl extends BaseServiceImpl<Employee,Long> implements IEmployeeService { }

配置applicationContext-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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 对静态资源进行放行 --> <mvc:default-servlet-handler /> <!-- 扫描controller部分的包 --> <!-- @Component组件, @Repository持久层, @Service业务逻辑层, and @Controller控制器 --> <context:component-scan base-package="cn.itsource.aisell.web.controller" /> <!-- 添加mvc对@RequestMapping等注解的支持 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> <!-- No serializer:配置 setObjectMapper(new CustomMapper)objectMapper 为我们自定义扩展后的 CustomMapper,解决了返回对象有关系对象的报错问题 --> <property name="objectMapper"> <bean class="cn.itsource.aisell.common.CustomMapper"></bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- ViewResolver 视图解析器 (struts2视图类型类似) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 设置视图路径的前后缀,该配置可以让我们写视图路径的时候更简单。 --> <!-- 希望跳转jsp是[/WEB-INF/views/前缀][xxx变量][.jsp后缀] --> <!-- * @see #setPrefix --> <property name="prefix" value="/WEB-INF/views/" /> <!-- * @see #setSuffix --> <property name="suffix" value=".jsp" /> </bean> <!-- 错误:提示告诉开发者你没有配置文件上传解析器。 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为1MB --> <property name="maxUploadSize"> <value>1048576</value> </property> </bean> </beans>

配置web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> </web-app>

完成Controller层

@Controller @RequestMapping("/employee") public class EmployeeController { @Autowired private IEmployeeService employeeService; @RequestMapping("/index") public String index() { //根据配置,这里会跳到/WEB-INF/views/employee/employee.jsp页面 return "employee/employee"; } @RequestMapping("/list") @ResponseBody public List<Employee> list(){ return employeeService.findAll(); } }

三,完成员工页面前端展示和分页

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="/WEB-INF/views/head.jsp"%> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/model/employee.js"></script> </head> <body> <!-- datagrid fit 填充父容器 rownumbers 行号 pagination 分页 --> <table id="employeeGrid" class="easyui-datagrid" data-options="fit:false,fixed:true, fitColumns:true,toolbar:'#tb',singleSelect:true"; url="/employee/page" iconCls="icon-save" rownumbers="true" pagination="true"> <thead> <tr> <th width="20" field="headImage" align="right" formatter="formatImage">头像</th> <th width="20" field="username" >用户名</th> <th width="20" field="password">密码</th> <th width="20" field="email">邮件</th> <th width="20" field="age" align="right">年龄</th> <th width="20" field="department" align="right" formatter="formatObj">部门名称</th> </tr> </thead> </table> <div id="tb" style="padding:5px;height:auto"> <!-- 这部分是加上增删改的按键:现在没有功能,我们先不管它 --> <div style="margin-bottom:5px"> <a href="#" data-method="add" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a> <a href="#" data-method="edit" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a> <a href="#" data-method="del" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a> </div> <!-- 这部门是查询的功能 --> <div> <form id="searchForm" action="/employee/download" method="post"> 用户名: <input name="username" class="easyui-textbox" style="width:80px;height:32px"> 邮件: <input name="email" class="easyui-textbox" style="width:80px;height:32px"> 部门 : <input class="easyui-combobox" name="departmentId" data-options="valueField:'id',textField:'name',panelHeight:'auto',url:'/util/departmentList'"> <a href="#" data-method="search" class="easyui-linkbutton" iconCls="icon-search">查找</a> </form> </div> </div> </body> </html>

解决懒加载问题

<filter> <filter-name>openEntity</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openEntity</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> public class CustomMapper extends ObjectMapper { public CustomMapper() { this.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false 对null的bean 不做序列化 this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); } }

加入高级查询条件 UtilController

@Controller @RequestMapping("/util") public class UtilController { //注入部门信息 @Autowired private IDepartmentService departmentService; //departmentList @RequestMapping("/departmentList") @ResponseBody public List<Department> queryDepartmentList(){ return departmentService.findAll(); } } $(function(){ //定义form表单 var searchForm = $("#searchForm"); var employeeGrid = $("#employeeGrid"); //绑定事件 easyui 第二天的时候 $("a[data-method]").on('click',function(){ //获取 data-method属性 <a data-method="seacher"> var methodName = $(this).data("method"); //动态调用方法 itsource["seacher"] itsource[methodName](); }) //对象 var itsource = { search:function(){ //怎么完成高级查询 jquery.jdirk.js 这个方法 这是jquery扩展方法 //该方法返回一个 JSON Object,返回对象中的每个数据都表示一个表单控件值。 var param = searchForm.serializeObject(); //发送查询数据库 --加载表格 发送请求 /employee/page employeeGrid.datagrid('load',param); }, add:function(){ alert(1); } } public class EmployeeQuery extends BaseQuery{ /** * username admin * email xx@qq.com * departmentId 1 */ //自身条件 private String username; private String email; private Integer age; private Integer departmentId; public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } //抽取查询 @Override public Specification createSpecification() { Specification<Employee> spe = Specifications.<Employee>and(). like(StringUtils.isNotBlank(username), "username", "%" + username + "%") .like(StringUtils.isNotBlank(email), "email", "%" + email + "%") .eq(departmentId!=null,"department.id",departmentId) .gt(age != null, "age", age) .build(); return spe; } }
最新回复(0)