欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSM笔记-SpringMVC的CRUD和静态资源

程序员文章站 2022-06-04 19:41:43
...

1、处理静态资源
①通过DispatcherServlet配置请求映射后,获取静态资源的请求(通过url获取静态资源时),也会被当成普通请求处理,如果想配置请求映射后还能通过url的形式获取静态资源的话,则需要到springmvc配置文件中配置
②解决方法:在springmvc配置文件中配置mvc:default-servlet-handler标签

2、CRUD
步骤:
①创建Bean(数据模型+getset方法)
②创建对应的Dao(根据数据模型写对应的增删查改方法,如果对应的Bean中还有其他Bean的类对象,则需要使用@Autowired修饰这个类对象)
③创建Handler类,编写一些调用增删查改的action逻辑
④编写调用action的页面和显示结果的页面

注意:
①Dao中, 如果对应的Bean中还有其他Bean的类对象,则需要使用@Autowired修饰这个类对象
②如果要处理静态资源, 则需要到springmvc配置文件中配置mvc:default-servlet-handler标签
③提供修改功能的页面里面的form标签的action需要设为绝对路径,因为进入该页面的时候,路径会变成指向这个页面的对应action的路径,如果不设置绝对路径,路径就会变成action路径之下的子路径,这样就会无法重定向回显示页面,要这样写才行:
action="${pageContext.request.contextPath}/actionName
④Handler类中, 修改操作时,不显示及不提交某一个指定参数,所以正常情况下,该参数的值为空,为了让这个不允许修改或不出现在页面的参数不被设为空,这里需要通过@ModelAttribute,每次执行操作前都通过dao获取一次指定id的所有参数值
⑤上一点中被@ModelAttribute修饰的方法中需要使用Map来把查询到的数据存起来, 这个时候Map的key需要是被查询的Bean的首字母小写的类名,不然会无效,不允许修改或不出现到页面的参数,在更新后会被改为空

3、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_3_1.xsd" version="3.1">
  <display-name>SpringMVC_7_CRUD</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>
  <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>

4、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: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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

    <!-- 配置自动扫描包 -->
    <context:component-scan base-package="com.test.springmvc"></context:component-scan>

    <!-- 配置视图解析器,把handler返回值解析为实际视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 处理静态资源 -->
    <!-- 通过DispatcherServlet配置请求映射后,获取静态资源的请求(通过url获取静态资源时),也会被当成普通请求处理 -->
    <!-- 解决方法:配置mvc:default-servlet-handler标签 -->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>

5、Info.java

package com.test.springmvc.bean;

import org.springframework.stereotype.Repository;

@Repository
public class Info {

    Integer infoId;
    String infoName;
    String infoDesc;
    Detail detail;

    public Info() {}

    public Info(Integer infoId, String infoName, String infoDesc, Detail detail) {
        super();
        this.infoId = infoId;
        this.infoName = infoName;
        this.infoDesc = infoDesc;
        this.detail = detail;
    }
    public Integer getInfoId() {
        return infoId;
    }
    public void setInfoId(Integer infoId) {
        this.infoId = infoId;
    }
    public String getInfoName() {
        return infoName;
    }
    public void setInfoName(String infoName) {
        this.infoName = infoName;
    }
    public String getInfoDesc() {
        return infoDesc;
    }
    public void setInfoDesc(String infoDesc) {
        this.infoDesc = infoDesc;
    }
    public Detail getDetail() {
        return detail;
    }
    public void setDetail(Detail detail) {
        this.detail = detail;
    }
}

6、Detail.java

package com.test.springmvc.bean;

public class Detail {

    Integer detailId;
    String detailName;

    public Detail() {}

    public Detail(Integer detailId, String detailName) {
        super();
        this.detailId = detailId;
        this.detailName = detailName;
    }

    public Integer getDetailId() {
        return detailId;
    }

    public void setDetailId(Integer detailId) {
        this.detailId = detailId;
    }

    public String getDetailName() {
        return detailName;
    }

    public void setDetailName(String detailName) {
        this.detailName = detailName;
    }

}

7、InfoDao.java

package com.test.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.test.springmvc.bean.Detail;
import com.test.springmvc.bean.Info;

@Repository
public class InfoDao {

    private static Map<Integer, Info>map = null;

    @Autowired
    private DetailDao detailDao;

    static{
        map=new HashMap<Integer,Info>();
        map.put(1, new Info(1, "infoA", "DescA", new Detail(1, "detailA")));
        map.put(2, new Info(2, "infoB", "DescB", new Detail(2, "detailB")));
        map.put(3, new Info(3, "infoC", "DescC", new Detail(3, "detailC")));
        map.put(4, new Info(4, "infoD", "DescD", new Detail(3, "detailD")));
    }

    public Collection<Info> getAll(){
        return map.values();
    }
    public Info getById(Integer id){
        return map.get(id);
    }
    public boolean add(Info info){
        map.put(map.size()+1, info);
        return true;
    }
    public boolean delete(Integer id){
        map.remove(id);
        return true;
    }
    public boolean update(Info info){
        if(info.getInfoId()!=null){
            info.setDetail(detailDao.getById(info.getDetail().getDetailId()));
            map.put(info.getInfoId(), info);
            return true;
        }else{
            return false;
        }
    }
}

8、DetailDao.java

package com.test.springmvc.dao;

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

import org.springframework.stereotype.Repository;

import com.test.springmvc.bean.Detail;

@Repository
public class DetailDao {

    private static Map<Integer, Detail>map = null;

    static{
        map=new HashMap<Integer,Detail>();
        map.put(1, new Detail(1, "detailA"));
        map.put(2, new Detail(2, "detailB"));
        map.put(3, new Detail(3, "detailC"));
        map.put(4, new Detail(3, "detailD"));
    }

    public Collection<Detail>getAll(){
        return map.values();
    }
    public Detail getById(Integer id){
        return map.get(id);
    }
    public boolean add(Detail detail){
        map.put(map.size()+1, detail);
        return true;
    }
    public boolean delete(Integer id){
        map.remove(id);
        return true;
    }
    public boolean update(Integer id,Detail detail){
        if(map.get(id)!=null){
            map.put(id, detail);
            return true;
        }else{
            return false;
        }
    }
}

9、Handler.java

package com.test.springmvc.handlers;

import java.util.Map;

import org.jcp.xml.dsig.internal.MacOutputStream;
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.test.springmvc.bean.Detail;
import com.test.springmvc.bean.Info;
import com.test.springmvc.dao.DetailDao;
import com.test.springmvc.dao.InfoDao;

@Controller
public class Handler {

    @Autowired
    public InfoDao infoDao;

    @Autowired
    public DetailDao detailDao;

    //修改操作时,不显示及不提交某一个指定参数,所以正常情况下,该参数的值为空,为了让这个不允许修改或不出现在页面的参数不被设为空,这里需要通过@ModelAttribute,每次执行操作前都通过dao获取一次指定id的所有参数值
    //注意:这里map的key为修改操作方法中参数Info类的首字母小写,不然会无效,不允许修改或不出现到页面的参数,在更新后会被改为空
    @ModelAttribute
    public void getInfo(@RequestParam(value="infoId",required=false)Integer infoId,Map<String, Object>map ){
        if(infoId!=null){
            map.put("info", infoDao.getById(infoId));
        }
    }

    @RequestMapping("/list")
    public String show(Map<String, Object>map){
        System.out.println("list");
        map.put("infos", infoDao.getAll());
        System.out.println(map);
        return "list";
    }

    @RequestMapping(value="/emp",method=RequestMethod.GET)
    public String addPage(Map<String,Object>map){
        map.put("details", detailDao.getAll());
        map.put("infos", new Info());
        return "edit";
    }

    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String save(Info info){
        info.getDetail().setDetailName(detailDao.getById(info.getDetail().getDetailId()).getDetailName());
        info.setDetail(info.getDetail());
        infoDao.add(info);
        return "redirect:/list";
    }

    @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable Integer id){
        System.out.println("delete id:"+id);
        infoDao.delete(id);
        return "redirect:/list";
    }

    @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
    public String updatePage(@PathVariable Integer id,Map<String,Object>map){
        map.put("details", detailDao.getAll());
        map.put("infos", infoDao.getById(id));
        return "edit";
    }

    @RequestMapping(value="/emp",method=RequestMethod.PUT)
    public String update(Info info){
        System.out.println("update getInfoName:"+info.getInfoName());
        infoDao.update(info);
        return "redirect:/list";
    }
}

10、index.jsp

<%@ 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>Insert title here</title>
</head>
<body>
    <a href="list">list data</a>
    <br><br>
</body>
</html>

11、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">
<title>Info list</title>
</head>
<body>
    <a href="emp">Add info</a>
    <br><br>
    <a href="/SpringMVC_7_CRUD/statsFile/jstl.jar">静态资源</a>
    <br><br>

    <c:if test="${empty requestScope.infos}">
        no data
    </c:if>
    <c:if test="${!empty requestScope.infos}">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <td>infoId</td>
                <td>infoName</td>
                <td>infoDesc</td>
                <td>detailId</td>
                <td>detailName</td>
                <td>Update</td>
                <td>Delete</td>
            </tr>
            <c:forEach items="${requestScope.infos}" var="infoData">
                <tr>
                <td>${infoData.infoId}</td>
                <td>${infoData.infoName}</td>
                <td>${infoData.infoDesc}</td>
                <td>${infoData.detail.detailId}</td>
                <td>${infoData.detail.detailName}</td>
                <td><a href="emp/${infoData.infoId}">Update</a></td>
                <td>
                    <form method="post" action="emp/${infoData.infoId}">
                        <input type="hidden" name="_method" value="DELETE">
                        <input type="submit" name="submit" value="Delete">
                    </form>
                </td>
            </tr>
            </c:forEach>
        </table>
    </c:if>
</body>
</html>

12、edit.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" %>
<!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>Add Info</title>
</head>
<body>

    <!-- 这里action需要设为绝对路径,因为进入edit的时候,路径会变成/emp,如果不设置绝对路径,路径就会变成/emp之下的子路径,这样就会无法重定向回显示页面 -->
    <form:form method="POST" action="${pageContext.request.contextPath}/emp" modelAttribute="infos">
        <c:if test="${infos.infoId!=null}">
            <!-- _method不能用form:hidden标签,因为modelAttribut对应的bean没有_method属性 -->
            <input type="hidden" name="_method" value="PUT">
        </c:if>
        infoId:<form:input path="infoId"/>
        <br>
        <c:if test="${infos.infoId==null}">
        infoName:<form:input path="infoName"/>
        <br>
        </c:if>
        infoDesc:<form:input path="infoDesc"/>
        <br>
        detail:<form:select path="detail.detailId" items="${details}" itemLabel="detailName" itemValue="detailId"></form:select>
        <br>
        <input type="submit" value="submit">
    </form:form>

</body>
</html>

13、项目目录
SSM笔记-SpringMVC的CRUD和静态资源

14、demo
https://download.csdn.net/download/qq_22778717/10601060

相关标签: Spring4