springmvc----REST风格CRUD----笔记

先说坑:

	
		HiddenHttpMethodFilter
		org.springframework.web.filter.HiddenHttpMethodFilter
	
	
		HiddenHttpMethodFilter
		/*	
		FORWARD
        REQUEST
	

本以为添加了HiddenHttpMethodFilter后springmvc的框架会自己处理好表单的隐藏域和http协议结果还是除了post get外 报错JSPs only permit GET, POST or HEAD. Jasper also permits OPTIONS,查了资料,貌似tomcat7.0没问题,其他版本好像就有这样的问题。

于是没有办法在PUT和DELETE的控制器方法上加了@ResponseBody注解,该注解把返回值直接输出到页面而不是再次交给框架去寻找view,我还用了原生的servlet的response做重定向。

2.post中文参数乱码
首先把所有jsp页面的encoding全部改为utf8无效。
页面内和控制器方法内把request.setCharacterEncoding(“UTF-8”);方法设置为utf8无效。
把tomcat server.xml的


设置为utf8还是无效。

最终添加一个过滤器 且在过滤器中设置

request.setCharacterEncoding("UTF-8");

解决问题

回到主题

一个小案例,没有用数据库,数据用了静态成员变量。
为了简洁,没有对数据进行校验
公司员工表,员工类和部门类 里面分别都是两个字段 id和名字。

实现的功能分别是员工信息的增删查改。

功能很简单下面直接放代码和配置文件不说明。

web.xml




	
	
		springDispatcherServlet
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:springmvc.xml
		
		1
	

	
	
		springDispatcherServlet
		/
	
	
	
		encodingfilter
		top.demo.crud.filter.EncodingFilter
	
	
	
		encodingfilter
		/*
		 
        FORWARD
        REQUEST
	
	
	
		HiddenHttpMethodFilter
		org.springframework.web.filter.HiddenHttpMethodFilter
	
	
		HiddenHttpMethodFilter
		/*	
		FORWARD
        REQUEST
	



springmvc配置





	
	
	
	
		
		
		




	
	
	



员工和部门bean

package top.demo.crud.bean;

public class Department {
	
	public int id;
	public String departmentName;
	
	
	public Department() {
		
	}
	
	@Override
	public String toString() {
		return "Department [id=" + id + ", departmentName=" + departmentName + "]";
	}


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


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public String getDepartmentName() {
		return departmentName;
	}


	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}


}

package top.demo.crud.bean;

public class Employ {
	
	public int id;
	public String name;
	public Department department=new Department();
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Employ(int id, String name, Department department) {
		super();
		this.id = id;
		this.name = name;
		this.department = department;

	}
	public Employ() {

	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Employ [id=" + id + ", name=" + name + ", department=" + department + "]";
	}
	public Department getDepartment() {
		return department;
	}
	public void setDepartment(Department department) {
		this.department = department;
	}

}

封装员工和部门DAO操作

package top.demo.crud.dao;

import java.util.LinkedList;
import java.util.List;

import org.springframework.stereotype.Component;

import top.demo.crud.bean.Department;

@Component
public class DepartmentDao {

	
	
	public DepartmentDao() {
		
	}
	
	public static List departments=new LinkedList<>();
	
	static{
		departments.add(new Department(1,"市场部"));
		departments.add(new Department(2,"财务部"));
		departments.add(new Department(3,"人事部"));
		departments.add(new Department(4,"xx部"));
	}
	
	
	public Department getOneDepartment(int id) {
		Department ret=null;
		for(Department department:departments)
		{
			if(id==department.getId())
			{
				ret=department;
				break;
			}
		}
		return ret;
	}
	
	public List getAllDepartment(){
		
		
		return departments;
	}
	
}

package top.demo.crud.dao;

import java.util.LinkedList;
import java.util.List;

import org.springframework.stereotype.Component;

import top.demo.crud.bean.Department;
import top.demo.crud.bean.Employ;

@Component
public class EmployDao {
	
	
	public EmployDao() {
		
		
	}
	
	public static List employs=new LinkedList<>();
	
	static{
		employs.add( new Employ(1, "小王",new Department(1, "市场部")) );
		employs.add( new Employ(2, "小李",new Department(2, "财务部")) );
		employs.add( new Employ(3, "小张",new Department(3, "人事部")) );
		employs.add( new Employ(4, "小红",new Department(4, "xx部")) );
	}
	
	public List getAllEmp() {
		
		return employs;
	}
	
	public Employ getOneEmp(int id) {
		
		Employ ret=null;
		
		for(Employ employ:employs) {
			if(employ.getId()==id)
			{
				ret=employ;
				break;
			}
		}
		
		return ret;
	}
	
	public boolean addEmp(Employ emp) {
		int id=1;
		if(employs.size()>0)
			 id=employs.get(employs.size()-1).getId()+1;
		/*模拟主键自增*/
		emp.setId(id);
		employs.add(emp);
		
		return true;
	}
	
	public void deleteEmp(int id) {
			
		for(Employ employ:employs) {
			if(employ.getId()==id)
			{
				employs.remove(employ);
				break;
			}
		}
		
	}
	
	public void update(Employ employ) {
		
		Employ employOld=null;
		for(Employ employTemp:employs) {
			if(employTemp.getId()==employ.id)
			{
				employOld=employTemp;
				break;
			}
		}
		
		employOld.name=employ.name;
		employOld.department=employ.department;
	}

}

编码过滤器

package top.demo.crud.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodingFilter implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		System.out.println("encoding  filter");
		request.setCharacterEncoding("UTF-8");
		chain.doFilter(request, response);
		
	}


}

控制器

package top.demo.crud.control;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.ModelAndView;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.xml.internal.ws.addressing.policy.AddressingPolicyMapConfigurator;

import top.demo.crud.bean.Department;
import top.demo.crud.bean.Employ;
import top.demo.crud.dao.DepartmentDao;
import top.demo.crud.dao.EmployDao;

@Controller
public class MyMainControl {
	
	
	@Autowired
	private EmployDao employDao;
	@Autowired
	private DepartmentDao departmentDao;
	
	
	@RequestMapping("/showemp")
	public ModelAndView showEmp(Map map) {
		
		ModelAndView modelAndView=new ModelAndView("showEmp");
		modelAndView.addObject("emps", employDao.getAllEmp());
		
		return modelAndView;
	}
	
	@RequestMapping(value="addEmp",method=RequestMethod.GET)
	public String addEmp(Mapmap ) {
		System.out.println("get");
		
		map.put("departments", departmentDao.getAllDepartment());
		
		/*为了让 spring form标签正常显示 需要添加一个bean和form标签modelAttribute属性对应*/
		map.put("employ", new Employ());
		
		return "addEmp";
	}
	
	@RequestMapping(value="addEmp",method=RequestMethod.POST)
	public String addEmp(Employ employ,Mapmap) {
		
		System.out.println("post");	
		
		Listlist=departmentDao.getAllDepartment();
		
		for(Department department:list) {
			if(department.getId()==employ.getDepartment().getId())
			{
				employ.getDepartment().setDepartmentName(department.getDepartmentName());
				break;
			}
		}
		System.out.println(employ);
		employDao.addEmp(employ);
		
		map.put("message", "添加成功");
		
		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value="addEmp/{id}",method=RequestMethod.DELETE)
	public void deleteEmp(@PathVariable("id") int id,HttpServletRequest request,HttpServletResponse response) {
		
		System.out.println("DELETE"+id);
		employDao.deleteEmp(id);

		try {
			response.sendRedirect(request.getContextPath()+"/info/success.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="addEmp/{id}",method=RequestMethod.GET)
	public String updateEmp(@PathVariable("id") int id,Mapmap) {
	
		map.put("departments", departmentDao.getAllDepartment());
		
		/*为了让 spring form标签正常显示 需要添加一个bean和form标签modelAttribute属性对应*/
		Employ employ=employDao.getOneEmp(id);
		map.put("employ",employ);
		
		return "addEmp";
	}
	
	
	@ResponseBody
	@RequestMapping(value="addEmp",method=RequestMethod.PUT)
	public String updateEmp(Employ employ,HttpServletRequest request,HttpServletResponse response) {
	
		System.out.println("put update");
		System.out.println(request.getMethod());
		
		Listlist=departmentDao.getAllDepartment();
		
		for(Department department:list) {
			if(department.getId()==employ.getDepartment().getId())
			{
				employ.getDepartment().setDepartmentName(department.getDepartmentName());
				break;
			}
		}
		
		employDao.update(employ);
		try {
			response.sendRedirect(request.getContextPath()+"/info/success.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "showEmp";
	}
	
	

}

你可能感兴趣的:(JavaEE)