SpringMVC简单地入门程序

SpringMVC是一个很流行的MVC框架,在系统地学习完Sturts2之后据说很容易就能掌握它。所以找来了一套视频,先从最简单地入门。

1.新建Web项目

2.修改项目的编码UTF-8

3.拷贝Jar包(SpringMVC3.1.1)


4.新建sourcefolder以及下面的package.


5.在web.xml中添加DispatcherServlet的配置。就像Struts2中需要配置StrutsPrepareAndExecuteFilter一样。

<?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>springmvc</display-name>
  <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>
  <servlet-mapping>
  	<servlet-name>springDispatcherServlet</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
6.根据web.xml中的配置classpath:spirngmvc.xml。在根目录下创建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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="   
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
	
	<!-- 配置自动扫描的包 -->
	<context:component-scan base-package="com.cars.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>
	
	<mvc:default-servlet-handler/>
	
	<mvc:annotation-driven/>
</beans>

根据配置文件需要在WEB-INF下新建文件夹views。文件的后缀为.jsp

7.准备数据:主要为了实现SpringMVC,所以Service层省掉了,数据也采用Map进行初始化。现在Model层新建两个实体:Department和Employee的实体。一对多的关系。

Department:

package com.cars.springmvc.model;

public class Department {
	private Integer id;
	private String departmentName;
	
	public Department(int i, String string) {
		this.id = i;
		this.departmentName = string;
	}

	public Department() {
	}

	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.cars.springmvc.model;

public class Employee {
	private Integer id;
	private String lastName;
	private String email;
	private Integer gender;
	private Department department;
	public Employee(int i, String string, String string2, int j, Department department2) {
		this.id = i;
		this.lastName = string;
		this.email = string2;
		this.gender = j;
		this.department = department2;
	}
	
	public Employee() {	}

	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;
	}
	
}
对应的Dao层代码:

DepartmentDao

package com.cars.springmvc.dao;

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

import org.springframework.stereotype.Repository;

import com.cars.springmvc.model.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(101,"D_BB"));
		departments.put(103, new Department(101,"D_CC"));
		departments.put(104, new Department(101,"D_DD"));
		departments.put(105, new Department(101,"D_EE"));
	}
	
	public Department getDepartment(int i){
		return departments.get(i);
	}
	
	public Collection<Department> getDepartments(){
		return departments.values();
	}
}
EmployeeDao:

package com.cars.springmvc.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.cars.springmvc.model.Department;
import com.cars.springmvc.model.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", "aa@163.com", 0, new Department(102, "D-BB")));
		employees.put(1003, new Employee(1003, "E-CC", "aa@163.com", 1, new Department(103, "D-CC")));
		employees.put(1004, new Employee(1004, "E-DD", "aa@163.com", 0, new Department(104, "D-DD")));
		employees.put(1005, new Employee(1005, "E-EE", "aa@163.com", 1, new Department(105, "D-EE")));
	}
	
	public Collection<Employee> getEmployees(){
		return employees.values();
	}
	public Employee getEmployee(Integer id){
		return employees.get(id);
	}
	
	//保存方法和删除方法
	
	private static Integer initId = 1006;
	
	public void saveEmployee(Employee employee){
		if(employee.getId() == null){
			employee.setId(initId++);
		}
		employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
		employees.put(employee.getId(), employee);
	}
	
	public void removeEmployee(Integer id){
		employees.remove(id);
	}
}
8.完成list方法,显示所有的员工信息,映射Handler中的方法/list

Handler代码:

package com.cars.springmvc.handler;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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 com.cars.springmvc.dao.DepartmentDao;
import com.cars.springmvc.dao.EmployeeDao;
import com.cars.springmvc.model.Employee;
@Controller
public class EmployeeHandler {
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private DepartmentDao departmentDao;
	
	@RequestMapping("/list")
	public String list(Map<String,Object> map){
		map.put("employees", employeeDao.getEmployees());
		return "list";
	}
	
	@RequestMapping(value="/emp",method=RequestMethod.GET)
	public String input(Map<String,Object> map){
		//加载department下拉框
		map.put("departments", departmentDao.getDepartments());
		map.put("employee",new Employee());
		return "input";
	}
	
	@RequestMapping(value="/emp",method=RequestMethod.POST)
	public String add(Employee employee){
		employeeDao.saveEmployee(employee);
		return "redirect:/list";
	}
	@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
	public String del(@PathVariable("id") Integer id){
		employeeDao.removeEmployee(id);
		return "redirect:/list";
	}
	
	@RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
	public String input(@PathVariable("id") Integer id,Map<String,Object> map){
		//需要回显出数据
		map.put("employee",employeeDao.getEmployee(id));
		map.put("departments", departmentDao.getDepartments());
		return "input";
	}
	
	@RequestMapping(value="/emp",method=RequestMethod.PUT)
	public String edit(Employee employee){
		employeeDao.saveEmployee(employee);
		return "redirect:/list";
	}
}

9.在WEB-INF/views下新建页面list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ 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">
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
	$(function(){
		//alert("123");
		$(".delete").click(function(){
			var href = $(this).attr("href");
			$("form").attr("action",href).submit();
			return false;
		}); 
	});
</script>
<title>Insert title here</title>
</head>
<body>
	
	<form action="" method="POST">
	   <input type="hidden" name="_method" value="delete">
	</form>
	<!-- 若没有数据,则显示没有员工信息,若有信息,则显示表格信息 -->
	<c:if test="${empty requestScope.employees }">没有任何员工信息</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="emp/${emp.id }">Edit</a> </td>
				<td><a class="delete" href="emp/${emp.id }">Delete</a> </td>
			</tr>
			</c:forEach>
		</table>	
	</c:if>
	
	<a href="emp">Add New Employee</a>
</body>
</html>

这样在浏览器输入地址:http://localhost:8080/spirngmvc2/list   看到的效果为:

除了LIst的功能,我们再看看跳转到Add页面

我们点击Add NEW Employee则连接到emp。映射到Handler中方法:

	@RequestMapping(value="/emp",method=RequestMethod.GET)
	public String input(Map<String,Object> map){
		//加载department下拉框
		map.put("departments", departmentDao.getDepartments());
		map.put("employee",new Employee());
		return "input";
	}
新建input.jsp

<%@ 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" %>
<%@ page language="java" import="java.util.Map" %>
<%@ page language="java" import="java.util.HashMap" %>
<!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:form action="${pageContext.request.contextPath }/emp" method="POST" modelAttribute="employee">
		<c:if test="${employee.id == null}">
			lastName:<form:input path="lastName"/>
		</c:if>
		<c:if test="${employee.id != null}">
			<form:hidden path="id"/>
			<input type="hidden" name="_method" value="PUT">
		</c:if>
		<br>
		Email:<form:input path="email"/>
		<br>
		<%
			Map<String,String> genders = new HashMap<String,String>();
			genders.put("0", "Male");
			genders.put("1", "Female");
			
			request.setAttribute("genders", genders);
		%>
		Gender:<form:radiobuttons path="gender" items="${genders }"/>
		<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>
效果为:



其他的功能如:Add,Edit和Delete,请自行查看效果。












评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值