【SpringMVC】SpringMVC入门笔记2(1w字+)



IDE: IntelliJ IDEA 2020.2

零 l  写在前面


1、以初学者的视角记录笔记
2、课程链接:[链接]
3、资料链接:[笔记对应课程的配套资料],提取码:invv
4、实操很重要!!!
5、本文主讲SpringMVC
6、前文链接:
[Spring入门笔记1][Spring入门笔记2][Spring入门笔记3]
[MyBatis入门笔记1][MyBatis入门笔记2]
[MVC设计模式简介]
[SpringMVC入门笔记1]




一 l  修改时带页面回显


(一)简单的页面回显实现

1、User.java(.\src\com\gyf\backoffice\model\User.java)

public class User {
    private Integer id;
    private String username;
    private int age;
    private String gender;
    private Date birthday;
    
    public User() {}
    public User(String username, int age, String gender, Date birthday) {
        this.username = username;
        this.age = age;
        this.gender = gender;
        this.birthday = birthday;
    }
    
    ...get、set、toString方法...
}

2、UserController.java(.\src\com\gyf\backoffice\web\controller\UserController.java)

@Controller
@RequestMapping("/user")
public class UserController{
    @RequestMapping("/list")
    public String list(Model model){
        // 1.模拟数据库的数据
        List<User> userList = new ArrayList<User>();
        User user1 = new User("小明",23,"男",new Date());
        User user2 = new User("小军",26,"男",new Date());
        User user3 = new User("小力",18,"男",new Date());
        user1.setId(1);
        user2.setId(2);
        user3.setId(3);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        // 2.把数据存在model
        model.addAttribute("userList",userList);
        return "user/userlist";
    }
    
    @RequestMapping("/edit")
    public String edit(int id, Model model){
        // 通过id,查询数据库,返回一个User对象,把user对象存在model
        User user = new User("小明",23,"男",new Date());  // 假设从数据库查
        user.setId(1);
        model.addAttribute("user",user);
        return "user/useredit";
    }
}

3、userlist.jsp(.\web\WEB-INF\views\user\userlist.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户列表</title>
</head>
<body>
用户列表
<table border="1">
    <tr>
        <td>名字</td>
        <td>年龄</td>
        <td>性别</td>
        <td>生日</td>
    </tr>
    <c:forEach items="${userList}" var="user">
        <tr>
            <td>${user.username}</td>
            <td>${user.age}</td>
            <td>${user.gender}</td>
            <td>${user.birthday}
                <a href="${pageContext.request.contextPath}/user/edit.do?id=${user.id}">修改</a>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

4、useredit.jsp(.\web\WEB-INF\views\user\useredit.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/update.do" method="post">
    用户名:<input type="text" name="username" value="${user.username}"><br>
    年龄:<input type="text" name="password" value="${user.age}"><br>
    性别:<input type="text" name="gender" value="${user.gender}"><br>
    生日:<input type="text" name="birthday" value="${user.birthday}"><br>
    <input type="submit">
</form>
</body>
</html>

(二)URL模版映射


在简单的页面回显之上进行修改,使其符合restfull软件架构

url模版映射可以实现restfull软件架构

1、UserController.java(.\src\com\gyf\backoffice\web\controller\UserController.java)(edit1的注解不同,传入参数需要设置@PathVariable注解)

@Controller
@RequestMapping("/user")
public class UserController{
    @RequestMapping("/list")
    public String list(Model model){
        // 1.模拟数据库的数据
        List<User> userList = new ArrayList<User>();
        User user1 = new User("小明",23,"男",new Date());
        User user2 = new User("小军",26,"男",new Date());
        User user3 = new User("小力",18,"男",new Date());
        user1.setId(1);
        user2.setId(2);
        user3.setId(3);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        // 2.把数据存在model
        model.addAttribute("userList",userList);
        return "user/userlist";
    }
    
    @RequestMapping("/edit1/{id}")
    public String edit1(@PathVariable int id,Model model){
        // 通过id,查询数据库,返回一个User对象,把user对象存在model
        User user = new User("小明",23,"男",new Date());//假设从数据查
        user.setId(1);
        model.addAttribute("user",user);
        return "user/useredit";
    }
}

2、userlist.jsp(.\web\WEB-INF\views\user\userlist.jsp)(修改按钮的访问路径不同)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户列表</title>
</head>
<body>
用户列表
<table border="1">
    <tr>
        <td>名字</td>
        <td>年龄</td>
        <td>性别</td>
        <td>生日</td>
    </tr>
    <c:forEach items="${userList}" var="user">
        <tr>
            <td>${user.username}</td>
            <td>${user.age}</td>
            <td>${user.gender}</td>
            <td>${user.birthday}
                <a href="${pageContext.request.contextPath}/user/edit1/${user.id}.do">修改</a>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

3、web.xml(.\web\WEB-INF\web.xml)(配置rest风格的访问路径,http://localhost/rest/user/listhttp://localhost/user/list.do都能访问)

<web-app>
    ...
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    ...
</web-app>





二 l  转发和重定向


转发: 只需要在 控制器方法返回值前“forward:” 就行了

重定向: 只需要把 “forward:” 改成 “redirect:” 就行了

扩展:[转发和重定向的区别]


1、相同控制器转发(访问http://localhost/user/test1.do会转发到http://localhost/user/list.do
UserController.java

@Controller
@RequestMapping("/user")
public class UserController{
    @RequestMapping("/test1")
    public String test1(){
        // 同一个控制器转发,跳到下面的/list去
        return "forward:list.do";
    }
    
    @RequestMapping("/list")
    public String list(Model model){
        // 1.模拟数据库的数据
        List<User> userList = new ArrayList<User>();
        User user1 = new User("小明",23,"男",new Date());
        User user2 = new User("小军",26,"男",new Date());
        User user3 = new User("小力",18,"男",new Date());
        user1.setId(1);
        user2.setId(2);
        user3.setId(3);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        // 2.把数据存在model
        model.addAttribute("userList",userList);
        return "user/userlist";
    }
}

2、不同控制器转发(访问http://localhost/stu/test1.do会转发到http://localhost/user/list.do
UserController.java

@Controller
@RequestMapping("/stu")
public class StudentController {
    @RequestMapping("/test1")
    public String test1() {
        return "forward:/user/list.do";
    }
}

3、不同控制器重定向(访问http://localhost/stu/test1.do会重定向到http://localhost/user/list.do
UserController.java

@Controller
@RequestMapping("/stu")
public class StudentController {
    @RequestMapping("/test1")
    public String test1() {
        return "redirect:/user/list.do";
    }
}





三 l  限定JavaBean传入、返回格式


(一)ResponseBody和RequestBody(只针对json数据)

@ResponseBody把后台pojo转换json对象,返回到页面。(在bean函数的返回值使用)
@RequestBody接受前台json数据,把json数据自动封装javaBean。(在bean函数的输入使用)
一般情况,接收的数据是直接用bean获取数据(不用@RequestBody),返回给前端用@ResponseBody。

示例1:请求和响应都是json数据

1、导入json的jar
三-1
2、添加json转换器
DispatcherServlet-servlet.xml(.\web\WEB-INF\DispatcherServlet-servlet.xml)(主要看第3步)

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!-- 注解配置控制器 -->
    <!-- 1.配置扫描包 -->
    <context:component-scan base-package="com.gyf.backoffice.web.controller"/>
    <!-- 2.配置注解处理映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <!-- 3.配置适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!-- 配置json转换器,告诉springmvc使用jackson来转换json -->
        <property name="messageConverters">
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </property>
    </bean>
    <!-- 4.配置资源视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/views/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

3、Student.java(.\src\com\gyf\backoffice\model\Student.java)

public class Student {
    private String name;
    private String sex;
    
    ...get、set、toString方法...
}

4、StudentController.java(.\src\com\gyf\backoffice\web\controller\StudentController.java)

@Controller
@RequestMapping("/stu")
public class StudentController {
    @RequestMapping("/toReg")
    public String toReg() {
        return "stu/register";
    }
    
    @RequestMapping("/save")
    // @RequestBody:把json数据转成对象
    // @ResponseBody:把对象转成json字符串返回网页
    public @ResponseBody Student save(@RequestBody Student stu) {
        System.out.println(stu);
        return stu;
    }
}

5、register.jsp(.\web\WEB-INF\views\stu\register.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!-- jquery文件位置,需要自行下载 -->
    <script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
    <script>
        function register() {
            // 表单提交
            var url = '${pageContext.request.contextPath}/stu/save.do';

            // 希望传{"name":"gyf", "sex":"male"}这种格式
            var name = $('#name').val();
            var sex = $('#sex').val();
            var jsonObj = {name:name,sex:sex}

            // 把json对象转化成字符串
            var parameters = JSON.stringify(jsonObj);
            console.log(jsonObj);
            console.log(parameters);

            // jquery提交json数据
            $.ajax({
                type:'POST',
                url:url,
                contentType:'application/json;charset=utf-8',
                data:parameters,
                success:function (respData) {
                    console.log('执行成功返回值:' + respData);
                }
            });
        }
    </script>
</head>
<body>
<%-- 默认请求头:application/x-www-form-urlencoded;默认数据格式:name=gyf&sex=male
     修改请求头:application/json                 ;修改数据格式:{"name":"gyf","sex":"male"} --%>
<form action="${pageContext.request.contextPath}/stu/save.do" method="post">
    学生姓名:<input id="name" type="text" name="name"><br>
    性别:<input id="sex" type="text" name="sex"><br>
    <input type="button" value="提交json格式数据" onclick="register();">
    <input type="submit">
</form>
</body>
</html>

(二)Springmvc多视图(更灵活)

多视图是一个方法可以返回json/xml等格式的数据。

1、导入xml格式支持的jar包spring-oxm-x.x.x.jar

2、Student.java(.\src\com\gyf\backoffice\model\Student.java)
使用@XmlRootElement配置xml的根目录

@XmlRootElement(name="student")
public class Student {
    private String name;
    private String sex;
    
    ...get、set、toString方法...
}

3、配置支持多视图
DispatcherServlet-servlet.xml(.\web\WEB-INF\DispatcherServlet-servlet.xml)(主要看第5步,前4步跟之前是一样的)

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!-- 注解配置控制器 -->
    <!-- 1.配置扫描包 -->
    <context:component-scan base-package="com.gyf.backoffice.web.controller"/>
    <!-- 2.配置注解处理映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <!-- 3.配置适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!-- 配置json转换器,告诉springmvc使用jackson来转换json -->
        <property name="messageConverters">
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </property>
    </bean>
    <!-- 4.配置资源视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/views/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 5.配置多视图,javabean可以返回json,也可以返回xml -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <!-- 配置支持媒体类型 -->
        <property name="contentNegotiationManager">
            <bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
                <property name="mediaTypes">
                    <map>
                        <entry key="json" value="application/json"></entry>
                        <entry key="xml" value="application/xml"></entry>
                    </map>
                </property>
            </bean>
        </property>
        
        <!-- 指定默认视图 -->
        <property name="defaultViews">
            <!-- 支持多个视图 -->
            <list>
                <!-- 对josn格式视图支持 -->
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
                <!-- xml格式视图支持 -->
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <constructor-arg>
                        <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                            <property name="classesToBeBound">
                                <list>
                                    <value>com.gyf.backoffice.model.Student</value>
                                </list>
                            </property>
                        </bean>
                    </constructor-arg>
                </bean>
            </list>
        </property>
    </bean>
</beans>

4、StudentController.java(.\src\com\gyf\backoffice\web\controller\StudentController.java)

@Controller
@RequestMapping("/stu")
public class StudentController {
    @RequestMapping("/get")
    public Student get() {
        Student stu = new Student();
        stu.setName("zhangsan");
        stu.setSex("male");
        return stu;
    }
}

5、测试http://localhost:8080/rest/stu/get.jsonhttp://localhost:8080/rest/stu/get.xml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值