java框架--springmvc+springdata+jpa+restful+ajax 完成 CRUD

                                                                        

com.atguigu.sssp.entity

package com.atguigu.sssp.entity;

import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Cacheable
@Table(name="SSSP_DEPARTMENTS")
@Entity
public class Department {

    private Integer id;
    private String departmentName;

    @GeneratedValue
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

}
Department
package com.atguigu.sssp.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.format.annotation.DateTimeFormat;

@Table(name="SSSP_EMPLOYEES")
@Entity
public class Employee {
    
    private Integer id;
    private String lastName;
    
    private String email;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
    
    private Date createTime;
    
    private Department department;

    @GeneratedValue
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Temporal(TemporalType.DATE)
    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Temporal(TemporalType.TIMESTAMP)
    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @JoinColumn(name="DEPARTMENT_ID")
    @ManyToOne(fetch=FetchType.LAZY)
    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}
Employee

com.atguigu.sssp.handle

package com.atguigu.sssp.handler;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.sssp.entity.Employee;
import com.atguigu.sssp.service.DepartmentService;
import com.atguigu.sssp.service.EmployeeService;

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeService employeeService;
    
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        employeeService.delete(id);
        return "redirect:/emps";
    }
    
    @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,
            Map<String, Object> map){
        if(id != null){
            Employee employee = employeeService.get(id);
            employee.setDepartment(null);
            map.put("employee", employee);
        }
    }
    
    @RequestMapping(value="/emp/{id}",method=RequestMethod.PUT)
    public String update(Employee employee){
        employeeService.save(employee);
        return "redirect:/emps";
    }
    // 编辑功能之前先查询功能
    @RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
    public String input(@PathVariable("id") Integer id, Map<String, Object> map){
        Employee employee = employeeService.get(id);
        map.put("employee", employee);
        map.put("departments", departmentService.getAll());
        return "emp/input";
    }
    
    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String save(Employee employee){
        employeeService.save(employee);
        return "redirect:/emps";
    }
    //ajax判断修改时候是否是同一用户名
    @ResponseBody
    @RequestMapping(value="/ajaxValidateLastName",method=RequestMethod.POST)
    public String validateLastName(@RequestParam(value="lastName",required=true) String lastName){
        Employee employee = employeeService.getByLastName(lastName);
        if(employee == null){
            return "0";
        }else{
            return "1";
        }
    }
    //添加功能
    @RequestMapping(value="/emp",method=RequestMethod.GET)
    public String input(Map<String,Object> map){
        map.put("departments", departmentService.getAll());
        map.put("employee", new Employee());
        return "emp/input";
    }
    //查询所有
    @RequestMapping("/emps")
    public String list(@RequestParam(value="pageNo", required=false, defaultValue="1") String pageNoStr, 
            Map<String, Object> map){
        int pageNo = 1;
        
        try {
            pageNo = Integer.parseInt(pageNoStr);
            if(pageNo < 1){
                pageNo = 1;
            }
        } catch (Exception e) {}
        
        Page<Employee> page = employeeService.getPage(pageNo, 5);
        map.put("page", page);
        
        return "emp/list";
    }
    
}
EmployeeHandler

com.atguigu.sssp.repository

package com.atguigu.sssp.repository;

import java.util.List;

import javax.persistence.QueryHint;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;

import com.atguigu.sssp.entity.Department;

public interface DepartmentRepository extends JpaRepository<Department, Integer>{

    @QueryHints({@QueryHint(name=org.hibernate.ejb.QueryHints.HINT_CACHEABLE,value="true")})
    @Query("FROM Department d")
    List<Department> getAll();
    
}
DepartmentRepository
package com.atguigu.sssp.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.atguigu.sssp.entity.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {

    Employee getByLastName(String lastName);
    
}
EmployeeRepository

com.atguigu.sssp.service

package com.atguigu.sssp.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.atguigu.sssp.entity.Department;
import com.atguigu.sssp.repository.DepartmentRepository;

@Service
public class DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;
    
    @Transactional(readOnly=true)
    public List<Department> getAll(){
        return departmentRepository.getAll();
    }
}
DepartmentService
package com.atguigu.sssp.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.atguigu.sssp.entity.Employee;
import com.atguigu.sssp.repository.EmployeeRepository;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;
    
    @Transactional
    public void delete(Integer id){
        employeeRepository.delete(id);
    }
    
    @Transactional(readOnly=true)
    public Employee get(Integer id){
        return employeeRepository.findOne(id);
    }
    
    @Transactional
    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setCreateTime(new Date());
        }
        employeeRepository.saveAndFlush(employee);
    }
    
    @Transactional(readOnly=true)
    public Employee getByLastName(String lastName){
        return employeeRepository.getByLastName(lastName);
    }
    
    @Transactional(readOnly=true)
    public Page<Employee> getPage(int pageNo, int pageSize){
        PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
        return employeeRepository.findAll(pageable);
    }
}
EmployeeService

src 配置文件

<?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:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.atguigu.sssp">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    
    <!-- 配置数据源 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource"
        class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>    
        <property name="password" value="${jdbc.password}"></property>    
        <property name="driverClass" value="${jdbc.driverClass}"></property>    
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>    
        
        <!-- 配置其他属性 -->
    </bean>
    
    <!-- 配置 JPA 的 EntityManagerFactory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
        </property>    
        <property name="packagesToScan" value="com.atguigu.sssp"></property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
            </props>
        </property>
        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"></property>
    </bean>
    
    <!-- 配置事务 -->
    <bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>    
    </bean>
    
    <!-- 配置支持基于注解的事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <!-- 配置 SpringData -->
    <jpa:repositories base-package="com.atguigu.sssp"
        entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
    
</beans>
applicationContext.xml
jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring
db.properties
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>
ehcache.xml
log4j.rootLogger=debug,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE

log4j.logger.org.slsale=debug
log4j.logger.org.apache.ibatis=debug
log4j.logger.org.mybatis.spring=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug

######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=debug
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - [%p] %d %c - %m%n

######################################################################################
# Rolling File  \u6587\u4ef6\u5927\u5c0f\u5230\u8fbe\u6307\u5b9a\u5c3a\u5bf8\u7684\u65f6\u5019\u4ea7\u751f\u4e00\u4e2a\u65b0\u7684\u6587\u4ef6
######################################################################################
#log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.ROLLING_FILE.Threshold=INFO
#log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
#log4j.appender.ROLLING_FILE.Append=true
#log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
#log4j.appender.ROLLING_FILE.MaxBackupIndex=100
#log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n

######################################################################################
# DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=${sssp_new.root}/logs/log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n

#DWR \u65e5\u5fd7
#log4j.logger.org.directwebremoting = ERROR

#\u663e\u793aHibernate\u5360\u4f4d\u7b26\u7ed1\u5b9a\u503c\u53ca\u8fd4\u56de\u503c
#log4j.logger.org.hibernate.type=DEBUG,CONSOLE 

#log4j.logger.org.springframework.transaction=DEBUG
#log4j.logger.org.hibernate=DEBUG
#log4j.logger.org.acegisecurity=DEBUG
#log4j.logger.org.apache.myfaces=TRACE
#log4j.logger.org.quartz=DEBUG

#log4j.logger.com.opensymphony=INFO  
#log4j.logger.org.apache.struts2=DEBUG  
log4j.logger.com.opensymphony.xwork2=debug
log4j.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        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-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.atguigu.sssp" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 映射加载静态文件 -->
    <mvc:default-servlet-handler/>
    <!-- 注解加载驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>
springDispatcherServlet-servlet.xml

WebContent 

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

    <!-- 配置启动 IOC 容器的 Listener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <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>
    </filter>
    
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置可以把 POST 请求转为 PUT、DELETE 请求的 Filter -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置 OpenEntityManagerInViewFilter. 可以解决懒加载异常的问题 -->
    <filter>
        <filter-name>OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置 SpringMVC 的 DispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springDispatcherServlet-servlet.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

       <!-- log4j配置 -->
       <context-param>
               <param-name>log4jConfigLocation</param-name>
             <param-value>classpath:log4j.properties</param-value>
       </context-param>
       <context-param>
          <param-name>webAppRootKey</param-name>
          <param-value>sssp_new.root</param-value>
       </context-param> 
       <!-- spring加载log4j的监听 -->
        <listener>
           <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
       </listener>
</web-app>
web.xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
<!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=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#lastName").change(function(){
            var val = $(this).val();
            val = $.trim(val);
            $(this).val(val);
            
            //若修改的 lastName 和之前的 lastName 一致, 则不发送 Ajax 请求, 直接 alert:lastName 可用!
            var _oldLastName = $("#_oldLastName").val();
            _oldLastName = $.trim(_oldLastName);
            if(_oldLastName != null && _oldLastName != "" && _oldLastName == val){
                alert("lastName 可用!");
                return;
            }
            
            var url = "${pageContext.request.contextPath }/ajaxValidateLastName";
            var args = {"lastName":val,"date":new Date()};
            
            $.post(url, args, function(data){
                if(data == "0"){
                    alert("lastName 可用!");
                }else if(data == "1"){
                    alert("lastName 不可用!");
                }else{
                    alert("网络或程序出错. ");
                }
            });
        });
    })
</script>
</head>
<body>
    
    <c:set value="${pageContext.request.contextPath }/emp" var="url"></c:set>
    
    <c:if test="${employee.id != null }">
        <c:set value="${pageContext.request.contextPath }/emp/${employee.id}" var="url"></c:set>
    </c:if>
    
    <form:form action="${url }" method="POST" modelAttribute="employee">
        
        <c:if test="${employee.id != null }">
            <input type="hidden" id="_oldLastName" value="${employee.lastName }"/>
            <form:hidden path="id"/>
            <input type="hidden" name="_method" value="PUT"/>
        </c:if>
    
        LastName: <form:input path="lastName" id="lastName"/>
        <br>
        Email: <form:input path="email"/>
        <br>
        Birth: <form:input path="birth"/>
        <br>
        Department: 
        <form:select path="department.id" items="${departments }" 
            itemLabel="departmentName" itemValue="id"></form:select>
        <br>
        <input type="submit" value="Submit"/>
        
    </form:form>
        
</body>
</html>
input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    
<!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=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        $(".delete").click(function(){
            var label = $(this).next(":hidden").val();
            var flag = confirm("确定要删除" + label + "的信息吗?");
            if(flag){
                var url = $(this).attr("href");
                
                $("#_form").attr("action", url);
                $("#_method").val("DELETE");
                $("#_form").submit();
            }
            
            return false;
        });
    })
</script>
</head>
<body>

    <form action="" method="POST" id="_form">
        <input type="hidden" id="_method" name="_method"/>
    </form>
    
    <c:if test="${page == null || page.numberOfElements == 0 }">
        没有任何记录. 
    </c:if>
    <c:if test="${page != null && page.numberOfElements > 0 }">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>ID</th>
                <th>LastName</th>
                
                <th>Email</th>
                <th>Birth</th>
                
                <th>CreateTime</th>
                <th>Department</th>
                
                <th>Edit</th>
                <th>Delete</th>
            </tr>
            
            <c:forEach items="${page.content }" var="emp">
                <tr>
                    <td>${emp.id }</td>
                    <td>${emp.lastName }</td>
                    
                    <td>${emp.email }</td>
                    <td>
                        <fmt:formatDate value="${emp.birth }" pattern="yyyy-MM-dd"/>
                    </td>
                    
                    <td>
                        <fmt:formatDate value="${emp.createTime }" pattern="yyyy-MM-dd hh:mm:ss"/>
                    </td>
                    <td>${emp.department.departmentName }</td>
                    
                    <td><a href="${pageContext.request.contextPath }/emp/${emp.id}">Edit</a></td>
                    <td>
                        <a href="${pageContext.request.contextPath }/emp/${emp.id}" class="delete">Delete</a>
                        <input type="hidden" value="${emp.lastName }"/>
                    </td>
                </tr>
            </c:forEach>
            
            <tr>
                <td colspan="8">
                    共 ${page.totalElements } 条记录
                    共 ${page.totalPages } 页
                    当前 ${page.number + 1 } 页
                    <a href="?pageNo=${page.number + 1 - 1 }">上一页</a>
                    <a href="?pageNo=${page.number + 1 + 1 }">下一页</a>
                </td>
            </tr>
            
        </table>
    </c:if>
    
</body>
</html>
list.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="emps">List All Employees</a>
    <br><br>
    <a href="emp">Add New Employee</a>
    
</body>
</html>
index.jsp

 

 

转载于:https://www.cnblogs.com/ou-pc/p/7988787.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值