文章目录
- 系列文章目录
- 一、rest-query
- 二、rest-add
- 三、rest-update
- 四、rest-delete
一、准备工作
1.创建springmvc-crud.xml文件,配置好扫描包,引入连接数据库的config.properties文件,创建c3p0数据源对象,配置好连接信息以及JdbcTemplate对象以及视图解析器。
<context:component-scan base-package="edu.csust.crud"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/content/crud/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<context:property-placeholder location="classpath:META-INF/config.properties"></context:property-placeholder>
<!-- 创建c3p0数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--jdbc连接信息-->
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="driverClass" value="${driverClass}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<!--数据库连接池配置参数-->
<property name="initialPoolSize" value="${initialPoolSize}"/>
<property name="minPoolSize" value="${minPoolSize}"/>
<property name="maxPoolSize" value="${maxPoolSize}"/>
<property name="acquireIncrement" value="${acquireIncrement}"/>
<property name="maxStatements" value="${maxStatements}"/>
<property name="maxStatementsPerConnection" value="${maxStatementsPerConnection}"/>
</bean>
<!-- 创建JDBCTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
2.在web.xml文件中引入springmvc-crud.xml文件
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--导入其他文件:指定加载的xml文件路径-->
<!--classpath:/abc.xml 在当前项目中的classes目录下查找-->
<!--classpath*:/abc.xml 在当前项目中以及依赖jar中的classes目录下查找-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/META-INF/springmvc-crud.xml</param-value>
<!--<param-value>classpath:/META-INF/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>
package edu.csust.crud.model;
public class Department {
private Integer did;
private String departmentName;
public Department() {
}
public Department(Integer did, String departmentName) {
this.did = did;
this.departmentName = departmentName;
}
public Integer getDid() {
return did;
}
public void setDid(Integer did) {
this.did = did;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department{" +
"did=" + did +
", departmentName='" + departmentName + '\'' +
'}';
}
}
package edu.csust.crud.model;
public class Employee {
private Integer eid;
private String lastName;
private String email;
private Integer gender;
private Department department;
public Employee() {
}
public Employee(Integer eid, String lastName, String email, Integer gender, Department department) {
this.eid = eid;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
}
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
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;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"eid=" + eid +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
", department=" + department +
'}';
}
}
一、获取员工列表
1.添加表格入口<a href="emp" >员工管理</a>
2.书写前端table表格
<h3>员工管理</h3><br>
<a href="emp">添加</a>
<table>
<tr>
<th>ID</th>
<th>名称</th>
<th>邮箱</th>
<th>性别</th>
<th>部门</th>
<th>操作</th>
</tr>
<c:forEach items="${emps}" var="emp">
<tr>
<td>${emp.eid}</td>
<td>${emp.lastName}</td>
<td>${emp.email}</td>
<td>${emp.gender==1?"男":"女"}</td>
<td>${emp.department.departmentName}</td>
<td>
<a href="emp/${emp.eid}">编辑</a>
<a href="emp/${emp.eid}" class="delete">删除</a>
</td>
</tr>
</c:forEach>
3.当点击入口时,获取到所有的员工列表跳转到员工管理页面,所以到层获取到所有员工信息,注意@Repository和注入JdbcTemplate,加上@Autowire
@Autowired
private JdbcTemplate jdbcTemplate;
/*
查询所有员工列表
*/
public List<Employee> getEmps(){
String sql="select eid,lastName,email,gender,d.did did,departmentName " +
"from employees e,department d where e.did=d.did";
List<Employee> list=jdbcTemplate.query(sql, new RowMapper<Employee>(){
@Override
public Employee mapRow(ResultSet rs, int i) throws SQLException {
Department department=new Department(rs.getInt("did"),rs.getString("departmentName"));
Employee emp=new Employee(rs.getInt("eid"),rs.getString("lastName"),rs.getString("email"),rs.getInt("gender"),department);
return emp;
}
});
return list;
}
5.走控制器跳转到员工列表页面
//获取所有员工列表
@RequestMapping(value="emps",method= RequestMethod.GET)
public String getEmps(Map<String,Object> map){
List<Employee> list=employeeDao.getEmps();
map.put("emps",list);
return "index";
}
二、添加员工
1.在跳转到添加员工页面之前,首先获取到所有部门信息回显在所要提交的表单中,然后在addemp.jsp页面写好form表单中要提交的信息。
DepartmentDao:
@Autowired
private JdbcTemplate jdbcTemplate;
/*
查询所有部门
*/
public List<Department> getDepts(){
String sql="select did,departmentName from department";
List<Department> list=jdbcTemplate.query(sql, new RowMapper<Department>(){
@Override
public Department mapRow(ResultSet rs, int i) throws SQLException {
Department dep=new Department(rs.getInt("did"),rs.getString("departmentName"));
return dep;
}
});
return list;
}
<h3>添加员工</h3>
<%--modelAttribute是需要从request中获取指定key--%>
<%--path属性会从modelAttribute中对应提交和显示--%>
<form:form action="${pageContext.request.contextPath}/emp" method="post" modelAttribute="employee">
<c:if test="${employee.eid!=null}">
<form:hidden path="eid"/>
<%--rest隐藏域--%>
<input type="hidden" name="_method" value="PUT">
</c:if>
LastName:<form:input path="lastName" /><br>
Email:<form:input path="email" /><br>
<%
Map<String,String> gender=new HashMap<>();
gender.put("0","女");
gender.put("1","男");
request.setAttribute("gender",gender);
%>
性别:<form:radiobuttons path="gender" items="${gender}"/><br>
部门:<form:select path="department.did" items="${depts }" itemValue="did" itemLabel="departmentName"></form:select><br>
<input type="submit" value="提交">
</form:form>
2.经过控制器跳转到添加员工页面
/**
* 获取所有部门列表
* @param map 需要将部门信息返回到前端
* @return
*/
@RequestMapping(value="emp",method= RequestMethod.GET)
public String getdepts(Map<String,Object> map){
List<Department> list=departmentDao.getDepts();
map.put("depts",list);
//前端form标签中指定的modelAttribute属性需要在request存在
map.put("employee",new Employee());
return "addemp";
}
3.输入信息点击提交后经过控制器method="POST",调用dao将数据插入数据库
//添加员工
@RequestMapping(value="emp",method= RequestMethod.POST)
public String addEmps(Employee emp){
employeeDao.saveEmps(emp);
return "redirect:/emps";
}
EmployeeDao
/*
添加员工
*/
public int saveEmps(Employee emp){
String sql="insert into employees(lastName,email,gender,did) values(?,?,?,?)";
int i=jdbcTemplate.update(sql, emp.getLastName(),emp.getEmail(),emp.getGender(),emp.getDepartment().getDid());
return i;
}
三、修改员工
1.点击编辑后将员工eid传到控制器,获取到eid为该对象的员工对象,传回到addemp.jsp前端页面进行显示
<a href="emp/${emp.eid}">编辑</a>
EmployeeControl
//修改员工:进入修改页面
@RequestMapping(value="emp/{eid}",method= RequestMethod.GET)
public String editempin(@PathVariable Integer eid,Map<String,Object> map){
List<Department> list=departmentDao.getDepts();
map.put("depts",list);
Employee employee=employeeDao.getEmpById(eid);
map.put("employee",employee);
return "addemp";
}
EmployeeDao
//根据员工id获取员工对象
public Employee getEmpById(Integer eid){
String sql="select eid,lastName,email,gender,d.did did,departmentName " +
"from employees e,department d where e.did=d.did and eid=?";
Employee employee=jdbcTemplate.queryForObject(sql, new Object[]{eid}, new RowMapper<Employee>() {
@Override
public Employee mapRow(ResultSet rs, int i) throws SQLException {
Department department=new Department(rs.getInt("did"),rs.getString("departmentName"));
Employee emp=new Employee(rs.getInt("eid"),rs.getString("lastName"),
rs.getString("email"),rs.getInt("gender"),department);
return emp;
}
});
return employee;
}
2.此处修改页面和添加页面整合为一个页面,但是添加员工的时候没有eid传过去,但是修改信息的时候,要传eid过去,所以可以使用c:if来区分是添加还是修改。之前笔记有提到使用哪种请求方式。
<c:if test="${employee.eid!=null}">
<form:hidden path="eid"/>
<%--rest隐藏域--%>
<input type="hidden" name="_method" value="PUT">
</c:if>
3.将eid作为隐藏域提交过去之后,根据eid修改员工信息。
EmployeeControl
//修改员工
@RequestMapping(value="emp",method= RequestMethod.PUT)
public String editemp(Employee employee){
employeeDao.editEmp(employee);
return "redirect:/emps";
}
EmployeeDao
//修改员工
public int editEmp(Employee emp){
String sql="update employees set lastName=?,email=?,gender=?,did=? where eid=?";
int i=jdbcTemplate.update(sql,emp.getLastName(),emp.getEmail(),emp.getGender(),emp.getDepartment().getDid(),emp.getEid());
return i;
}
四、删除员工
1.点击删除之后,把eid传过去,根据eid删除员工对象。
<a href="emp/${emp.eid}" class="delete">删除</a>
EmployeeControl
@RequestMapping(value = "emp/{eid}",method=RequestMethod.DELETE)
public String deleteemp(@PathVariable Integer eid){
employeeDao.deleteEmp(eid);
return "redirect:/emps";
}
EmoloyeeDao
public int deleteEmp(Integer eid){
String sql="delete from employees where eid=?";
int i=jdbcTemplate.update(sql,eid);
return i;
}
注意:点击删除之后由于表单action为添加页面路径,所以需要书写js,让默认事件不要触发。
<script>
$(function(){
$(".delete").click(function(){
var href=$(this).attr("href");
$("form").attr("action",href).submit();
return false;//不会再执行默认事件
});
})
</script>
且需要表单再添加一个隐藏域,使得method=request.DELETE
<form action="" method="post">
<input type="hidden" name="_method" value="DELETE">
</form>
由于静态资源会被springmvc拦截所以要配置静态资源,有以下两种方式
<!--静态资源处理方式一:非银蛇url交给default servlet处理-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
<!--静态资源处理方式二:指定路径查找对应的的静态资源-->
<!--<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>-->
<!--<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>-->
<!--<mvc:resources mapping="/image/**" location="/image/**"></mvc:resources>-->
<!--<mvc:annotation-driven></mvc:annotation-driven>-->