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

先说坑:

	<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>	
		<dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
	</filter-mapping>

本以为添加了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的

<Connector connectionTimeout="20000" port="9081" protocol="HTTP/1.1" redirectPort="8443"  URIEncoding="UTF-8"/>

设置为utf8还是无效。

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

request.setCharacterEncoding("UTF-8");

解决问题

回到主题

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

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

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

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">

	<!-- 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>encodingfilter</filter-name>
		<filter-class>top.demo.crud.filter.EncodingFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>encodingfilter</filter-name>
		<url-pattern>/*</url-pattern>
		 <!-- 指定该过滤器对哪些方式生效  对转发的时候生效还是 请求的时候生效,一共四种方式-->
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
	</filter-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>	
		<dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
	</filter-mapping>


</web-app>

springmvc配置

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">


	<context:component-scan base-package="top.demo.crud"></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>	




	<!-- 配置默认的servlet处理器 ,用于在没有对应映射的控制器方法时 找到静态的资源 -->
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven></mvc:annotation-driven>

</beans>

员工和部门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<Department> 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<Department> 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<Employ> 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<Employ> 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<String, Object> map) {
		
		ModelAndView modelAndView=new ModelAndView("showEmp");
		modelAndView.addObject("emps", employDao.getAllEmp());
		
		return modelAndView;
	}
	
	@RequestMapping(value="addEmp",method=RequestMethod.GET)
	public String addEmp(Map<String, Object>map ) {
		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,Map<String, Object>map) {
		
		System.out.println("post");	
		
		List<Department>list=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,Map<String, Object>map) {
	
		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());
		
		List<Department>list=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";
	}
	
	

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值