WEB应用开发综合实训day3

本文详细介绍了使用Spring MVC进行WEB应用开发的过程,包括新建maven-archetype-webapp项目,配置SpringMvc依赖,设置web.xml,创建项目目录,配置Tomcat,处理静态资源404问题,以及表单数据提交和POST中文乱码的解决方案。此外,还讲解了JSON数据的处理,如使用Fastjson转换器进行对象到JSON的转换,并在实际代码中进行了测试。
摘要由CSDN通过智能技术生成

本节实训内容为Spring Web Mvc框架、表单提交、JSON数据转换器

新建maven-archetype-webapp项目

不要选择前两天的quickstart项目
在这里插入图片描述

导入SpringMvc依赖

pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.18.RELEASE</version>
</dependency>

配置web.xml

web.xml是web项目的核心配置文件,当tomcat服务器启动时,会先加载web.xml配置文件的内容,dispatchServlet:前端中转控制器,将前端请求对应的路径与后端controller中对应的映射匹配
所以我们需要在web.xml中配置dispatchServlet,并且加载spring-mvc.xml

web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--配置中转控制器 dispatchservlet-->
  <servlet>
    <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

创建项目目录

在src/main目录下新建java和resources两个目录并把resources给mark一下
完整项目目录结构如下
在这里插入图片描述

配置tomcat

tomcat8.0下载链接:https://pan.baidu.com/s/1AjWr8AO9Im1xYjdYau09Cg
提取码:8888

下载tomcat后解压
在这里插入图片描述
点击Configure…选中tomcat文件夹路径,按下图红框进行配置
在这里插入图片描述
在这里插入图片描述
选择Deployment,点击+出现Artifact,选择exploded即可
如果没有Artifact就检查pom.xml文件和项目是否为webapp项目
在这里插入图片描述

运行项目

在这里插入图片描述

配置spring-mvc.xml

在resources目录下新建一个spring-mvc.xml文件
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: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.qianfeng.controller">
    </context:component-scan>
</beans>

UserController.java

@Controller
public class UserController {
   

    //定义后台映射 hello
    @RequestMapping("/hello")  // 返回的String都是页面
    public String 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值