SpringMVC 控制器之实现基础CRUD操作

这一篇讲以下三个知识点:

1.@RequestMapping——请求映射注解

2.@RequestParam——请求参数

3.ModelAndView——返回模型和视图

4.SpringMVC——属性自动封装

5.SpringMVC——POST请求乱码解决

6.Controller——内部转发与重定向

示例:(学生信息的查询、添加、修改,删除)——为了方便就不链接数据库直接在类中模拟了一些数据

1.配置springMVC的web.xml

<?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>SpringMVC2</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 同struts一样,也是需要拦截请求 -->
  <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern><!-- 拦截所有以.do结尾的请求 -->
    </servlet-mapping>
    
    <!-- spring的编码过滤器 -->
    <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><!-- 改成utf-8 -->
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>*.do</url-pattern><!-- 对所有的.do请求进行过滤 -->
    </filter-mapping>
</web-app>

2.配置spring-mvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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.xsd">

    <!-- 使用注解的包,包括子集 -->
    <context:component-scan base-package="com.maya"/>

    <!-- 视图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" /><!-- 返回视图到这个目录下 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

3.建立model层,实体类student

package com.maya.model;

public class Student {
    private int id;
    private String name;
    private int age;
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Student(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //空参构造函数一定要加上,不然再SpringMVC进行自动封装时会报init<>异常
    public Student() {
        super();
    }
}

4.建立controller层,StudentController类

package com.maya.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;//是web.servlet.ModelAndView!!!不要选错

import com.maya.model.Student;

@Controller//声明这是控制层
@RequestMapping("/student")//为了区分模块,在请求时通常会在模块前加一个前缀
public class StrudentController {
    
    private static List<Student> studentList=new ArrayList<Student>();
    static{//模拟数据
        studentList.add(new Student(1, "张三", 11));
        studentList.add(new Student(2, "李四", 12));
        studentList.add(new Student(3, "王五", 13));
    }
    
    @RequestMapping("/list")//定义请求的名字
    public ModelAndView list(){//ModelAndView返回模型和视图
        ModelAndView mav=new ModelAndView();
        mav.addObject("studentList", studentList);
        mav.setViewName("student/list");//设置视图的名,student文件名下的list.jsp
        return mav;
    }
    
    @RequestMapping("/preSave")                //required默认是true! 与value同时出现            
    public ModelAndView preSave(@RequestParam(value="id",required=false) String id){
                                //接收前台参数id,因为添加修改都用这一个请求,那么required应设为false,后面定义接收参数的类型
        ModelAndView mav=new ModelAndView();
        if(id==null){//如果没有接收到参数,说明是添加
            mav.setViewName("student/add");//设置视图的名,student文件名下的add.jsp
        }else{//否则就是修改了
            mav.addObject("student", studentList.get(Integer.parseInt(id)-1));
            mav.setViewName("student/update");//设置视图的名,student文件名下的update.jsp
        }        
        return mav;
    }
    
    @RequestMapping("/saveOrUdate")
    public String save(Student student){//进行添加或者修改
        if(student.getId()!=0){//根据id判断
            Student s=studentList.get(student.getId()-1);
            s.setName(student.getName());
            s.setAge(student.getAge());
        }else{            
            studentList.add(student);
        }
        return "redirect:/student/list.do";//重定向
    }
    
    @RequestMapping("/delete")
    public String delete(@RequestParam("id") int id){//这样就可以将String id强制转换成int id了
        studentList.remove(id-1);
        //return "redirect:/student/list.do";//当然除了重定向之外,还有转发(如下)
        return "forward:/student/list.do";
    }
}

5.建立view视图层,因为设定了在jsp文件夹下的student文件下!所以要相应的建立正确的路径

<%@ 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>list.jsp</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/student/preSave.do">添加</a>
<table>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>操作</th>
    </tr>
<c:forEach var="list" items="${studentList }">
    <tr>
        <td>${list.id }</td>
        <td>${list.name }</td>
        <td>${list.age }</td>
        <td><a href="${pageContext.request.contextPath }/student/preSave.do?id=${list.id }">修改</a></td>
        <td><a href="delete.do?id=${list.id }">删除</a></td>
    </tr>    
</c:forEach>
</table>
</body>
</html>
<body>
添加
<form action="${pageContext.request.contextPath}/student/saveOrUdate.do" method="post">
    姓名:<input type="text" name="name" /><!-- 进行自动封装,那么name属性的值一定要对应实体类中的属性 -->
    年龄:<input type="text" name="age" />
    <input type="submit" value="提交" />
</form>
</body>
<body>
修改
<form action="${pageContext.request.contextPath }/student/saveOrUdate.do" method="post">
    姓名:<input type="text" name="name" value="${student.name }" />
    年龄:<input type="text" name="age" value="${student.age }" />
    <input type="hidden" name="id" value="${student.id }" />
    <input type="submit" value="提交" />
</form>
</body>

转载于:https://www.cnblogs.com/AnswerTheQuestion/p/6681810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值