springmvc(3)

简介: springmvc

springmvc(2)https://developer.aliyun.com/article/1530450

8.3、具体功能:访问首页

①配置view-controller

<mvc:view-controller path="/" view-name="index"/>

②创建页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" >
        <title>Title</title>
    </head>
    <body>
        <h1>首页</h1>
        <a th:href="@{/employee}">访问员工信息</a>
    </body>
</html>

8.4、具体功能:查询所有员工数据

①控制器方法

@Controller  
public class EmployeeController {  
    @Autowired  
    private EmployeeDao employeeDao;  
  
    @RequestMapping(value = "/employee", method = RequestMethod.GET)  
    public String getAllEmployee(Model model){  
        //获取所有员工信息  
        Collection<Employee> all = employeeDao.getAll();  
        //将员工信息放在请求域中共享  
        model.addAttribute("allEmployee",all);  
        return "employee_list";  
    }

②创建employee_list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Employee Info</title>
        <script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
    </head>
    <body>
        <table border="1" cellpadding="0" cellspacing="0" style="text-align:center;" id="dataTable">
            <tr>
                <th colspan="5">Employee Info</th>
            </tr>
            <tr>
                <th>id</th>
                <th>lastName</th>
                <th>email</th>
                <th>gender</th>
                <th>options(<a th:href="@{/toAdd}">add</a>)</th>
            </tr>
            <tr th:each="employee : ${allEmployee}">
                <td th:text="${employee.id}"></td>
                <td th:text="${employee.lastName}"></td>
                <td th:text="${employee.email}"></td>
                <td th:text="${employee.gender}"></td>
                <td>
                    <a class="deleteA" @click="deleteEmployee"
                       th:href="@{'/employee/'+${employee.id}}">delete</a>
                    <a th:href="@{'/employee/'+${employee.id}}">update</a>
                </td>
            </tr>
        </table>
    </body>
</html>

③处理静态资源

我们项目的web.xml是会继承Tomcat的web.xml,我们tomcat原本配置静态资源由一个专门的servlet处理,但是项目的Dispatcherservlet配置为对所有文件生效,但是它又处理不了静态资源,所以会导致css失效

<!--配置默认的servlet处理静态资源,
当前工程的web.xml配置的前端控制器pispatcherservlet的url -pattern是/
tomcat的web.xm儿配置的Defaultservlet的url-pattern也是/
此时,浏览器发送的请求会优先被DispatcherservLet进行处理,但是DispatcherservLet无法处理静态资源若配置了<mvc: default-servlet-handler />,此时浏览器发送的所有请求都会被Defaultservlet处理若配置了<mvc:default-servlet-handler />和<mvc : annotation-driven />
浏览器发送的请求会先被Dispatcherservlet处理,无法处理在交给Defaultservlet处理
-->  
  
<mvc:default-servlet-handler />  
<!--开启mvc注解驱动-->    
<mvc:annotation-driven />

必须搭配annotation-driven使用,不然全部都会用默认的servlet来处理

8.5、具体功能:删除

[!important]

原本的删除是一个链接,但是我们需要用表达传输delete请求,这时我们就得用到vue来绑定事件,把链接绑定到表单的action里面,而表单提交delete请求需要配置[[springmvc#7.3、HiddenHttpMethodFilter]]

①创建处理delete请求方式的表单

<!-- 作用:通过超链接控制表单的提交,将post请求转换为delete请求 -->
<form id="delete_form" method="post">
    <!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 -->
    <input type="hidden" name="_method" value="delete"/>
</form>
<div id="app">  
    <table border="1" cellpadding="0" cellspacing="0" style="text-align:center;" id="dataTable">  
        <tr>            <th colspan="5">Employee Info</th>  
        </tr>        <tr>            <th>id</th>  
            <th>lastName</th>  
            <th>email</th>  
            <th>gender</th>  
            <th>options(<a th:href="@{/toAdd}">add</a>)</th>  
        </tr>        <tr th:each="employee : ${allEmployee}">  
            <td th:text="${employee.id}"></td>  
            <td th:text="${employee.lastName}"></td>  
            <td th:text="${employee.email}"></td>  
            <td th:text="${employee.gender}"></td>  
            <td><a @click="deleteEmployee()" th:href="@{'/employee/'+${employee.id}}">delete</a>  
                <a th:href="@{'/employee/'+${employee.id}}">update</a>  
            </td>
            </tr>    
            </table>
             <form method="post">  
        <input type="hidden" name="_method" value="delete">  
    </form>  
</div>

引入vue.js==,默认的servert需要设置才能使用静态资源==

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>

删除超链接

<a class="deleteA" @click="deleteEmployee"th:href="@{'/employee/'+${employee.id}}">delete</a>

通过vue处理点击事件

<script type="text/javascript">
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            //event表示当前事件
            deleteEmployee:function (event) {
                //通过id获取表单标签
                var delete_form = document.getElementById("delete_form");
                //将触发事件的超链接的href属性为表单的action属性赋值
                delete_form.action = event.target.href;
                //提交表单
                delete_form.submit();
                //阻止超链接的默认跳转行为
                event.preventDefault();
            }
        }
    });
</script>

③控制器方法

请求方式为delete

@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
    employeeDao.delete(id);
    return "redirect:/employee";
}

8.6、具体功能:跳转到添加数据页面

①配置view-controller

<mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>

②创建employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Add Employee</title>
    </head>
    <body>
        <form th:action="@{/employee}" method="post">
            lastName:<input type="text" name="lastName"><br>
            email:<input type="text" name="email"><br>
            gender:<input type="radio" name="gender" value="1">male
            <input type="radio" name="gender" value="0">female<br>
            <input type="submit" value="add"><br>
        </form>
    </body>
</html>

8.7、具体功能:执行保存

①控制器方法

@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

8.8、具体功能:跳转到更新数据页面

①修改超链接

不拼接后面的就会当成路径来解析而不是一个表达式的值

<a th:href="@{'/employee/'+${employee.id}}">update</a>

②控制器方法

@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}

③创建employee_update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Update Employee</title>
    </head>
    <body>
        <form th:action="@{/employee}" method="post">
            <input type="hidden" name="_method" value="put">
            <input type="hidden" name="id" th:value="${employee.id}">
            lastName:<input type="text" name="lastName" th:value="${employee.lastName}">
            <br>
            email:<input type="text" name="email" th:value="${employee.email}"><br>
            <!--
                th:field="${employee.gender}"可用于单选框或复选框的回显
                若单选框的value和employee.gender的值一致,则添加checked="checked"属性
      -->
            gender:<input type="radio" name="gender" value="1"th:field="${employee.gender}">male
            <input type="radio" name="gender" value="0"th:field="${employee.gender}">female<br>
            <input type="submit" value="update"><br>
        </form>
    </body>
</html>

8.9、具体功能:执行更新

①控制器方法

@RequestMapping(value = "/employee", method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

9、SpringMVC处理ajax请求

回顾

<div id="app">
    <h1>index.html</h1>
    <input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br>
    <input type="button" value="使用@RequestBody注解处理json格式的请求参数" @click="testRequestBody()"><br>
    <a th:href="@{/test/ResponseBody}">测试@ResponseBody注解响应浏览器数据</a><br>
    <input type="button" value="使用@ResponseBody注解响应json格式的数据" @click="testResponseBody()"><br>
    <a th:href="@{/test/down}">下载图片</a>
    <form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
        头像:<input type="file" name="photo"><br>
        <input type="submit" value="上传">
    </form>
</div>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
    /**
     * axios({
           url:"",//请求路径
           method:"",//请求方式
           //以name=value&name=value的方式发送的请求参数
           //不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后
           //此种方式的请求参数可以通过request.getParameter()获取
           params:{},
           //以json格式发送的请求参数
           //请求参数会被保存到请求报文的请求体传输到服务器
           //此种方式的请求参数不可以通过request.getParameter()获取
           data:{}
       }).then(response=>{
           console.log(response.data);
       });
     */
    var vue = new Vue({
        el:"#app",
        methods:{
            testAjax(){
                axios.post(
                    "/SpringMVC/test/ajax?id=1001",
                    {username:"admin",password:"123456"}
                ).then(response=>{
                    console.log(response.data);
                });
            },
            testRequestBody(){
                axios.post(
                    "/SpringMVC/test/RequestBody/json",
                    {username:"admin",password:"123456",age:23,gender:"男"}
                ).then(response=>{
                    console.log(response.data);
                });
            },
            testResponseBody(){
                axios.post("/SpringMVC/test/ResponseBody/json").then(response=>{
                    console.log(response.data);
                });
            }
        }
    });
</script>

data的数据会放在请求体中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uY1qWtSc-1686124821306)(null)]

在模型数据中我们经常创建一些json对象,json数组,将这些和页面中的表单进行双向绑定,表单中输入了数据后,data中设置的模型数据就可以获取到这些输入的数据

9.1、@RequestBody

@RequestBody可以获取请求体信息,使用@RequestBody注解标识控制器方法的形参,当前请求的请求体就会为当前注解所标识的形参赋值

<!--此时必须使用post请求方式,因为get请求没有请求体-->
<form th:action="@{/test/RequestBody}" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit">
</form>
@RequestMapping("/test/RequestBody")
public String testRequestBody(@RequestBody String requestBody){
    System.out.println("requestBody:"+requestBody);
    return "success";
}

输出结果:

requestBody:username=admin&password=123456

9.2、@RequestBody获取json格式的请求参数

在使用了axios发送ajax请求之后,浏览器发送到服务器的请求参数有两种格式:

1、name=value&name=value…,此时的请求参数可以通过request.getParameter()获取,对应

SpringMVC中,可以直接通过控制器方法的形参获取此类请求参数

2、{key:value,key:value,…},此时无法通过request.getParameter()获取,之前我们使用操作

json的相关jar包gson或jackson处理此类请求参数,可以将其转换为指定的实体类对象或map集

合。在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将此类请求参数

转换为java对象

使用@RequestBody获取json格式的请求参数的条件:

1、导入jackson的依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.1</version>
</dependency>

2、SpringMVC的配置文件中设置开启mvc的注解驱动

<!--开启mvc的注解驱动-->
<mvc:annotation-driven />

3、在控制器方法的形参位置,设置json格式的请求参数要转换成的java类型(实体类或map)的参

数,并使用@RequestBody注解标识

<input type="button" value="测试@RequestBody获取json格式的请求参数"@click="testRequestBody()"><br>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
    var vue = new Vue({
        el:"#app",
        methods:{
            testRequestBody(){
                axios.post(
                    "/SpringMVC/test/RequestBody/json",
                    {username:"admin",password:"123456"}
                ).then(response=>{
                    console.log(response.data);
                });
            }
        }
    });
</script>
//将json格式的数据转换为map集合
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody Map<String, Object> map,HttpServletResponse response) throws IOException {
    System.out.println(map);
    //{username=admin, password=123456}
    response.getWriter().print("hello,axios");
}
//将json格式的数据转换为实体类对象
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody User user, HttpServletResponseresponse) throws IOException {
    System.out.println(user);
    //User{id=null, username='admin', password='123456', age=null,gender='null'}
  response.getWriter().print("hello,axios");
}

9.3、@ResponseBody

@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器

@RequestMapping("/testResponseBody")
public String testResponseBody(){
    //此时会跳转到逻辑视图success所对应的页面
    return "success";
}
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
    //此时响应浏览器数据success
    return "success";
}

springmvc(4)https://developer.aliyun.com/article/1530457

相关文章
|
9月前
|
XML JSON fastjson
|
9月前
|
前端开发 Java 数据处理
|
9月前
|
Java Spring
|
21天前
|
前端开发 Java 数据格式
|
29天前
|
存储 JSON 前端开发
|
1月前
|
存储 JSON 安全
SpringMVC 02
SpringMVC 02
12 0
|
6月前
|
存储 JSON Java
SpringMVC应用
SpringMVC应用
41 0
|
9月前
|
存储 前端开发 应用服务中间件
|
11月前
|
XML 设计模式 开发框架
springMVC篇
Spring MVC是基于Java的Web应用程序开发框架,它是Spring框架的一部分,用于简化和加速Web应用程序的开发过程。
55 1
|
10月前
SpringMVC@CookieValue
SpringMVC@CookieValue
25 0