springmvc及前端展示

.创建IBaseService
package cn.itsource.pss.service;

import cn.itsource.pss.domain.Employee;
import cn.itsource.pss.query.BaseQuery;
import org.springframework.data.domain.Page;
import java.io.Serializable;
import java.util.List;

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

2.3.创建BaseServiceImpl
package cn.itsource.pss.service.impl;

import cn.itsource.pss.query.BaseQuery;
import cn.itsource.pss.repository.BaseRepository;
import cn.itsource.pss.service.IBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

import static org.springframework.transaction.annotation.Propagation.SUPPORTS;

@Transactional(readOnly = true,propagation = SUPPORTS)
public class BaseServiceImpl<T,ID extends Serializable> implements IBaseService<T,ID>{

//注意:Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用
@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);
}

}

2.4.创建IEmployeeService
package cn.itsource.pss.service;

import cn.itsource.pss.domain.Employee;
//注:在开发中,业务后期是有很多功能的(不只是我们最简单的CRUD)
public interface IEmployeeService extends IBaseService<Employee,Long> {
}

2.5.创建EmployeeServiceImpl
package cn.itsource.pss.service.impl;

import cn.itsource.pss.domain.Employee;
import cn.itsource.pss.service.IEmployeeService;
import org.springframework.stereotype.Service;

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

2.6.功能测试
2.6.1.BaseServiceTest
package cn.itsource.pss.repository;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“classpath:applicationContext.xml”)
public class BaseServiceTest {
}

2.6.2.EmployeeServiceTest
package cn.itsource.pss.service;

import cn.itsource.pss.domain.Employee;
import cn.itsource.pss.repository.BaseServiceTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

public class EmployeeServiceTest extends BaseServiceTest {

@Autowired
private IEmployeeService employeeService;

@Test
public void findAll(){
    System.out.println(employeeService);
    System.out.println(employeeService.getClass());

    List<Employee> employees = employeeService.findAll();
    for (Employee employee : employees) {
        System.out.println(employee);
    }
}

@Test
public void save(){
    Employee employee = new Employee();
    employee.setUsername("用户名称");
    employeeService.save(employee);
}

}

3.集成SpringMVC
备注:SpringMVC咱们刚学完,其中的配置和今天的集成配置几乎完全一样,这一节我们不做详细讲解,大家只需要把之前的配置代码进行拷备使用即可。如果忘了这部分配置的同学,希望下来自己去SpringMVC的课程进行复习。
3.1.引入相应jar包(已经完成)
首先确定咱们已经引入SpringMVC的核心jar包,这个包咱们之前在pom.xml中已经引入,这里主要是给大家提醒一下。

org.springframework spring-web ${org.springframework.version} org.springframework spring-webmvc ${org.springframework.version}

3.2.配置applicationContext-mvc.xml
咱们可以为SpringMVC单独配置一个xml,把它与核心的applicationContext.xml分开。让咱们的xml配置也是模块化配置的。
以下为applicationContext-mvc.xml的代码(大家可以直接到之前SpringMVC的课程中拷备即可)

<?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.pss.web" />
    <!-- 添加mvc对@RequestMapping等注解的支持 -->
    <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>

3.3.配置web.xml
3.3.1.修改正确的版本
注意:现在web.xml使用提2.3的版本,这个版本是不支持EL表达式的,所以我们需要改它的头修改成2.4及以上版本(大家随便到之前哪个项目的位置拷备一个正确版本即可)!

以下为正确的版本(大家可以直接拷备):

<?xml version="1.0" encoding="UTF-8"?>

3.3.2.完成相应的配置
这里大家要特别注意,本来我们可以配置一个applicationContext.xml读取即可。
但是大家下一个项目学习Shiro,而Shiro 用到的 Spring 的配置必须在 listener 里加载。
所以在这里我们对两个xml进行了单独进行了配置。
<?xml version="1.0" encoding="UTF-8"?>

    <!-- 读取SpringMVC -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 启动Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--  配置解决中文乱码的问题 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

<!-- 配置核心控制器-->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <!-- 告诉SpringMVC到哪里去找配置文件 -->
        <param-name>contextConfigLocation</param-name>
        <!-- 注意:这里只读取springmvc的xml -->
        <param-value>classpath:applicationContext-mvc.xml</param-value>
    </init-param>
    <!-- Servlet默认在每一次访问的时候创建 -->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

3.4.创建Controller与页面
3.4.1.EmployeeController
package cn.itsource.pss.controller;

import cn.itsource.pss.domain.Employee;
import cn.itsource.pss.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@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();
}

}

3.4.2.employee.jsp页面
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

Title

访问成功

完成后我们可以直接运行tomcat进行测试(注:tomcat的配置在 Maven&IntelliJ IDEA&UML当天的课程文档中,大家如果忘记配置可以直接去查看)

3.5.功能测试
这里,我们直接运行tomcat(如果发现报如下错误)
(动态图,按ctrl+右键打开)

解决方案:File > Project Structure > Artifacts > 在右侧Output Layout右击项目名,选择Put into Output Root
(动态图,按ctrl+右键打开)

输入路径 http://localhost/employee/index 查看是否访问成功
输入路径 http://localhost/employee/list 查看是否返回数据
如果访问都没有问题,就代表咱们的集成已经完成!!!

4.引入主页面
咱们使用的主页面是使用Easyui来完成。接下来,我们来看下来怎么来使用这个界面。
这个界面在咱们今天的资源文件夹中,大家可以去打开找到。

4.1.把相应的文件拷备到项目中来
4.1.1.把文件拷备到根目录(注意结构)

4.1.2.准备MainController.java文件
package cn.itsource.pss.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {

@RequestMapping("/main")
public String index() {
    return "forward:WEB-INF/views/main.jsp";
}

}

4.1.3.准备main.jsp文件

注意:这个文件中的内容我们以前学EasyUI的时候已经学过

4.2.主页面的代码
4.2.1.抽取一个head.jsp
这里放的是引入easyui的代码(我们很多页面都要引入,所以单独抽取出来)
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

4.2.2.准备静态菜单数据
咱们现在还没有做菜单功能,所以先准备一些数据可以读取

代码如下:
[{
“id”:1,
“text”:“基本数据”,
“iconCls”:“icon-save”,
“children”:[{
“text”:“用户管理”,
“url”:"/employee/index"
},{
“text”:“部门管理”,
“url”:"/department/index"
}]
}]

4.2.3.main.jsp中的代码如下
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

智销系统 <%@include file="/WEB-INF/views/head.jsp" %>
<script type="text/javascript">
    $(function () {
        $('#menuTree').tree({
            url:'/json/menu.json',
            onClick:function(node) {
                addTab(node.text,node.url);
            }
        });
    })


    function addTab(title, url){
        if(url){
            if ($('#dataTab').tabs('exists', title)){
                $('#dataTab').tabs('select', title);
            } else {
                var content = '<iframe scrolling="auto" frameborder="0"  src="'+url+'" style="width:100%;height:100%;"></iframe>';
                $('#dataTab').tabs('add',{
                    title:title,
                    content:content,
                    closable:true
                });
            }
        }
    }
</script>

源码时代智销系统

5.员工的查询页面
使用EasyUI中的Grid控件来完成:
5.1.employee.jsp
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

Title <%@include file="/WEB-INF/views/head.jsp" %>

5.2.UiPage.java
由于咱们SpringDataJpa返回的数据和EasyUI中的数据匹配不上,所以咱们准备一个类,直接把SpringDataJpa的Page对象进行一次封装,返回给前台即可:
package cn.itsource.yxb.common;
import org.springframework.data.domain.Page;
import java.util.List;

public class UiPage {
private long total; //总条数
private List rows; //每页数据
public UiPage(){}
public UiPage(Page page){
total = page.getTotalElements();
rows = page.getContent();
}
get,set省略
}

5.3.BaseQuery.java
EasyUI查询传参的名称如果和BaseQuery中接收的名称不一致,咱们就需要修改BaseQuery这个类进行功能的兼容:
/**

  • 所有Query对象的父类 公共代码|规范
    */
    public abstract class BaseQuery {

    ….
    //兼容Easyui的分页
    public void setPage(int page) {
    this.currentPage = page;
    }
    public void setRows(int rows) {
    this.pageSize = rows;
    }
    }

5.4.EmployeeController.java
在控制层页面返回相应的数据即可
@Controller
@RequestMapping("/employee")
public class EmployeeController extends BaseController{

@Autowired
private IEmployeeService employeeService;

@RequestMapping("/index")
public String index(){
    return "employee/employee";
}

//查询分页数据
@RequestMapping("/page")
@ResponseBody
public UiPage page(EmployeeQuery query){
    return new UiPage(employeeService.findPageByQuery(query));
}

}
6.完善Employee对象
6.1.加入部门模块
注:部门模块咱们只做到service部分就可以了!
创建部门Domain,然后把员工的代码都拷备一份修改即可(此处我们不做详细介绍)
6.2.员工完善字段
@Entity
@Table(name=“employee”)
public class Employee extends BaseDomain {

private String username;
private String password;
private String email;
private Integer age;

//头像
private String headImage;
//部门
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="department_id")
private Department department;
…

}

6.3.显示部门与头像
请注意:图片需要大家自己根据数据库的图片路径把文件加上去
6.3.1.employee.js
function formatImage(data) {
return “没有图片
}
function formatDept(data) {
if(data){return data.name};
return “”;
}

$(function () {

})

6.3.2.employee.jsp

6.3.3.web.xml(解决noSession)
运行时我们会发现没有数据,然后通过js调试工作可以看到,返回报错 no-session
我们加上以下代码即可

openEntity org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter openEntity /*

6.3.4.No serializer
No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
这个错我们可以到网上搜索,SpringMVC与Jpa集成的时候(有懒加载)就会出现这个问题
(这是因为你需要序列化对象有一个属性是一类类型,而你使用了Hibernate的延迟加载所以这里是个Hibernate的代理对象。该代理对象有些属性不能被序列化所以会报错。)
在类上加属性:生成的时候把这个字段忽略了:
@JsonIgnoreProperties(value={“hibernateLazyInitializer”,“handler”,“fieldHandler”})

网上有很多相应的解决方案(这里我们不做缀述),我选一下个比较暴力的。大家直接把下面的代码拷备过来使用即可:

第一步:创建一个新的类(重写com.fasterxml.jackson.databind.ObjectMapper)
package cn.itsource.pss.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class CustomMapper extends ObjectMapper {
public CustomMapper() {
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}

第二步:在applicationContext-mvc.xml中配置一下即可

mvc:annotation-driven
mvc:message-converters



application/json; charset=UTF-8
application/x-www-form-urlencoded; charset=UTF-8







</mvc:message-converters>
</mvc:annotation-driven>

展示的效果如下:

7.加入高级查询条件
7.1.employee.jsp
这里咱们之前employee的grid控件是引入了这个div的

用户名: 邮件: 部门 : 查找

7.2.UtilController
我们把很多工具功能都放到这个类中
/**

  • 工具的Controller
    */
    @Controller
    @RequestMapping("/util")
    public class UtilController extends BaseController {

    @Autowired
    private IDepartmentService departmentService;
    @RequestMapping("/departmentList")
    @ResponseBody
    public List departmentList(){
    return departmentService.findAll();
    }

}

7.3.employee.js
咱们先可以引入jquery.serializejson.js这个控件,它直接直接拿到一个表单中的所有值,并且封装成一个json数据.

$(function () {
//这里我们把很多会常用到的元素进行一个抽取
var searchForm = $("#searchForm");
var employeeGrid = $("#employeeGrid");

//只要a标签中有data-method属性,咱们就给它添加事件
//  执行对应的itsource中的事件
$("a[data-method]").on("click",function () {
    itsource[$(this).data("method")]();
})

var itsource={
    search:function () {
        //需要先引入 jquery.jdirk.js 才可以使用这个方法
        var params = searchForm.serializeObject();
        employeeGrid.datagrid('load',params);
    }
}

})

7.4.EmployeeQuery
这里添加部门的支持
//只写一些特殊的条件
public class EmployeeQuery extends BaseQuery {

private Long departmentId;

@Override
public Specification createSpecification() {
    Specification<Employee> spec = Specifications.<Employee>and()
            .like(StringUtils.isNotBlank(username),"username", "%"+username+"%")
            .like(StringUtils.isNotBlank(email),"email", "%"+email+"%")
            .eq(departmentId!=null,"department.id",departmentId)
            .lt(age!=null,"age", age )
            .build();
    return spec;
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值