Spring MVC

本文介绍了一个使用SpringMVC框架的实战配置案例,包括Maven依赖配置、web.xml配置、springmvc-config.xml配置等关键步骤,并展示了具体的Controller实现及视图文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring MVC的配置

文件目录

这里写图片描述

po.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>xom.xsh136</groupId>
    <artifactId>spring-mvc-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <!--引入servlet-->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--引入spring mvc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>

</project>

web.xml配置

<?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_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springmvc-config</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc-config</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>encode</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encode</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

springmvc配置文件 springmvc-config.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启mvc注解能力-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--开启默认servlet-handler,主要用于处理非mvc资源-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!--启用类注解自动扫描器,会扫描加注解的所有类-->
    <context:component-scan base-package="com.xsh136.mvcdemo"></context:component-scan>
    <!--启用视图解决方案-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>

    </bean>
</beans>

controller包下的controller类

package com.xsh136.mvcdemo.controller;

import com.xsh136.mvcdemo.entity.User;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ZWW on 2017/7/29.
 */
@Controller
@RequestMapping("/springmvc-config")
@SessionAttributes("user")
public class MVCCtroller {
    @RequestMapping("/index")
    public String welcome(){
        return "welcome";
    }
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(){

        return "register";
    }
   /* @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(User user, HttpSession session){
        session.setAttribute("user",user);
        System.out.println(user);
        return "redirect:index";
    }*/

    /*@RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(User user, RedirectAttributesModelMap modelMap){
        modelMap.addFlashAttribute("user",user);
        System.out.println(user);
        return "redirect:index";
    }*/

    @RequestMapping(value = "/register",method = RequestMethod.POST)

    public String register(User user, ModelMap modelMap){  // 默认在request域
        modelMap.addAttribute("user",user);
        System.out.println(user);
        return "redirect:index";
    }
    @RequestMapping(value = "/upload",method = RequestMethod.GET)
    public String upload(){
        return "upload";
    }
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam("prefix") String prefix, @RequestParam("file") MultipartFile file) throws Throwable{
        String fileName=prefix+file.getOriginalFilename();
        file.transferTo(new File("E:\\upload",fileName));
        return "redirect:list";
    }
    @RequestMapping("/list")
    public String list(ModelMap modelMap){
        File file=new File("E:\\upload");
        String[] fileNames=file.list();
        modelMap.addAttribute("fileNames",fileNames);
        return "list";
    }

    /**
     * 耦合方法
     * @param
     * @param response
     */
    @RequestMapping(value = "/download")
    public void download(String fileName, HttpServletResponse response) throws Throwable{
//        response.addHeader("Content-Disposition","attachment;fileName="+fileName);
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);
        response.setContentType("application/octet-stream");
        OutputStream out=response.getOutputStream();
        InputStream in=new FileInputStream(new File("E:\\upload",fileName));
        IOUtils.copy(in,out);
        out.close();
        in.close();
    }
}

entity包下的实体类User

package com.xsh136.mvcdemo.entity;

/**
 * Created by ZWW on 2017/7/29.
 */
public class User {
    private String name;
    private String pwd;
    private String email;


    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", email='" + email + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

webapp下WEB-INF下jsp包下的jsp文件

welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>欢迎页</title>
</head>
<body>
<h1> Hi  Spring MVC!</h1>
<h2>${user.name}</h2>
</body>
</html>

register.jsp内容

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册页面</title>
</head>
<body>
<form method="post">
    用户名:<input type="text" name="name"/><br>
    密码:<input type="password" name="pwd"/><br>
    邮箱:<input type="email" name="email"><br>
    <input type="submit" value="注册"><br>
</form>
</body>
</html>

list.jsp页面内容

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示上传的文件名</title>
</head>
<body>
<ul>
    <c:forEach items="${fileNames}" var="fileName">
        <li><a href="download?fileName=${fileName}">${fileName}</a></li>
    </c:forEach>
</ul>
</body>
</html>

upload.jsp页面内容

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
    <input type="text" name="prefix"><br>
    <input type="file" name="file"><br>
    <input type="submit" value="上传"><br>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值