SpringMVC笔记七之Result风格的增删改查

在做项目的时候,增删改查是最基本的操作,但是平时我们都是为他们创建四个方法,然后在struts中分别配置add、delete、update、find四个不同的路由,聪明点的直接用<action name="user_*" method="{1}>进行匹配,但在springMVC中有一个更简洁的方法,只需要一条路由,他就会自动执行你的增删改查。

首先我们要了解,浏览器支持get,post,delete,put等请求方式,get代表查,post代表增,delete代表删,put代表改。但是普通浏览器中只支持get和post两种方式,在springMVC中我们需要用过滤器来拦截请求,之后根据请求方式找到对应的方法并执行

这个过滤器就是HiddenHttpMethodFilter,他位于spring-web包下,当使用delete和put请求时,只需在页面表单中增加一个隐藏字段即可,注意:这个字段的name值必须为"_method"

<!-- 隐藏表单域,name值为_method,value的值就是请求方式 -->
     <input type="hidden" name="_method" value="DELETE">
     <input type="hidden" name="_method" value="PUT">

接下来我们看一个例子:

1、在web.xml中添加HiddenHttpMethodFilter过滤器,用来拦截请求

<?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>SpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
     <servlet-name>springmvc</servlet-name>
     <!-- 前端控制器 -->
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
         <!-- contextConfigLocation是参数名称,该参数的值包含的是springmvc的配置文件路径 -->
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/springmvc-config.xml</param-value>
     </init-param>
     <!-- 在web应用程序启动时立即加载Servlet -->
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置监听器 -->
  <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 指定spring的核心文件,必须使用context-param,ContextLoaderListener才能找到 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-config.xml</param-value>
  </context-param>
  
  <!-- 过滤器、拦截一切请求,目的是给普通浏览器增加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>
</web-app>

2、编写spring配置文件,其于web.xml同级,位于WEB-INF目录下

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">
        
       <!-- spring自动扫描base-package下面的包或子包下面的java文件(用了注解的java类必须被扫描才有效) -->
     <context:component-scan base-package="kshon.controller,kshon.pojo" />
       <!-- 设置配置方案 -->
     <mvc:annotation-driven />
       <!-- 使用默认的servlet响应静态文件 -->
     <mvc:default-servlet-handler/>
       <!-- 配置annotation类型的处理映射器 -->
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
       <!-- 配置annotation类型的处理器适配器 -->
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
       <!-- 视图解析器 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix">
             <value>/WEB-INF/content/</value>
         </property>
          <property name="suffix">
             <value>.jsp</value>
         </property>
     </bean>
     
     <!-- 国际化 -->
     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
       <property name="basenames" value="message"></property>
     </bean>
     <!-- 国际化操作拦截器如果采用基于(session/cookie)则必须配置 -->
     <mvc:interceptors>
       <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
     </mvc:interceptors>
     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
     
     
</beans>

3、写一个pojo类,用于接收数据,src/pojo/Book.java类如下

package pojo;

public class Book {

	private int id;
	private String name;
	private String author;
	
	public Book(){}
	public Book(int id,String name,String author){
		this.id = id;
		this.name = name;
		this.author = author;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
}

4、编写控制器src/controller/BookController.java,在每个方法前要通过@RequestMapping注解指定响应的请求方式

package kshon.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import kshon.pojo.Book;

@Controller
public class BookController {

	@RequestMapping(value="book",method=RequestMethod.POST)
	public void add(Book book){
		System.out.println("增加book。。。。。");
		System.out.println(book.getId());
		System.out.println(book.getName());
	}
	@RequestMapping(value="book",method=RequestMethod.DELETE)
	public void delete(Book book){
		System.out.println("删除book。。。。。");
		System.out.println(book.getId());
		System.out.println(book.getName());
	}
	@RequestMapping(value="book",method=RequestMethod.PUT)
	public void update(Book book){
		System.out.println("修改book。。。。。");
		System.out.println(book.getId());
		System.out.println(book.getName());
	}
	@RequestMapping(value="book",method=RequestMethod.GET)
	public void find(Book book){
		System.out.println("查找book。。。。。");
		System.out.println(book.getId());
		System.out.println(book.getName());
	}
}

5、编写表单页面WebContent/book.jsp,表单中的action统一使用book请求就行,但需要注意delete和put需要添加隐藏域

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>json数据</title>
</head>
<body>
<form action="book" method="get">
	id:<input type="text" name="id"/><br>
	书名:<input type="text" name="name"/><br>
	作者:<input type="text" name="author"/><br>
	<input type="submit" value="查"/>
</form><br>
<form action="book" method="post">
	id:<input type="text" name="id"/><br>
	书名:<input type="text" name="name"/><br>
	作者:<input type="text" name="author"/><br>
	<input type="submit" value="增"/>
</form><br>
<form action="book" method="post">
     <!-- 隐藏表单域,name值为_method,value的值就是请求方式 -->
     <input type="hidden" name="_method" value="DELETE">
	id:<input type="text" name="id"/><br>
	书名:<input type="text" name="name"/><br>
	作者:<input type="text" name="author"/><br>
	<input type="submit" value="删"/>
</form><br>
<form action="book" method="post">
     <!-- 隐藏表单域,name值为_method,value的值就是请求方式 -->
     <input type="hidden" name="_method" value="PUT">
	id:<input type="text" name="id"/><br>
	书名:<input type="text" name="name"/><br>
	作者:<input type="text" name="author"/><br>
	<input type="submit" value="改"/>
</form><br>
</body>
</html>	

启动tomcat,输入http://localhost:8080/SpringMVC/book.jsp

可以在eclipse控制台中看到相应的输出

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值