JavaWeb框架梳理(七)——配置SSM框架


来源于how2j
github项目入口

搭建SSM项目

POJO

package com.how2java.pojo;
 
public class Category {
    private int id;
    private String name;
    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;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
     
}

CategoryMapper

package com.how2java.mapper;
  
import java.util.List;
 
import com.how2java.pojo.Category;
  
public interface CategoryMapper {
  
    public int add(Category category); 
        
    public void delete(int id); 
        
    public Category get(int id); 
      
    public int update(Category category);  
        
    public List<Category> list();
     
    public int count(); 
     
}

配置Category.xml

  • Category.xml需要和CategoryMapper放在同一个包下面,并且namespace必须写CategoryMapper的完整类名
  • 代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
    <mapper namespace="com.how2java.mapper.CategoryMapper">
        <insert id="add" parameterType="Category" >
            insert into category_ ( name ) values (#{name})   
        </insert>
         
        <delete id="delete" parameterType="Category" >
            delete from category_ where id= #{id}  
        </delete>
         
        <select id="get" parameterType="_int" resultType="Category">
            select * from   category_  where id= #{id}   
        </select>
 
        <update id="update" parameterType="Category" >
            update category_ set name=#{name} where id=#{id}   
        </update>
        <select id="list" resultType="Category">
            select * from   category_     
        </select>    
    </mapper>

CategoryService

package com.how2java.service;
 
import java.util.List;
 
import com.how2java.pojo.Category;
 
public interface CategoryService {
 
    List<Category> list();
 
}

CategoryServiceImpl

  • CategoryServiceImpl被注解@Service标示为一个Service
    并且装配了categoryMapper
  • 代码:
package com.how2java.service.impl;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.how2java.mapper.CategoryMapper;
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
 
@Service
public class CategoryServiceImpl  implements CategoryService{
    @Autowired
    CategoryMapper categoryMapper;
     
    public List<Category> list(){
        return categoryMapper.list();
    }
 
}

CategoryController

  • CategoryController被@Controller标示为了控制器
    自动装配了categoryService
  • 通过@RequestMapping映射访问路径/listCategory路径到方法listCategory()。
  • 在listCategory()方法中,通过categoryService获取后,然后存放在"cs"这个key上。
  • 代码:
package com.how2java.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
 
// 告诉spring mvc这是一个控制器类
@Controller
@RequestMapping("")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
 
    @RequestMapping("listCategory")
    public ModelAndView listCategory(){
        ModelAndView mav = new ModelAndView();
        List<Category> cs= categoryService.list();
         
        // 放入转发参数
        mav.addObject("cs", cs);
        // 放入jsp路径
        mav.setViewName("listCategory");
        return mav;
    }
 
}

web.xml

在WEB-INF目录下新增加web.xml,这个web.xml有两个作用:

  • 通过ContextLoaderListener在web app启动的时候,获取contextConfigLocation配置文件的文件名applicationContext.xml,并进行Spring相关初始化工作

  • 有任何访问,都被DispatcherServlet所拦截,这就是Spring MVC那套工作机制了。

  • 代码:

<?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"
         xmlns:web="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" version="2.5">
     
    <!-- spring的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     
    <!-- spring mvc核心:分发servlet -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- spring mvc的配置文件 -->
        <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>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
     
</web-app>

applicationContext.xml

在src目录下新建applicationContext.xml文件,这是Spring的配置文件,其作用

  1. 通过注解,将Service的生命周期纳入Spring的管理
<context:annotation-config />
<context:component-scan base-package="com.how2java.service" />
  1. 配置数据源<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  2. 扫描存放SQL语句的Category.xml<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
  3. 扫描Mapper,并将其生命周期纳入Spring的管理<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  • 代码:
<?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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     
   <context:annotation-config />
    <context:component-scan base-package="com.how2java.service" />
 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
      <property name="driverClassName"> 
          <value>com.mysql.jdbc.Driver</value> 
      </property> 
      <property name="url"> 
          <value>jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8</value> 
     
      </property> 
      <property name="username"> 
          <value>root</value> 
      </property> 
      <property name="password"> 
          <value>admin</value> 
      </property>    
    </bean>
     
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="typeAliasesPackage" value="com.how2java.pojo" />
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/how2java/mapper/*.xml"/>
    </bean>
 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.how2java.mapper"/>
    </bean>
     
</beans>

springMVC.xml

在src目录下新建springMVC.xml

  1. 扫描Controller,并将其生命周期纳入Spring管理
 <context:annotation-config/>
   <context:component-scan base-package="com.how2java.controller">
         <context:include-filter type="annotation" 
         expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>

  1. 注解驱动,以使得访问路径与方法的匹配可以通过注解配置
    <mvc:annotation-driven />
  2. 静态页面,如html,css,js,images可以访问<mvc:default-servlet-handler />
  3. 视图定位到/WEB/INF/jsp 这个目录下
<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
  • 代码:
<?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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/beans http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:annotation-config/>
 
    <context:component-scan base-package="com.how2java.controller">
          <context:include-filter type="annotation"
          expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
 
    <mvc:annotation-driven />
     
    <mvc:default-servlet-handler />
 
    <!-- 视图定位 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

listCategory.jsp

  • 在WEB-INF下创建jsp目录,并创建文件listCategory.jsp。
    在这个jsp文件中,通过forEach标签,遍历CategoryController传递过来的集合数据。
  • 代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${cs}" var="c" varStatus="st">
        <tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
               
        </tr>
    </c:forEach>
</table>

出现Could not resolve type alias ‘categoryMap’. Cause: java.lang.ClassNotFoundException:

  • 开始以为是sqlSession下面配置的 路径有问题,后来发现不是
  • 去tomcat的临时路径看classes下面并没有编译的.class文件,然后看workspace中项目的build下面也没有 .class,所以应该是eclipse出bug了;
  • 清空后, 重启eclipse即正常

效果:

在这里插入图片描述

流程梳理

在这里插入图片描述

  1. 首先浏览器上访问路径 /listCategory
  2. tomcat根据web.xml上的配置信息,拦截到了/listCategory,并将其交由DispatcherServlet处理。
  3. DispatcherServlet 根据springMVC的配置,通过@RequestMapping将这次请求交由CategoryController类进行处理,所以需要进行这个类的实例化
  4. 在实例化CategoryController的时候,注入CategoryServiceImpl。 (自动装配实现了CategoryService接口的的实例,只有CategoryServiceImpl实现了CategoryService接口,所以就会注入CategoryServiceImpl)
  5. 在实例化CategoryServiceImpl的时候,又注入CategoryMapper
  6. 根据ApplicationContext.xml中的配置信息,将CategoryMapper和Category.xml关联起来了。
  7. 这样拿到了实例化好了的CategoryController,并调用 list 方法
  8. 在list方法中,访问CategoryService,并获取数据,并把数据放在"cs"上,接着服务端跳转到listCategory.jsp去
  9. 最后在listCategory.jsp 中显示数据

配置SSM的CRUD

添加editCategory.jsp

  • 代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
 <div style="width:500px;margin:0px auto;text-align:center">
	
	
	<div style="text-align:center;margin-top:40px">
		
		<form method="post" action="updateCategory">
			分类名称: <input name="name" value="${c.name}" type="text"> <br><br>
			<input type="hidden" value="${c.id}" name="id">
			<input type="submit" value="增加分类">
		</form>

	</div>	
 </div>
  • 其中action=updateCategory

修改CategoryController

  • 代码:
package com.how2java.controller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
import com.how2java.util.Page;

// 鍛婅瘔spring mvc杩欐槸涓�涓帶鍒跺櫒绫�
@Controller
@RequestMapping("")
public class CategoryController {
	@Autowired
	CategoryService categoryService;

	@RequestMapping("listCategory")
	public ModelAndView listCategory(Page page){
	
		ModelAndView mav = new ModelAndView();
		List<Category> cs= categoryService.list(page);
		int total = categoryService.total();
		
		page.caculateLast(total);
		
		// 鏀惧叆杞彂鍙傛暟
		mav.addObject("cs", cs);
		// 鏀惧叆jsp璺緞
		mav.setViewName("listCategory");
		return mav;
	}
	
	@RequestMapping("addCategory")
	public ModelAndView addCategory(Category category){
		categoryService.add(category);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
	    return mav;
	}	
	@RequestMapping("deleteCategory")
	public ModelAndView deleteCategory(Category category){
		categoryService.delete(category);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
		return mav;
	}	
	@RequestMapping("editCategory")
	public ModelAndView editCategory(Category category){
		Category c= categoryService.get(category.getId());
		ModelAndView mav = new ModelAndView("editCategory");
		mav.addObject("c", c);
		return mav;
	}	
	@RequestMapping("updateCategory")
	public ModelAndView updateCategory(Category category){
		categoryService.update(category);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
		return mav;
	}	

}

  • page插件
  • Service

CategoryService

  • CategoryService.java
package com.how2java.service;

import java.util.List;

import com.how2java.pojo.Category;
import com.how2java.util.Page;

public interface CategoryService {

	List<Category> list();
	int total();
	List<Category> list(Page page);
	void add(Category c);
	void update(Category c);
	void delete(Category c);
	Category get(int id);

}

  • CategoryServiceImpl.java
package com.how2java.service.impl;

import java.util.List;

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

import com.how2java.mapper.CategoryMapper;
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
import com.how2java.util.Page;

@Service
public class CategoryServiceImpl  implements CategoryService{
	@Autowired
	CategoryMapper categoryMapper;
	
	
	public List<Category> list(){
		return categoryMapper.list();
	}


	@Override
	public List<Category> list(Page page) {
		// TODO Auto-generated method stub
		return categoryMapper.list(page);
	}


	@Override
	public int total() {
		return categoryMapper.total();
	}


	@Override
	public void add(Category c) {
		categoryMapper.add(c);
		
	}


	@Override
	public void update(Category c) {
		categoryMapper.update(c);
	}


	@Override
	public void delete(Category c) {
		categoryMapper.delete(c.getId());
	}


	@Override
	public Category get(int id) {
		// TODO Auto-generated method stub
		return categoryMapper.get(id);
	};

}

配置Page分页

  • 导入包在这里插入图片描述
  • page.java
package com.how2java.util;

public class Page {

	int start=0;
	int count = 5;
	int last = 0;
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getLast() {
		return last;
	}
	public void setLast(int last) {
		this.last = last;
	}
	
	public void caculateLast(int total) {
	    // 假设总数是50,是能够被5整除的,那么最后一页的开始就是45
	    if (0 == total % count)
	        last = total - count;
	    // 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
	    else
	        last = total - total % count;		
	}

	
	
	
}

在这里插入代码片

配置CategoryMapper

  • CategoryMapper.java
package com.how2java.mapper;
 
import java.util.List;

import com.how2java.pojo.Category;
import com.how2java.util.Page;;
 
public interface CategoryMapper {
 
      
    public int add(Category category);  
       
      
    public void delete(int id);  
       
      
    public Category get(int id);  
     
      
    public int update(Category category);   
       
      
    public List<Category> list();
    
    public List<Category> list(Page page);
    
      
    public int total();  
    
    
    
}
  • Category.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

	<mapper namespace="com.how2java.mapper.CategoryMapper">
	    <insert id="add" parameterType="Category" >
	        insert into category_ ( name ) values (#{name})    
	    </insert>
	    
	    <delete id="delete" parameterType="Category" >
	        delete from category_ where id= #{id}   
	    </delete>
	    
	    <select id="get" parameterType="_int" resultType="Category">
	        select * from   category_  where id= #{id}    
	    </select>

	    <update id="update" parameterType="Category" >
	        update category_ set name=#{name} where id=#{id}    
	    </update>
	    <select id="list" resultType="Category">
	        select * from   category_ order by id desc     
	        <if test="start!=null and count!=null">
                    limit #{start},#{count}
            </if>
            
	    </select>
	    <select id="total" resultType="int">
	        select count(*) from   category_      
	    </select>	    	    
	</mapper>

listCategory

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
 <div style="width:500px;margin:0px auto;text-align:center">
	<table align='center' border='1' cellspacing='0'>
	    <tr>
	        <td>id</td>
	        <td>name</td>
	        <td>编辑</td>
	        <td>删除</td>
	    </tr>
	    <c:forEach items="${cs}" var="c" varStatus="st">
	        <tr>
	            <td>${c.id}</td>
	            <td>${c.name}</td>
	            <td><a href="editCategory?id=${c.id}">编辑</a></td>
	            <td><a href="deleteCategory?id=${c.id}">删除</a></td>
	        </tr>
	    </c:forEach>
	</table>
	<div style="text-align:center">
		<a href="?start=0">首  页</a>
		<a href="?start=${page.start-page.count}">上一页</a>
		<a href="?start=${page.start+page.count}">下一页</a>
		<a href="?start=${page.last}">末  页</a>
	</div>
	
	
	<div style="text-align:center;margin-top:40px">
		
		<form method="post" action="addCategory">
			分类名称: <input name="name" value="" type="text"> <br><br>
			<input type="submit" value="增加分类">
		</form>

	</div>	
 </div>

效果

在这里插入图片描述

配置Restful风格的ssm框架

什么是restful

  • 大家在做Web开发的过程中,method常用的值是get和post. 可事实上,method值还可以是put和delete等等其他值。
  • 既然method值如此丰富,那么就可以考虑使用同一个url,但是约定不同的method来实施不同的业务,这就是Restful的基本考虑。
  • CRUD是最常见的操作,在使用Restful 风格之前,通常的增加做法是这样的:/addCategory?name=xxx
  • 可是使用了Restful风格之后,增加就变成了:/categories
  • CRUD如下表所示,URL就都使用一样的 “/categories”,区别只是在于method不同,服务器根据method的不同来判断浏览器期望做的业务行为
  • 在这里插入图片描述

配置web.xml

  • SpringMVC 只能处理post和get,为了还原对put和delete的处理,web.xml里面要加如下过滤器
<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>
  • 代码:
<?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"
         xmlns:web="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" version="2.5">
     
    <!-- spring的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     
    <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>
         
    <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> 
        <url-pattern>/*</url-pattern> 
    </filter-mapping>    
         
    <!-- spring mvc核心:分发servlet -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- spring mvc的配置文件 -->
        <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>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
     
</web-app>

修改listCategory.jsp

listCategory.jsp 做了如下修改

  1. 增加
    action修改为"categories"

  2. 删除
    2.1 url修改为categories/id
    2.2 点击超链后,会使用form提交,并且提交_method的值为delete, 这样在 springmvc得到后,就会以 method=delete 处理了。

  3. 获取
    3.1 url修改为了/categories/id

  4. 在最开始增加了jquery.min.js的引入

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
 <script type="text/javascript" src="js/jquery.min.js"></script>
  
    <script type="text/javascript">
       /*将post method 改变为delete*/
      $(function(){                    
           $(".delete").click(function(){
               var href=$(this).attr("href");
               $("#formdelete").attr("action",href).submit();
               return false;
           })
       })
   </script>
    
 <div style="width:500px;margin:0px auto;text-align:center">
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>编辑</td>
            <td>删除</td>
        </tr>
        <c:forEach items="${cs}" var="c" varStatus="st">
            <tr>
                <td>${c.id}</td>
                <td>${c.name}</td>
                <td><a href="categories/${c.id}">编辑</a></td>
                <td><a class="delete" href="categories/${c.id}">删除</a></td>
            </tr>
        </c:forEach>
    </table>
    <div style="text-align:center">
        <a href="?start=0">首  页</a>
        <a href="?start=${page.start-page.count}">上一页</a>
        <a href="?start=${page.start+page.count}">下一页</a>
        <a href="?start=${page.last}">末  页</a>
    </div>
     
    <div style="text-align:center;margin-top:40px">
        <form method="POST" action="categories">
                分类名称: <input name="name" value="" type="text"> <br><br>
                <input type="submit" value="增加分类">
        </form>
    </div>   
 </div>
 
    <form id="formdelete" action="" method="POST" >
       <input type="hidden" name="_method" value="DELETE">
   </form>

editCategory.jsp

  • action修改为了 categories/id
  • 注意:form 下增加 filed, 虽然这个form的method是post, 但是springmvc看到这个_method的值是put后,会把其修改为put.<input type="hidden" name="_method" value="PUT">
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
 <div style="width:500px;margin:0px auto;text-align:center">
    <div style="text-align:center;margin-top:40px">
        <form method="post" action="../categories/${c.id}">
            <input type="hidden" name="_method" value="PUT">
            分类名称: <input name="name" value="${c.name}" type="text"> <br><br>
            <input type="submit" value="修改分类">
        </form>
 
    </div>   
 </div>

Controller

CRUD的RequestMapping都修改为了/categories,只是method各不相同。
其他的。。。没变化

package com.how2java.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
import com.how2java.util.Page;
 
// 告诉spring mvc这是一个控制器类
@Controller
@RequestMapping("")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
 
    @RequestMapping(value="/categories",method=RequestMethod.GET)
    public ModelAndView listCategory(Page page){
     
        ModelAndView mav = new ModelAndView();
        List<Category> cs= categoryService.list(page);
        int total = categoryService.total();
         
        page.caculateLast(total);
         
        // 放入转发参数
        mav.addObject("cs", cs);
        // 放入jsp路径
        mav.setViewName("listCategory");
        return mav;
    }
     
    @RequestMapping(value="/categories",method=RequestMethod.POST)
    public ModelAndView addCategory(Category category){
        System.out.println("category.getName():"+category.getName());
        categoryService.add(category);
        ModelAndView mav = new ModelAndView("redirect:/categories");
        return mav;
    }  
     
    @RequestMapping(value="/categories/{id}",method=RequestMethod.DELETE)
    public ModelAndView deleteCategory(Category category){
        categoryService.delete(category);
        ModelAndView mav = new ModelAndView("redirect:/categories");
        return mav;
    }  
    @RequestMapping(value="/categories/{id}",method=RequestMethod.GET)
    public ModelAndView editCategory(Category category){
        Category c= categoryService.get(category.getId());
        ModelAndView mav = new ModelAndView("editCategory");
        mav.addObject("c", c);
        return mav;
    }  
    @RequestMapping(value="/categories/{id}",method=RequestMethod.PUT)
    public ModelAndView updateCategory(Category category){
        categoryService.update(category);
        ModelAndView mav = new ModelAndView("redirect:/categories");
        return mav;
    }  
 
}

效果

在这里插入图片描述
github项目入口

发布了117 篇原创文章 · 获赞 59 · 访问量 9万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览