环境:IDE:eclipse、jdk1.7、mysql5.7、maven
项目结构图
上面目录结构你可以自己创建
搭建框架
首先加入maven依赖包以及相关插件
<dependencies> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- hibernate相关 --> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.6.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>5.0.1.Final</version> </dependency> <dependency> <groupId>org.jboss</groupId> <artifactId>jandex</artifactId> <version>2.0.0.Final</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <!-- jpa相关 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.0.6.Final</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <!-- ehcache缓存 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>5.0.6.Final</version> </dependency> <!-- springdata --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.6.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.4.2.RELEASE</version> </dependency> <!-- common相关 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <!-- 日志 --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> <scope>test</scope> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>5.0.6.Final</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.45</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <!-- <source>1.8</source> --> <encoding>utf-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <uriEncoding>UTF-8</uriEncoding> </configuration> </plugin> </plugins> </build>
注意:1.上面的spring-data-commons和spring-data-jpa版本问题,不然会出现莫名其妙的错误。
2.我这里使用的是tomcat7-maven-plugin插件
jar包引入完之后,下边我们开始从web.xml配置
web.xml
<!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载application配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置字符编码过滤器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 解决懒加载问题 --> <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> <!-- 配置restfull风格 --> <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> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 加载配置springmvc配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
注意:上面的配置就多一个懒加载,这个是为了解决spring-data-jpa懒加载异常的。
接下来开始配置springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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"> <!-- 扫描注解的包 --> <context:component-scan base-package="com.jiangfx.controller"/> <!-- 开启注解 --> <mvc:annotation-driven/> <!--静态资源访问--> <mvc:default-servlet-handler/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
然后配置applicationContext.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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描注解的包 --> <context:component-scan base-package="com.jiangfx.service"/> <!-- 配置数据库 --> <!-- 加载配置文件 --> <context:property-placeholder location="classpath*:db.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${db.driverClassName}" /> <property name="jdbcUrl" value="${db.url}" /> <property name="user" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> <!-- 2.配置jpa的entityManagerFactory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 指定Entity实体类包路径 --> <property name="packagesToScan" value="com.jiangfx.entity"></property> <!-- 指定Jpa持久化实现厂商类 --> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean> </property> <!-- jpa属性 --> <property name="jpaProperties"> <props> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 二级缓存 --> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <!-- <prop key="hibernate.cache.use_query_cache">true</prop> --> </props> </property> <!-- <property name="sharedCacheMode" value="ENABLE_SELETIVE"></property> --> </bean> <!-- 3.配置事务管理器 --> <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.jiangfx.repository" entity-manager-factory-ref="entityManagerFactory"></jpa:repositories> </beans>
注意:上面要引入jpa的命名空间
上面数据库配置文件db.properties
db.driverClassName=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/springdatajpa?charcterEncoding=utf-8 db.username=root db.password=
现在框架搭建完成,下面开始着手完成增删改查功能。
controller
EmpController
package com.jiangfx.controller; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; 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.jiangfx.entity.Dept; import com.jiangfx.entity.Emp; import com.jiangfx.service.DeptService; import com.jiangfx.service.EmpService; import com.jiangfx.service.impl.EmpServiceImpl; @Controller public class EmpController { //注入empservice @Autowired private EmpService empService; //注入deptService @Autowired private DeptService deptService; /** * 查询:直接使用分页查询,这都是接口定义好的方法。不需要我们在写,方便。 */ @RequestMapping(value="/list",method=RequestMethod.GET) public String list(ModelMap map,@RequestParam(defaultValue="1",required=false,value="pageNo") Integer pageNo){ Page<Emp> page = empService.getPage(pageNo, 3); map.put("page", page); return "emp"; } /** * 跳转到添加页面 */ @RequestMapping(value="saveEmpPage",method=RequestMethod.GET) public String savePage(ModelMap map){ List<Dept> depts = deptService.getListDepts(); map.addAttribute("depts", depts); return "saveEmpPage"; } /** * 添加:ajax异步校验用户名是否存在 */ @RequestMapping(value="/checkName",method=RequestMethod.POST) @ResponseBody public String checkName(String ename){ Emp emp = empService.getByName(ename); System.out.println(emp); if(emp != null){ return "1"; }else{ return "0"; } } /** * 添加 */ @RequestMapping(value="/saveEmp",method=RequestMethod.POST) public String save(Emp emp){ emp.setTime(new Date()); empService.save(emp); return "redirect:/list"; } /** * 根据id查询 */ @RequestMapping(value="/getById",method=RequestMethod.GET) public void getById(Integer eid){ Emp emp = empService.getById(eid); } /** * 跳转到修改页面 */ @RequestMapping("/updatePage") public String updatePage(Integer eid,ModelMap map){ //先查询 Emp emp = empService.getById(eid); map.addAttribute("emp", emp); return "updatePage"; } /** * 修改 */ @RequestMapping(value="/update",method=RequestMethod.POST) public String update(Emp emp,ModelMap map){ empService.update(emp); /*List<Dept> depts = deptService.getListDepts(); map.addAttribute("depts", depts);*/ return "redirect:/list"; } /** * 删除 */ @RequestMapping(value="/deleteEmp",method=RequestMethod.GET) public String deleteEmp(Integer eid){ empService.deleteEmp(eid); return "redirect:/list"; } }
serviceImpl
EmpServiceImpl
package com.jiangfx.controller; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; 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.jiangfx.entity.Dept; import com.jiangfx.entity.Emp; import com.jiangfx.service.DeptService; import com.jiangfx.service.EmpService; import com.jiangfx.service.impl.EmpServiceImpl; @Controller public class EmpController { //注入empservice @Autowired private EmpService empService; //注入deptService @Autowired private DeptService deptService; /** * 查询:直接使用分页查询,这都是接口定义好的方法。不需要我们在写,方便。 */ @RequestMapping(value="/list",method=RequestMethod.GET) public String list(ModelMap map,@RequestParam(defaultValue="1",required=false,value="pageNo") Integer pageNo){ Page<Emp> page = empService.getPage(pageNo, 3); map.put("page", page); return "emp"; } /** * 跳转到添加页面 */ @RequestMapping(value="saveEmpPage",method=RequestMethod.GET) public String savePage(ModelMap map){ List<Dept> depts = deptService.getListDepts(); map.addAttribute("depts", depts); return "saveEmpPage"; } /** * 添加:ajax异步校验用户名是否存在 */ @RequestMapping(value="/checkName",method=RequestMethod.POST) @ResponseBody public String checkName(String ename){ Emp emp = empService.getByName(ename); System.out.println(emp); if(emp != null){ return "1"; }else{ return "0"; } } /** * 添加 */ @RequestMapping(value="/saveEmp",method=RequestMethod.POST) public String save(Emp emp){ emp.setTime(new Date()); empService.save(emp); return "redirect:/list"; } /** * 根据id查询 */ @RequestMapping(value="/getById",method=RequestMethod.GET) public void getById(Integer eid){ Emp emp = empService.getById(eid); } /** * 跳转到修改页面 */ @RequestMapping("/updatePage") public String updatePage(Integer eid,ModelMap map){ //先查询 Emp emp = empService.getById(eid); map.addAttribute("emp", emp); return "updatePage"; } /** * 修改 */ @RequestMapping(value="/update",method=RequestMethod.POST) public String update(Emp emp,ModelMap map){ empService.update(emp); /*List<Dept> depts = deptService.getListDepts(); map.addAttribute("depts", depts);*/ return "redirect:/list"; } /** * 删除 */ @RequestMapping(value="/deleteEmp",method=RequestMethod.GET) public String deleteEmp(Integer eid){ empService.deleteEmp(eid); return "redirect:/list"; } }
EmpService
package com.jiangfx.service; import org.springframework.data.domain.Page; import com.jiangfx.entity.Emp; public interface EmpService { Page<Emp> getPage(Integer pageNo, Integer pageSize); /** * 校验用户名是否存在 * @param ename * @return */ Emp getByName(String ename); /** * 添加用户 * @param emp */ void save(Emp emp); /** * 根据id查询 * @param eid * @return */ Emp getById(Integer eid); /** * 修改 * @param emp */ void update(Emp emp); /** * 删除 * @param emp */ void deleteEmp(Integer eid); }
repository
package com.jiangfx.repository; import org.hibernate.annotations.UpdateTimestamp; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.jiangfx.entity.Emp; public interface EmpRepository extends JpaRepository<Emp, Integer> { /** * 根据用户名查询 * @param ename * @return */ @Query("from Emp where ename= :ename") Emp getname(@Param("ename") String ename); /** * 分页查询,添加,修改:不需要定义方法,直接调用父接口中的save()方法 */ /** * 删除:也可以不定义方法,和上面一样,可以直接电涌父接口中的方法 * @return */ /*@Modifying @Query("delete from Emp where eid= :eid") void delete(@Param("eid") Integer eid);*/ }
实体类entity
package com.jiangfx.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; 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.hibernate.annotations.UpdateTimestamp; import org.springframework.format.annotation.DateTimeFormat; @Table(name="emp") @Entity public class Emp implements Serializable { private static final long serialVersionUID = 1L; private Integer eid; private String ename; private String eage; @DateTimeFormat(pattern="yyyy-MM-dd") private Date time; private Dept dept; @GeneratedValue(strategy = GenerationType.IDENTITY) @Id public Integer getEid() { return eid; } public void setEid(Integer eid) { this.eid = eid; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getEage() { return eage; } public void setEage(String eage) { this.eage = eage; } @Temporal(TemporalType.TIMESTAMP) public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @JoinColumn(name="did") @ManyToOne(fetch=FetchType.LAZY) public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } @Override public String toString() { return "Emp [eid=" + eid + ", ename=" + ename + ", eage=" + eage + ", time=" + time + ", dept=" + dept + "]"; } }
下面是一些jsp页面
emp.jsp显示分页查询员工列表
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="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"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"/> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script> <title>员工</title> </head> <body> <div class="container"> <table class="table table-hover table-bordered"> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>创建时间</th> <th>部门</th> <th colspan="3">操作</th> </tr> <c:forEach items="${page.content}" var="emp"> <tr> <td>${emp.eid}</td> <td>${emp.ename}</td> <td>${emp.eage}</td> <td> <fmt:formatDate value="${emp.time}" pattern="yyyy-MM-dd"/> </td> <td>${emp.dept.dname}</td> <td> <a href="${pageContext.request.contextPath }/saveEmpPage">添加</a> </td> <td><a href="${pageContext.request.contextPath }/deleteEmp?eid=${emp.eid}">删除</a> </td> <td><a href="${pageContext.request.contextPath }/updatePage?eid=${emp.eid}">修改</a> </td> </tr> </c:forEach> </table> <p>共${page.totalPages}页</p> <p>当前第${page.number+1}页</p> <a href="list?pageNo=${page.number+1}">上一页</a> <a href="list?pageNo=${page.number+1-1}">上一页</a> <a href="list?pageNo=${page.number+1+1}">下一页</a> </div> <!-- 模态框(Modal) --> <%-- <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="myModalLabel">模态框(Modal)标题</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="exampleInputEmail1">姓名</label> <input type="text" name="ename" class="form-control" id="exampleInputEmail1" placeholder="姓名"> </div> <div class="form-group"> <label for="exampleInputPassword1">年龄</label> <input type="text" name="eage" class="form-control" id="exampleInputPassword1" placeholder="年龄"> </div> <label for="exampleInputEmail1">部门</label> <select class="form-control" name="dept.did"> <c:forEach items="${depts }" var="dept"> <option value="${dept.did }">${dept.dname }</option> </c:forEach> </select> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary">提交更改</button> </div> </div> </div> </div>--%> </body> </html>
添加员工信息页面
saveEmpPage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>添加员工页面</title> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $("#name").change(function(){ var name = $("this").val(); var args = {"ename":name,"date":new Date()}; $.ajax({ url:"${pageContext.request.contextPath}/checkName", type:"post", data:args, success:function(result){ if(result=="0"){ alert("用户名可用") }else { alert("用户名不可用") } } }); }); }); </script> </head> <body> <form action="${pageContext.request.contextPath }/saveEmp" method="post"> 姓名<input type="text" id="name" name="ename"> 年龄<input type="text" name="eage"> 部门<select class="form-control" name="dept.did"> <c:forEach items="${depts }" var="dept"> <option value="${dept.did }">${dept.dname }</option> </c:forEach> </select> <input type="submit" value="提交"> </form> </body> </html>
修改员工信息页面
updatePage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>修改页面</title> </head> <body> <form action="${pageContext.request.contextPath }/update" method="post"> <input type="hidden" name="eid" value="${emp.eid }"> 姓名<input type="text" name="ename" value="${emp.ename }"> 年龄<input type="text" name="eage" value="${emp.eage }"> 部门<%-- <select class="form-control" name="dept.did"> <c:forEach items="${depts }" var="dept"> <option value="${dept.did }">${dept.dname }</option> </c:forEach> </select> --%> <input type="submit" value="提交"> </form> </body> </html>
首页index.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">
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/list">员工查询</a>
<a href="${pageContext.request.contextPath }/getlist">部门查询</a>
</body>
</html>
最后附上数据库信息
-- ---------------------------- -- Table structure for dept -- ---------------------------- DROP TABLE IF EXISTS `dept`; CREATE TABLE `dept` ( `did` int(11) NOT NULL, `dname` varchar(255) DEFAULT NULL, PRIMARY KEY (`did`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of dept -- ---------------------------- INSERT INTO `dept` VALUES ('1', '研发'); INSERT INTO `dept` VALUES ('2', '测试'); INSERT INTO `dept` VALUES ('3', '销售'); -- ---------------------------- -- Table structure for emp -- ---------------------------- DROP TABLE IF EXISTS `emp`; CREATE TABLE `emp` ( `eid` int(11) NOT NULL AUTO_INCREMENT, `ename` varchar(255) DEFAULT NULL, `eage` varchar(255) DEFAULT NULL, `time` datetime DEFAULT NULL, `did` int(11) DEFAULT NULL, PRIMARY KEY (`eid`), KEY `FKjq3nwkl52kinwb7t6l8f9ljtv` (`did`), CONSTRAINT `FKjq3nwkl52kinwb7t6l8f9ljtv` FOREIGN KEY (`did`) REFERENCES `dept` (`did`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of emp -- ---------------------------- INSERT INTO `emp` VALUES ('1', '钱七', '21', '2018-04-23 22:57:07', '3'); INSERT INTO `emp` VALUES ('2', '曹操', '45', '2018-04-23 22:57:23', '3'); INSERT INTO `emp` VALUES ('3', '张三', '25', '2018-04-24 16:06:59', '1'); INSERT INTO `emp` VALUES ('4', '李四', '26', '2018-04-25 10:49:24', '2'); INSERT INTO `emp` VALUES ('5', '王五', '35', '2018-04-25 10:49:39', '2'); INSERT INTO `emp` VALUES ('6', '赵六', '30', '2018-04-25 10:50:15', '1');