SpringMVC(三十) 实例:SpringMVC_RESTRUL_CRUD_显示所有员工信息

Step by step to create a springMVC demo.

1. 创建一个dynamic web 工程。

2. 添加需要的jar文件,如下图:

3. 配置web.xml:配置dispatcher servlet; 配置hiddenhttpmethod

<?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_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Curd</display-name>

	<!-- The front controller of this Spring Web application, responsible for
		handling all application requests -->
	<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:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<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>

</web-app>

4. 创建SpringMVC.xml,创建Spring Bean Configuration file. 选中bean, context, mvc命名空间。

5. 编辑springmvc.xml文件。配置context:component-scan 和 InternalResourceViewResolver

<?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.3.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.3.xsd">

    <!-- autoScanComponent -->

    <context:component-scan base-package="com.atguigu.springmvc"></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>

</beans>

6.其它文件结构图如下:

7. 创建index.jsp文件。内容如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<a href="listAllEmployees">list all employees</a>

</body>
</html>

8. 创建entity和service Dao。entity定义了对象结构。service dao定义了对象业务操作行为,如创建,查询和删除。

Department类:

package com.atguigu.springmvc.entities;

public class Department {

    private Integer id;
    private String departmentName;

    public Department(Integer id, String departmentName) {
        super();
        this.id = id;
        this.departmentName = departmentName;
    }

    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;
    }

}

Employee类:

package com.atguigu.springmvc.entities;

import java.util.Date;

public class Employee {

    private Integer id;
    private String lastname;
    private String email;
    private Integer gender;
    private Department department;
    private Date birth;
    private Float salary;

    public Employee(Integer id, String lastname, String email, Integer gender, Department department, Date birth,
            Float salary) {
        super();
        this.id = id;
        this.lastname = lastname;
        this.email = email;
        this.gender = gender;
        this.department = department;
        this.birth = birth;
        this.salary = salary;
    }

    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;
    }
    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;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Float getSalary() {
        return salary;
    }
    public void setSalary(Float salary) {
        this.salary = salary;
    }

}

9. Dao类 demo代码如下:

DepartmentDao:

package com.atguigu.springmvc.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.atguigu.springmvc.entities.Department;

@Repository
public class DepartmentDao {

    private static Map<Integer, Department> departments = null;

    static{
        departments = new HashMap<>();
        departments.put(101, new Department(101,"D-AA"));
        departments.put(102, new Department(101,"D-AA"));
        departments.put(103, new Department(101,"D-AA"));
        departments.put(104, new Department(101,"D-AA"));
        departments.put(105, new Department(101,"D-AA"));
    }

    public Collection<Department> getDepartment(Integer id) {
        System.out.println(departments.values().getClass());
        System.out.println(departments.values());
        return departments.values();
    }

}

EmployeeDao:

package com.atguigu.springmvc.dao;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.atguigu.springmvc.entities.Department;
import com.atguigu.springmvc.entities.Employee;

@Repository
public class EmployeeDao {

    private static Map<Integer, Employee> employess = null;

    @Autowired
    private DepartmentDao departmentDao;

    static{
        employess = new HashMap<>();

        employess.put(1001, new Employee(1001,"E-AA", "[email protected]", 1, new Department(101, "D-AA"), new Date(), (float) 123));
        employess.put(1002, new Employee(1002,"E-AA", "[email protected]", 1, new Department(102, "D-AA"), new Date(), (float) 124));
        employess.put(1003, new Employee(1003,"E-AA", "[email protected]", 1, new Department(103, "D-AA"), new Date(), (float) 125));
        employess.put(1004, new Employee(1004,"E-AA", "[email protected]", 1, new Department(104, "D-AA"), new Date(), (float) 126));
        employess.put(1005, new Employee(1005,"E-AA", "[email protected]", 1, new Department(105, "D-AA"), new Date(), (float) 127));
    }

    public Collection<Employee> getAll() {
        return employess.values();
    }

}

10. 通过Controller控制listAllEmployees action的视图返回,在该controller方法中,把所有的employess对象通过一个集合的方式传到视图中,视图可以通过获取该session attribute,从而获取相关数据。

package com.atguigu.springmvc.handlers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.atguigu.springmvc.dao.EmployeeDao;

@Controller
public class ListEmployees {

    @Autowired
    private EmployeeDao employeeDao;

    @RequestMapping("listAllEmployees")
    public String listAllEmployees(Map<String,Object> map) {
        map.put("employees",employeeDao.getAll());
        return "list";
    }

}

11. 上面代码使返回视图为list.jsp。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h1>hello world</h1>

    <c:if test="${empty requestScope.employees }">
        <h1>no employee</h1>
    </c:if>

    <c:if test="${!empty requestScope.employees }">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>ID</th>
                <th>LastName</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Department</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
            <c:forEach items="${requestScope.employees }" var="emp">
                <tr>
                    <td>${emp.id }</td>
                    <td>${emp.lastname }</td>
                    <td>${emp.email }</td>
                    <td>${emp.gender == 0 ? "Female" : "Male" }</td>
                    <td>${emp.department.departmentName }</td>
                    <td><a href="">Edit</a></td>
                    <td><a href="">Delete</a></td>
                </tr>
            </c:forEach>
        </table>
    </c:if>

</body>
</html>

12. 完成以上代码后,可以执行测试。

时间: 2024-12-05 15:50:18

SpringMVC(三十) 实例:SpringMVC_RESTRUL_CRUD_显示所有员工信息的相关文章

第三十八章

上德不德,是以有德:下德不失德,是以无德.上德无为而无以为也.上仁为之而无以为也:上义为之而有以为也.上礼为之而莫之应也,则攘臂而扔之.故失道而后德,失德而后仁,失仁而后义,失义而后礼.夫礼者,忠信之薄也,而乱之首也.前识者,道之华也,而愚之首也.是以大丈夫居其厚,不居其薄,居其实,不居其华.故去彼取此. 第三十八章1 想索取回报的行善,是“无德” 上德不德,是以有德:下德不失德,是以无德. (第三十七章 第3讲) 真正修行高的人,不会以“德”的名义去做事,不会标榜自己的德行,这是真正的“有德”

python实战演练(六)员工信息查询系统

一 实现功能 (1).工信息表程序,实现增删改查操作: (2).可进行模糊查询,语法至少支持下面3种:        select name,age from staff_table where age > 22       select * from staff_table where dept = "IT"       select * from staff_table where enroll_date like "2013"(3).查到的信息,打印后,

【FastDev4Android框架开发】实例解析之SwipeRefreshLayout+RecyclerView+CardView(三十五)

转载请标明出处: http://blog.csdn.net/developer_jiangqq/article/details/50087873 本文出自:[江清清的博客] (一).前言: 作为Android L开始,Google更新了新控件RecyclerView和CardView,这两个控件在之前的文章中已经做了详细介绍和使用,同时在前面还对下拉刷新组件SwipeRefreshLayout进行相关讲解.本来该专题不在更新了,正好昨天有一个群友问到了怎么样结合SwipeRefreshLayou

Android实战简易教程-第三十九枪(第三方短信验证平台Mob和验证码自动填入功能结合实例)

用户注册或者找回密码时一般会用到短信验证功能,这里我们使用第三方的短信平台进行验证实例. 我们用到第三方短信验证平台是Mob,地址为:http://mob.com/ 一.注册用户.获取SDK 大家可以自行注册,得到APPKEY和APPSECRET,然后下载SDK,包的导入方式如截图: 二.主要代码 SMSSendForRegisterActivity.java:(获取验证码页) package com.qiandaobao.activity; import java.util.regex.Mat

QT开发(三十)——计算器实例开发

QT开发(三十)--计算器实例开发 一.计算器界面制作 计算器界面需要QWidget组件作为顶层窗口,QLineEdit组件作为输入框,QPsuhButton作为按钮. 界面规划设计如下: #include <QApplication> #include <QWidget> #include <QLineEdit> #include <QPushButton>   int main(int argc, char *argv[]) {     QApplica

Python进阶(三十四)-Python3多线程解读

Python进阶(三十四)-Python3多线程解读 线程讲解 ??多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度. 程序的运行速度可能加快. 在一些等待的任务实现上如用户输入.文件读写和网络收发数据等,线程就比较有用了.在这种情况下我们可以释放一些珍贵的资源如内存占用等等. ??线程在执行过程中与进程还是有区别的.每个独立

QT开发(三十八)——Model/View框架编程

QT开发(三十八)--Model/View框架编程 一.自定义模型 1.自定义只读模型 QAbstractItemModel为自定义模型提供了一个足够灵活的接口,能够支持数据源的层次结构,能够对数据进行增删改操作,还能够支持拖放.QT提供了 QAbstarctListModel和QAbstractTableModel两个类来简化非层次数据模型的开发,适合于结合列表和表格使用. 自定义模型需要考虑模型管理的的数据结构适合的视图的显示方式.如果模型的数据仅仅用于列表或表格的显示,那么可以使用QAbs

三十项调整助力 Ubuntu 13.04 更上一层楼

在Ubuntu 13.04 Raring Ringtail安装完成之后,我们还有三十项调整需要进行. 1.Ubuntu 13.04 Raring Ringtail安装完毕后,我又进行了一系列工作 大家想知道Ubutnu最新版本带来哪些新内容吗?我认为其中引发讨论最多的话题在于,与前代版本相比(即12.10'Quantal Quetzal')新系统的性能表现并不理想.它不仅延迟明显,而且存在严重的稳定性问题.Raring Ringtail也并不在黄油计划的适用范围之内.但无论如何,Ubuntu 1

三十二、Java图形化界面设计——布局管理器之CardLayout(卡片布局)

摘自 http://blog.csdn.net/liujun13579/article/details/7773945 三十二.Java图形化界面设计--布局管理器之CardLayout(卡片布局) 卡片布局能够让多个组件共享同一个显示空间,共享空间的组件之间的关系就像一叠牌,组件叠在一起,初始时显示该空间中第一个添加的组件,通过CardLayout类提供的方法可以切换该空间中显示的组件. 1.  CardLayout类的常用构造函数及方法 2.  使用CardLayout类提供的方法可以切换显