文档章节

springMVC 5.1.6版本

mouos
 mouos
发布于 04/18 11:26
字数 1710
阅读 3
收藏 0

入门

导包

配置 web.xml,所有的请求由springMVC管理

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
        <init-param>
             修改默认springmvc加载的配置文件路径 
            <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>DispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>

在 WEB-INF 下创建 DispatcherServlet-servlet.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: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">


    <!-- 配置url处理映射 -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <!-- 配置控制器处理适配器 -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>

    <!-- 配置控制器-相当于配置了访问路径 -->
    <bean name="/user.do" class="com.company.web.controller.UserController"/>

    <!-- 配置资源视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀 -->
        <property name="prefix" value="/WEB-INF/views/"></property>
        <!--后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

创建 UserController

package com.company.web.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class UserController implements Controller {

    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {

        ModelAndView modelAndView = new ModelAndView("user/userlist");
        modelAndView.addObject("name", "tom");
        return modelAndView;
    }
}

创建接收tom的jsp文件 userlist.jsp

<%--
  Created by IntelliJ IDEA.
  User: mac
  Date: 2019-04-18
  Time: 14:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

${name}

</body>
</html>

目录结构

浏览器输入 http://localhost:8080/springmvc_war_exploded/user.do

url处理映射

方式一

即入门 DispatcherServlet-servlet.xml

方式二

    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/user.do">userController</prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
   
    <bean id="userController" class="com.company.web.controller.UserController"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

方式三 --未实现待整理

原因:ControllerClassNameHandlerMapping 未找到

    <!-- 不用配置访问路径,默认的访问路径就是类名 userController.do -->
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
   
    <bean id="userController" name="/user.do" class="com.company.web.controller.UserController"/>
    
    <bean class="com.company.web.controller.UserController"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

控制器处理适配器

方式一

即入门 DispatcherServlet-servlet.xml

方式二

package com.company.web.controller;

import org.springframework.web.HttpRequestHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserControllerHttp implements HttpRequestHandler {

    @Override
    public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

        httpServletRequest.setAttribute("name", "tom");
        httpServletRequest.getRequestDispatcher("/WEB-INF/views/user/userlist.jsp").forward(httpServletRequest, httpServletResponse);
    }
}
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>

    <bean name="/user.do" class="com.company.web.controller.UserControllerHttp"></bean>

注解

配置 DispatcherServlet-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- 配置扫描包 -->
    <context:component-scan base-package="com.company.web.controller"></context:component-scan>

    <!-- 配置处理映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>

    <!-- 配置适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>

    <!-- 配置资源视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
package com.company.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController1 {

    //@RequestMapping("list")
    //@RequestMapping("/list")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list() {
        return "user/userlist";
    }
}

接收表单参数

方式一

    @RequestMapping("add")
    public String add(String username, String password) {
        return "user/info";
    }
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
    <input type="text" name="username"><br>
    <input type="text" name="password"><br>
    <input type="submit" value="提交"><br>
</form>

方式二

    @RequestMapping("add")
    public String add(User user) {
        return "user/info";
    }
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
    <input type="text" name="username"><br>
    <input type="text" name="password"><br>
    <input type="submit" value="提交"><br>
</form>

方式三

public class UserExt {

    private User user;
    private List<User> userList = new ArrayList<>();
    private Map<String, Object> infos = new HashMap<>();
    @RequestMapping("add")
    public String add(UserExt userExt) {
        return "user/info";
    }

1.模型

<form action="${pageContext.request.contextPath}/user/add.do" method="post">
    <input type="text" name="user.username"><br>
    <input type="text" name="user.password"><br>
    <input type="submit" value="提交"><br>
</form>

2.list

<form action="${pageContext.request.contextPath}/user/add.do" method="post">
    <input type="text" name="userList[0].username"><br>
    <input type="text" name="userList[0].password"><br>
    <hr>
    <input type="text" name="userList[1].username"><br>
    <input type="text" name="userList[1].password"><br>

    <input type="submit" value="提交"><br>
</form>

3.map

<form action="${pageContext.request.contextPath}/user/add.do" method="post">
    <input type="text" name="infos['username']"><br>
    <input type="text" name="infos['password']"><br>

    <input type="submit" value="提交"><br>
</form>

使用Model存储数据

    @RequestMapping("list2")
    public String list2(Model model) {

        List<User> list = new ArrayList<User>();
        User user = new User("zhangsan", "123456");
        list.add(user);
        User user1 = new User("lisi", "123");
        list.add(user1);

        model.addAttribute("userlist", list);

        return "user/userlist";
    }

@PathVariable

    @RequestMapping("edit/{id}")
    public String edit(@PathVariable int id, Model model) {

        return "user/userlist";
    }
<a href="${pageContext.request.contextPath}/user/edit/${user.id}.do"></a>

转发和重定向

    //转发
    @RequestMapping("test")
    public String test() {
        //同一个控制器
        //return "forward:list.do";
        
        //不同一个控制器
        return "forward:/user/list.do";
    }
    
    //重定向
    @RequestMapping("test")
    public String test() {
        //同一个控制器
        //return "redirect:list.do";

        //不同一个控制器
        return "redirect:/user/list.do";
    }

@RequestParam

    @RequestMapping("test2")
    /**
     * value:参数名称
     * required:默认值
     * defaultValue:参数是否必须有值
     * */
    public String test3(@RequestParam(value = "id", required = true, defaultValue = "30") int id) {
        return "user/userlist";
    }

@RequestBody 和 @ResponseBody

  • @RequestBody     把json数据转成模型数据
  • @ResponseBody   返回json对象

导包

配置文件 DispatcherServlet-servlet.xml

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!--  配置json转换器,springMVC使用jaskson来转换json -->
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
            </list>
        </property>
    </bean>

接收和响应json数据

adduser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>

    <script>
        function tojson() {

            var url = '${pageContext.request.contextPath}/user/save.do';
            var username = $('#username').val();
            var password = $('#password').val();
            var jsonObj = {username: username, password: password};

            var parm = JSON.stringify(jsonObj);

            $.ajax({
                type: 'post',
                url: url,
                contentType: 'application/json;charset=utf-8',
                data: parm,
                success: function (respData) {

                }
            })
        }
    </script>
</head>
<body>

<form action="${pageContext.request.contextPath}/user/save.do" method="post">
    <input type="text" name="username" id="username"><br>
    <input type="text" name="password" id="password"><br>
    <input type="button" value="json格式数据" onclick="tojson()"><br>
</form>

</body>
</html>

 

    @RequestMapping("save")
    public @ResponseBody User save(@RequestBody User user) {
        System.out.println(user);
        return user;
    }

响应json数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/user/save.do" method="post">
    <input type="text" name="username" id="username"><br>
    <input type="text" name="password" id="password"><br>
    <input type="submit" name="提交"><br>
</form>

</body>
</html>

 

    @RequestMapping("save")
    public @ResponseBody User save(User user) {
        System.out.println(user);
        return user;
    }

关于多视图错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in ServletContext resource [/WEB-INF/DispatcherServlet-servlet.xml]: Cannot create inner bean 'org.springframework.web.servlet.view.xml.MarshallingView#7675bdb0' of type [org.springframework.web.servlet.view.xml.MarshallingView] while setting bean property 'defaultViews' with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.xml.MarshallingView#7675bdb0' defined in ServletContext resource [/WEB-INF/DispatcherServlet-servlet.xml]: Cannot create inner bean 'org.springframework.oxm.jaxb.Jaxb2Marshaller#618ea1bf' of type [org.springframework.oxm.jaxb.Jaxb2Marshaller] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.oxm.jaxb.Jaxb2Marshaller#618ea1bf': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.oxm.jaxb.Jaxb2Marshaller] from ClassLoader [ParallelWebappClassLoader...

需要导包

springmvc拦截器

配置拦截器 DispatcherServlet-servlet.xml 

    <mvc:interceptors>
        <!-- 配置登录拦截器 -->
        <mvc:interceptor>
            <!-- /** 拦截所有的请求 -->
            <mvc:mapping path="/**"/>
            <!-- 不需要拦截的 -->
            <!-- <mvc:exclude-mapping path="" -->
            <bean class="com.conpany.web.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

LoginInterceptor

package com.company.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        //排除不需要拦截路径
        System.out.println("客户端访问资源的路径:" + request.getRequestURI());
        if (request.getRequestURI().endsWith("login.do")) {
            return true;//放行
        }

        //如果已经登录,也要放行
        if (request.getSession().getAttribute("user") != null) {
            return true;
        }

        //进入到login页面
        request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("未返回视图前 后处理");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("返回视图前 后处理");
    }
}

默认跳转到登录页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<jsp:forward page="WEB-INF/views/login.jsp"></jsp:forward>

</body>
</html>

 

© 著作权归作者所有

mouos
粉丝 1
博文 245
码字总数 127890
作品 0
其它
私信 提问
Spring Framework 5.1.6、5.0.13 与 4.3.23 发布

Spring Framework 5.1.6、5.0.13 与 4.3.23 发布了。 v5.1.6 包含 49 个 bug 修复和功能改进; v5.0.13 是 5.0.x 系列的最后一个版本,包含了 25 个 bug 修复和功能改进; v4.3.23 带来了 20...

h4cd
04/02
0
0
spring boot (四)mybatis

上回说到web应用的前半截,还没有持久层,一个没有持久层的web应用不是完整的,现在我们就来使用mybatis连接MySQL存储数据,如果还没有安装MySQL数据库,百度安装(手动滑稽)。 数据库配置 ...

lelinked
04/07
0
0
Mybatis 学习笔记三 搭配pageHelper分页插件使用

Mybatis 学习笔记三 搭配pageHelper分页插件使用 基于《Mybatis 学习笔记二 与spring搭配》 maven依赖 配置 mybatis配置 conf.xml 注意:保持基本配置即可; spring配置 applicationContext...

晨猫
2018/11/16
0
0
centOS怎样强制卸载PHP

这个是原创的,当然也是在前人的基础上,自己留个拷贝,其他人也不用再摸索了。转载请保留版权信息谢谢:http://blog.csdn.net/21aspnet/ 很无语,centOS居然php版本才5.1.6,很多开源的CMS...

干死it
2014/06/17
0
0
centOS怎样强制卸载PHP以及自定义安装PHP

这个是原创的,当然也是在前人的基础上,自己留个拷贝,其他人也不用再摸索了。 转载请保留版权信息谢谢:http://blog.csdn.net/21aspnet/ 很无语,centOS居然php版本才5.1.6,很多开源的CMS...

晨曦之光
2012/03/09
2.6K
0

没有更多内容

加载失败,请刷新页面

加载更多

Linux使用源码包安装软件

前言: 最近整理一些以前的学习笔记。 过去都是存储在本地,此次传到网络留待备用。 源码包 Linux软件多数免费、开源,是开发人员编写的,具有很强可读性的一组相关代码文本。 源码包 --> 编...

迷失De挣扎
今天
2
0
IPv4如何转换为IPv6?

ipv6已经逐渐在应用,现在已经有很多的运营商支持ipv6,前天我们也发布了如何让电脑使用ipv6地址?有很多朋友在问?ipv6有什么作用,它的表示方式是什么,今天我们来一起来详细了解下ipv6相关计...

xiangyunyan
今天
3
0
小白讲网络安全系列

注入攻击防护 XSS注入 SQL注入 命令注入 文件上传 文件解压缩 CSRF防护 对称加密 非对称加密 数字证书 数字签名 完整性校验 消息验证码 单向散列Hash函数 口令单向加密算法 审计日志 认证鉴权...

一刀
今天
2
0
MYSQL 嵌套事务(SAVEPOINT) 与Spring 事务传播

摘要 savepoint 关键字可以实现嵌套事务。结合savepoint关键字,更方便理解spring的事务传播。 事务嵌套 初始化表脚本 drop table t;create table t(a int, primary key(a)); 开启事务 my...

liangxiao
今天
4
0
Chrome OS 更新新版本可让Linux访问USB连接的Android设备

谷歌再次为Chrome OS带来了重大版本更新,使版本号达到了75。本次更新的一大亮点就是允许在Chrome OS上运行的Linux能够识别通过USB方式连接的Android设备,能够让用户使用Linux进行调试等等。...

linuxCool
昨天
17
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部