文档章节

springmvc框架搭建案例

architect刘源源
 architect刘源源
发布于 06/19 00:12
字数 2106
阅读 66
收藏 0

web.xml

<?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">
  <display-name>RestEmp</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <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>
  	<!-- 过滤器用/*过滤所有请求,servlet用/来过滤所有请求,包括静态的,需要在springmvc.xml中加注解进行处理
  	<mvc:default-servlet-handler/>静态资源交由tomcat默认的servlet处理,非静态的交由dispatcherServlet处理
	<mvc:annotation-driven />开启注解驱动
  	 -->
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
 <!-- 保证可以通过表单提交PUT,DELETE方式的请求 -->
  <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>
  
  <!-- 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>
			<!-- 指定springmvc配置文件所在位置 -->
			<param-value>classpath:springMVC.xml</param-value>
		</init-param>
		<!-- 项目启动时加载此DispatcherServlet这个Servlet 当值为正数,项目启动时加载,负数或者0请求党文时加载 -->
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<!-- / DispatcherServlet会帮我们截获所有的url请求,并将请求发送给对应的controller。
                          对,是所有的请求!也包括静态文件,比如.js文件,图片文件,css文件的请求。404-->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
  
</web-app>

springmvc.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.rest.crud"></context:component-scan>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 
		配置Tomcat中默认的servlet,DefaultServlet
		注意:当DefaultServlet所设置的<url-pattern>的值和开发人员所配置的servlet的<url-pattern>相同,以开发人员所配置的servlet优先
		作用:当客户端发送请求,由于DefaultServlet所设置的<url-pattern>的值和开发人员所配置DispatcherServlet的<url-pattern>都是/
			因此先通过DispatcherServlet处理请求,找该请求是否有相对应的处理器,有则处理,无则交给DefaultServlet处理
	 -->
	<mvc:default-servlet-handler/>
	<!--这个陪之后才支持java对象转换成json对象
     * springMVC处理json的四个条件:
	 * 1、导入jackson的jar
	 * 2、在springMVC的配置文件中开启MVC驱动,<mvc:annotation-driven />
	 * 3、在处理ajax请求的方法上加上注解@ResponseBody
	 * 4、将要转换为json且响应到客户端的数据,直接作为该方法的返回值返回
    -->
	<mvc:annotation-driven />
<!-- 
		处理文件,将客户端上传的File文件,处理为MultipartFile
		注意:文件解析器的bean中id必须设置为multipartResolver
	 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置文件解析的编码,注意:一定要和页面的pageEncoding保持一致 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 设置最大上传文件大小 -->
		<property name="maxUploadSize" value="88888888"></property>
	</bean>
	
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
			<!-- error为对应的视图名称 -->
				<prop key="java.lang.NullPointerException">error</prop>
			</props>
		</property>
	</bean>

	<!-- <mvc:interceptors>
		默认拦截所有请求
		<bean class="com.atguigu.interceptor.FirstInterceptor"></bean>
		<bean class="com.atguigu.interceptor.SecondInterceptor"></bean>
		此方式要求拦截器类上必须加注解@Component
		<ref bean="firstInterceptor"/>
		
		设置自定义拦截方式
		<mvc:interceptor>
			<bean></bean>
			<mvc:mapping path=""/>
			<mvc:exclude-mapping path=""/>
		</mvc:interceptor>
	</mvc:interceptors> -->

</beans>
package com.atguigu.rest.crud.bean;

public class Department {

	private Integer id;
	private String departmentName;

	public Department() {
		// TODO Auto-generated constructor stub
	}
	
	public Department(int i, String string) {
		this.id = i;
		this.departmentName = string;
	}

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

	@Override
	public String toString() {
		return "Department [id=" + id + ", departmentName=" + departmentName
				+ "]";
	}
	
}
package com.atguigu.rest.crud.bean;

public class Employee {

	private Integer id;
	private String lastName;

	private String email;
	//1 male, 0 female
	private Integer gender;
	
	private Department department;

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

	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email="
				+ email + ", gender=" + gender + ", department=" + department
				+ "]";
	}

	public Employee(Integer id, String lastName, String email, Integer gender,
			Department department) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.gender = gender;
		this.department = department;
	}

	public Employee() {
		// TODO Auto-generated constructor stub
	}
}
package com.atguigu.rest.crud.controller;

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

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

import com.atguigu.rest.crud.bean.Department;
import com.atguigu.rest.crud.bean.Employee;
import com.atguigu.rest.crud.dao.DepartmentDao;
import com.atguigu.rest.crud.dao.EmployeeDao;

public class EmpController_Old {

	@Autowired
	private EmployeeDao employeeDao;
	
	@Autowired
	private DepartmentDao departmentDao;
	
	/**
	 * 获取所有的员工信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/emps")
	public String getAll(Map<String, Object> map) {
		Collection<Employee> emps = employeeDao.getAll();
		map.put("emps", emps);
		return "list";
	}
	
	/**
	 * 跳转到添加页面
	 * @return
	 */
	@RequestMapping(value="/emp", method=RequestMethod.GET)
	public String toAdd(Map<String, Object> map) {
		Collection<Department> depts = departmentDao.getDepartments();
		map.put("depts", depts);
		return "add";
	}
	
	/**
	 * 添加员工信息
	 * @param employee
	 * @return
	 */
	@RequestMapping(value="/emp", method=RequestMethod.POST)
	public String addEmp(Employee employee) {
		employeeDao.save(employee);
		return "redirect:/emps";
	}
	
	/**
	 * 获取要回显的数据,跳转到修改页面,并回显
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
	public String toUpdate(@PathVariable("id") Integer id, Map<String, Object> map) {
		//获取要修改的员工信息
		Employee emp = employeeDao.get(id);
		//所有的部门信息,供用户选择
		Collection<Department> depts = departmentDao.getDepartments();
		map.put("emp", emp);
		map.put("depts", depts);
		return "update";
	}
	
	@RequestMapping(value="/emp", method=RequestMethod.PUT)
	public String updateEmp(Employee employee) {
		employeeDao.save(employee);//修改
		return "redirect:/emps";
	}

    @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
	public String deleteEmp(@PathVariable("id") Integer id) {
		employeeDao.delete(id);
		return "redirect:/emps";
	}
	
}
package com.atguigu.rest.crud.dao;

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

import org.springframework.stereotype.Repository;

import com.atguigu.rest.crud.bean.Department;


@Repository
public class DepartmentDao {

	private static Map<Integer, Department> departments = null;
	
	static{
		departments = new HashMap<Integer, Department>();
		
		departments.put(101, new Department(101, "D-AA"));
		departments.put(102, new Department(102, "D-BB"));
		departments.put(103, new Department(103, "D-CC"));
		departments.put(104, new Department(104, "D-DD"));
		departments.put(105, new Department(105, "D-EE"));
	}
	
	public Collection<Department> getDepartments(){
		return departments.values();
	}
	
	public Department getDepartment(Integer id){
		return departments.get(id);
	}
	
}
package com.atguigu.rest.crud.dao;

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

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

import com.atguigu.rest.crud.bean.Department;
import com.atguigu.rest.crud.bean.Employee;

@Repository
public class EmployeeDao {

	private static Map<Integer, Employee> employees = null;
	
	@Autowired
	private DepartmentDao departmentDao;
	
	static{
		employees = new HashMap<Integer, Employee>();

		employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
		employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
		employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
		employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
		employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
	}
	
	private static Integer initId = 1006;
	
	public void save(Employee employee){
		if(employee.getId() == null){
			employee.setId(initId++);
		}
		
		employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
		employees.put(employee.getId(), employee);
	}
	
	public Collection<Employee> getAll(){
		return employees.values();
	}
	
	public Employee get(Integer id){
		return employees.get(id);
	}
	
	public void delete(Integer id){
		employees.remove(id);
	}
}

list.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>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_work.css" />
<script type="text/javascript" src="${pageContext.servletContext.contextPath }/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
	$(function(){
        $(".del").click(function(){
         if(confirm("确定要删除么?")){
             $(form).attr("action",this.href).submit();
                  return false;//取消表单的默认提交行为
         }
             return false;
        });
    });
</script>
</head>
<body>

	<table>
		<tr>
			<th>ID</th>
			<th>LASTNAME</th>
			<th>EMAIL</th>
			<th>GENDER</th>
			<th>DEPARTMENTNAME</th>
			<th>OPTION(<a href="emp">ADD</a>)</th>
		</tr>
		<c:forEach items="${emps }" var="emp">
			<tr>
				<td>${emp.id }</td>
				<td>${emp.lastName }</td>
				<td>${emp.email }</td>
				<td>${emp.gender==0?'女':'男' }</td>
				<td>${emp.department.departmentName }</td>
				<td>
					<a href="emp/${emp.id }">UPDATE</a>
					<a class="del" href="emp/${emp.id }">DELETE</a>
				</td>
			</tr>
		</c:forEach>
	</table>
	
	<form method="post">
		<input type="hidden" name="_method" value="DELETE" />
	</form>

</body>
</html>

add.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>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_work.css" />
</head>
<body>
	
	<form action="emp" method="post">
		<table>
			<tr>
				<th colspan="2">添加员工信息</th>
			</tr>
			<tr>
				<td>LASTNAME</td>
				<td>
					<input type="text" name="lastName" />
				</td>
			</tr>
			<tr>
				<td>EMAIL</td>
				<td>
					<input type="text" name="email" />
				</td>
			</tr>
			<tr>
				<td>GENDER</td>
				<td>
					<input type="radio" name="gender" value="1" />男
					<input type="radio" name="gender" value="0" />女
				</td>
			</tr>
			<tr>
				<td>DEPARTMENT</td>
				<td>
					<select name="department.id">
						<option>-SELECT DEPARTMENT-</option>
						<c:forEach items="${depts }" var="dept">
							<option value="${dept.id }">${dept.departmentName }</option>
						</c:forEach>
					</select>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="ADD" />
				</td>
			</tr>
		</table>
	</form>

</body>
</html>

update.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>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_work.css" />
</head>
<body>
	
	<form action="${pageContext.servletContext.contextPath }/emp" method="post">
		<input type="hidden" name="id" value="${emp.id }" />
		<input type="hidden" name="_method" value="PUT" />
		<table>
			<tr>
				<th colspan="2">修改员工信息</th>
			</tr>
			<tr>
				<td>LASTNAME</td>
				<td>
					<input type="text" name="lastName" value="${emp.lastName }" />
				</td>
			</tr>
			<tr>
				<td>EMAIL</td>
				<td>
					<input type="text" name="email" value="${emp.email }" />
				</td>
			</tr>
			<tr>
				<td>GENDER</td>
				<td>
					<input type="radio" name="gender" value="1" ${emp.gender == 1?'checked':'' } />男
					<input type="radio" name="gender" value="0" ${emp.gender == 0?'checked':'' } />女
					 <input type="radio" name="gender" value="1" <c:if test="${emp.gender == 1 }">checked="checked"</c:if> />男
					<input type="radio" name="gender" value="0" <c:if test="${emp.gender == 0 }">checked="checked"</c:if> />女
				</td>
			</tr>
			<tr>
				<td>DEPARTMENT</td>
				<td>
					<select name="department.id">
						<option>-SELECT DEPARTMENT-</option>
						<c:forEach items="${depts }" var="dept">
							<option value="${dept.id }" ${dept.id == emp.department.id?'selected':'' }>${dept.departmentName }</option>
						</c:forEach>
					</select>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="UPDATE" />
				</td>
			</tr>
		</table>
	</form>

</body>
</html>

 

© 著作权归作者所有

architect刘源源

architect刘源源

粉丝 169
博文 564
码字总数 941209
作品 0
浦东
程序员
私信 提问
spring原理案例-基本项目搭建 01 spring framework 下载 官网下载spring jar包

下载spring http://spring.io/ 最重要是在特征下面的这段话,需要注意: All avaible features and modules are described in the Modules section of the reference documentation. Their ......

noteless
2016/02/24
0
0
SpringBoot介绍及常用的搭建方式

SpringBoot简介 Spring Boot是Spring社区发布的一个开源项目,旨在帮助开发者快速并且更简单的构建项目。它使用习惯优于配置的理念让你的项目快速运行起来,使用Spring Boot很容易创建一个独...

Hans的博客
01/21
0
0
2018年互联网架构主流微服务架构之潮流的主先锋Spring Boot 2.0

一、Spring Boot 介绍 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定...

A尚学堂Len老师
2018/08/21
0
0
spring springmvc mybatis maven 项目整合示例-导航页面

spring原理 实践解析-简单的helloworld spring原理案例-基本项目搭建 01 spring framework 下载 官网下载spring jar包 spring原理案例-基本项目搭建 02 spring jar包详解 spring jar包的用途...

noteless
2018/06/29
0
0
从零学习Spring MVC框架「环境搭建和MVC架构」

这是Spring MVC框架教程的第一篇,首先为大家讲解MVC架构思想,MVC模式并不是Javaweb项目中独有的,MVC是一种软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型「Model」、视...

技术小能手
2018/07/18
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Replugin借助“UI进程”来快速释放Dex

public static boolean preload(PluginInfo pi) { if (pi == null) { return false; } // 借助“UI进程”来快速释放Dex(见PluginFastInstallProviderProxy的说明) return PluginFastInsta......

Gemini-Lin
今天
4
0
Hibernate 5 的模块/包(modules/artifacts)

Hibernate 的功能被拆分成一系列的模块/包(modules/artifacts),其目的是为了对依赖进行独立(模块化)。 模块名称 说明 hibernate-core 这个是 Hibernate 的主要(main (core))模块。定义...

honeymoose
今天
4
0
CSS--属性

一、溢出 当内容多,元素区域小的时候,就会产生溢出效果,默认是纵向溢出 横向溢出:在内容和容器之间再套一层容器,并且内部容器要比外部容器宽 属性:overflow/overflow-x/overflow-y 取值...

wytao1995
今天
4
0
精华帖

第一章 jQuery简介 jQuery是一个JavaScript库 jQuery具备简洁的语法和跨平台的兼容性 简化了JavaScript的操作。 在页面中引入jQuery jQuery是一个JavaScript脚本库,不需要特别的安装,只需要...

流川偑
今天
7
0
语音对话英语翻译在线翻译成中文哪个方法好用

想要进行将中文翻译成英文,或者将英文翻译成中文的操作,其实有一个非常简单的工具就能够帮助完成将语音进行翻译转换的软件。 在应用市场或者百度手机助手等各大应用渠道里面就能够找到一款...

401恶户
今天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部