springmvc请路径参数,springmvc-json-ajax使用,springmvc文件上传,springmvc文件下载,springmvc拦截器(内容较多)

springmvc 专栏收录该内容
4 篇文章 0 订阅

按照操作,绝对都可以实现,亲测。。。。。(项目所有文件和目录结构全都放上去了)

idea工具,创建maven项目

 

第一步:

放置各种配置文件:

pom.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>com.zit</groupId>
    <artifactId>springmvc03</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springmvc03</name>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

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


        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</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>

        <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <sourceDirectory>src/main/java</sourceDirectory>
        <!-- 解决无法加载资源配置文件 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <!-- 配置maven编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <!-- 配置jetty servlet服务器 -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.12.v20180830</version>
                <configuration>
                    <stopKey>exit</stopKey>
                    <stopPort>8989</stopPort>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <reload>manual</reload>
                    <webAppConfig>
                        <contextPath>/</contextPath>
                    </webAppConfig>
                    <httpConnector>
                        <port>80</port>
                    </httpConnector>
                </configuration>
                <executions>
                    <execution>
                        <id>jetty-run</id>
                        <phase>test</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>


    </build>


</project>

src/main/resources目录下:src/main/resources/smvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.zit.controller"/>

    <!-- 在没有配置mvc:resources的时候没有问题,一旦配置了mvc:resources,注解方式的url就没有加载 -->
    <mvc:annotation-driven>
        <!-- 消息转换器 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 文件上传支持 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 104857600 代表100MB -->
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="40960"/>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/admin/**"/>
            <mvc:exclude-mapping path="/admin/login"/>
            <bean class="com.zit.interceptor.TestInterceptor"/>
        </mvc:interceptor>

    </mvc:interceptors>


    <!--<mvc:resources mapping="/images/**" location="/images/" />-->


    <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/template/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

src/main/webapp/WEB-INF/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_4_0.xsd"
         version="4.0">
    <display-name>springmvc02</display-name>
    <!--springmvc 5.0.9-->
    <!--不使用注解,可以使用配置-->
    <!-- //@WebServlet(name = "springmvc", urlPatterns = {"/"}, loadOnStartup = 1,
     initParams = {@WebInitParam(name = "contextConfigLocation", value = "classpath:smvc.xml")})-->


    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:smvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--  &lt;!&ndash; 配置spring框架中的编码过滤器,实现接post请求中文乱码处理 &ndash;&gt;
      <filter>
        <filter-name>characterEncodingFilter</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>
        <init-param>
          <param-name>forceEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>-->

    <!-- spring filter 编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!--访问静态资源-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.js</url-pattern>
        <url-pattern>*.jpg</url-pattern>
        <url-pattern>*.gif</url-pattern>
        <url-pattern>*.png</url-pattern>
        <url-pattern>*.rar</url-pattern>
    </servlet-mapping>

    <!--配置web项目的web.xml文件的首页-->
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!--  <error-page>&lt;!&ndash;当系统出现404错误,跳转到页面nopage.html&ndash;&gt;
        <error-code>404</error-code>
        <location>/404.html</location>
      </error-page>
      <error-page>&lt;!&ndash;当系统出现java.lang.NullPointerException,跳转到页面error.html&ndash;&gt;
        <exception-type>java.lang.Exception</exception-type>
        <location>/error.html</location>
      </error-page>
      <session-config>&lt;!&ndash;会话超时配置 ,单位分钟&ndash;&gt;
        <session-timeout>30</session-timeout>
      </session-config>-->

</web-app>

配置文件完成。。。。

第二步:

目录结构以及目录结构中的内容:

controller目录下的文件:

AdminController.java

package com.zit.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @RequestMapping("/index")
    public void index() {

    }

    @RequestMapping("/login")
    public void login() {

    }

    //<img src=check/>
    @RequestMapping("/check")
    public void check(HttpServletRequest req, HttpServletResponse resp) {

    }
}

DownloadController.java

package com.zit.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
public class DownloadController {

    @RequestMapping("/down")
    @ResponseBody
    public ResponseEntity<byte[]> down(HttpServletRequest req) {
        String f = req.getServletContext().getRealPath("/images/images.rar");
        File ff = new File(f);
        System.out.println(ff.getName());
        ResponseEntity<byte[]> entity = null;
        try {
            FileInputStream fis = new FileInputStream(ff);

            byte[] body = new byte[fis.available()];
            fis.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchment;filename=" + ff.getName());
            System.out.println("filename" + ff.getName());
            HttpStatus statusCode = HttpStatus.OK;
            entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return entity;
    }

}

HomeController.java

package com.zit.controller;

import com.zit.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HomeController {
    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        return "hello-index";
    }

    @GetMapping("/abc")
    public void add(Model model) {
        model.addAttribute("name", "李四");
        List<Student> list = new ArrayList<Student>();
        Student st1 = new Student();
        st1.setId(3);
        st1.setName("金刚");
        st1.setScore(83);
        Student st2 = new Student();
        st2.setId(5);
        st2.setName("郝刚");
        st2.setScore(93);
        list.add(st1);
        list.add(st2);
        model.addAttribute("students", list);

        // /WEB-INF/template/abc.jsp
    }

    @RequestMapping("/xxx")
    public ModelAndView xxx() {
        ModelAndView mv = new ModelAndView("admin");//默认找admin.jsp视图文件
        mv.addObject("user", "李青");
        // mv.setViewName("ok");//WEB-INF/template/ok.jsp
        //mv.setViewName("");
        return mv;
    }

  /*  @GetMapping("/add")  @ResponseBody  /add?name=jack&id=6
    public void add(String name, int id, PrintWriter out){
        out.print(name);
        out.print(id);
    }*/

/*    @GetMapping("/add/{name}/{id}")
    @ResponseBody
    public void add(@PathVariable("name") String nn, @PathVariable("id") int id, PrintWriter out) {
        out.print(nn);
        out.print(id);
    }*/


    //http://localhost:8080/add?ii=30&nn=james
    @GetMapping("/add")
    @ResponseBody
    public void add(@RequestParam(value = "nn", required = false, defaultValue = "李四") String name, @RequestParam("ii") int id, PrintWriter out) {
        out.print(name);
        out.print(id);
    }


}

TimeController.java

package com.zit.controller;

import com.zit.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class TimeController {

    @GetMapping("/timer")
    @ResponseBody
    public String time() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    @GetMapping("/find")
    @ResponseBody
    public Student find() {
        Student st = new Student();
        st.setScore(80);
        st.setId(2);
        st.setName("李勇");
        return st;

    }

    /*@GetMapping("/query") @ResponseBody*/
    @RequestMapping(value = "/query")
    @ResponseBody
    public List<Student> query() {
        Student st = new Student();
        st.setScore(80);
        st.setId(2);
        st.setName("李勇");
        Student st2 = new Student();
        st2.setScore(88);
        st2.setId(4);
        st2.setName("李香兰");
        List<Student> list = new ArrayList<>();
        list.add(st);
        list.add(st2);
        return list;

    }

    @PostMapping("/save")
    @ResponseBody
    public boolean save(Student tt) {
        System.out.println("insert into stu values(" + tt.getId() + ",'" + tt.getName() + "'," + tt.getScore() + ")");
        return true;
    }


}

UploadController.java

package com.zit.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UploadController {
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("name") String name, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) {
        String path = req.getServletContext().getRealPath("/upload/user");
        File ff = new File(path);
        System.out.println(3);
        if (!ff.exists()) {
            ff.mkdirs();
        }
        /*System.out.println(path);
        System.out.println(name);
        System.out.println(file.getName());
        System.out.println(file.getSize());//大小
        System.out.println(file.getOriginalFilename());//文件名称*/
        try {
            file.transferTo(new File(path, file.getOriginalFilename()));

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }


    @RequestMapping("/uploads")
    public String uploads(@RequestParam("name") String name, @RequestParam("file") CommonsMultipartFile[] file, HttpServletRequest req, Model model) {
        String path = req.getServletContext().getRealPath("/upload/user");
        File ff = new File(path);
        if (!ff.exists()) {
            ff.mkdirs();
        }
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (CommonsMultipartFile f : file) {
            System.out.println(path);
            System.out.println(name);
            System.out.println(f.getName());
            System.out.println(f.getSize());//大小
            System.out.println(f.getOriginalFilename());//文件名称
            try {
                f.transferTo(new File(path, f.getOriginalFilename()));

            } catch (IOException e) {
                e.printStackTrace();
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", f.getOriginalFilename());
            map.put("size", f.getSize());
            list.add(map);
        }
        model.addAttribute("files", list);

        return "/up";
    }
}

UserController.java

package com.zit.controller;


import com.zit.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/show/{nn}/{id}")
    @ResponseBody
    public void show(@PathVariable String nn, @PathVariable int id, PrintWriter out) {

        out.print("欢迎" + nn + "hello world" + id);
    }

    @GetMapping("/save")
    @ResponseBody
    public String save() {
        // void save()
        // /WEB-INF/template/user/save.jsp

        //String save()
        // return "ok" 会使用 /WEB-INF/template/ok.jsp模板文件渲染显示
        // /WEB-INF/template/user/save.jsp

        // String save() 如果加上@ResponseBody,那么return 返回的字符串直接输出到网页上

        return "ok";
    }

    //@PostMapping("/add")
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @ResponseBody
    //@GetMapping("/add")@ResponseBody和上面性质一样
    public void add(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.getWriter().print(req.getParameter("id"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/*    @GetMapping("/myadd") @ResponseBody
    public void myadd(String name,String gender){
        System.out.println(name+","+gender);
    }*/

    @GetMapping("/myadd")
    @ResponseBody
    public void myadd(Student student, PrintWriter out) {

        out.print(student);
    }


    @GetMapping("/aaa")
    public String aaa() {
        //return "forward:aaa.jsp"; // 转发到/user/aaa.jsp找视图,请求地址不变
        return "forward:/aaa.jsp"; // /aaa.jsp
    }

    @GetMapping("/bbb")
    public String bbb() {
        // /user/bbb.jsp跳转重定向,地址会改变,不传值
        //return "redirect:bbb.jsp";

        // /bbb.jsp重定向
        //return "redirect:/bbb.jsp";

        return "redirect:t3:action";  //重定向到/user/t3.action

    }
}

controller包中的内容结束。。。。。。。

 

src/main/java/com.zit.entity包下的内容:

Student.java

package com.zit.entity;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    private int score;
}

entity包下的内容结束。。。。

 

src/main/java/com.zit/interceptor包下的内容:

TestInterceptor.java

package com.zit.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 TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("prehandle");
        //return false; //拦住,通不过停止

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

interceptor包下的内容结束。。。。。。

src/main/java/com.zit/servlet包下的内容:

Upload.java

package com.zit.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/myupload.do")
@MultipartConfig
public class Upload extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("name"));
        Part part = req.getPart("file");
        System.out.println(part.getSubmittedFileName());
        System.out.println(part.getName());
        System.out.println(part.getSize());
        String path = getServletContext().getRealPath("/upload");
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
            part.write(path + "/" + part.getSubmittedFileName());
        }
    }
}

src/main/java包下的内容完全结束。。。。

 

src/main/resources包下的内容:

smvc.xml   这个之前已经写过了。。。。。。,看前面。。。

 

src/main/resources包下的内容已经完全结束。。。。。。

 

src/main/webapp包下的内容:(按着顺序来)

webapp/css/index.css

h3 {
    color: red;
}

webapp/images/放置a.jpg  b.jpg  c.jpg   d.jpg  四张图片用来使用

webapp/css/js文件夹下:

上面的自己引入jquery-3.3.1.js  jar包

my.js

alert("ok");

/upload/user是自动生成的,不用管

通过上图可以改变输出路径,生成/upload/user路径

 

 

 

webapp/WEB-INF目录下classes和lib都是自动生成的,咱们不用管,只需要注意WEB-INF/template目录下的内容就行

template/admin/index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>后台管理首页...</h3>
</body>
</html>

template/login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>管理员登录页面...</h3>
</body>
</html>

 

template/user/save.jsp

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

 

template/abc.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>欢迎:${name}</h3>
<c:forEach items="${students}" var="stu">
    <h3>${stu.name}===${stu.score}</h3>

</c:forEach>
</body>
</html>

template/admin.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>欢迎:${user}</h3>
</body>
</html>

template/up.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>共上传了${files.size()}文件</h3>
<c:forEach items="${files}" var="f">
<h3>文件名称:${f.name},大小:${f.size}字节</h3>
</c:forEach>
</body>
</html>

 

WEB-INF/web.xml上面已经写过了。。看上文

webapp/404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404</title>
</head>
<body>
<h3>404页面找不到</h3>
</body>
</html>

webapp/add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.js"></script>
    <script>
        $(function () {
            $('input[type=button]').click(function () {
                $.ajax({
                    type:'post',
                    url:'/save',
                    data:{id:$('input[name=id]').val(),name:$('input[name=name]').val(),score:$('input[name=score]').val()},
                    dataType:'json',
                    success:function (d) {
                        alert(d)
                    }
                })
            });


     /*       $("input[type=button]").click(function () {
                $.ajax({
                    type: "post",
                    url: "/save",
                    data: {
                        id: $("input[name=id]").val(),
                        name: $("input[name=name]").val(),
                        score: $("input[name=score]").valueOf()
                    },
                    dataType: "json",
                    success: function (d) {
                        alert(d)
                    }

                })
            })*/

        })

    </script>
</head>
<body>
学号:<input type="text" name="id"><br>
姓名"<input type="text" name="name"><br>
成绩:<input type="text" name="score"><br>
<input type="button" value="保存">

</body>
</html>

webapp/down.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>下载图片</title>
</head>
<body>
<a href="/images/a.jpg" download>下载图片</a> <br>
<a href="/images/images.rar" download>下载rar</a>

<h3>安全下载</h3>
<a href="/down" download >下载rar</a>
</body>
</html>

webapp/error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
<h3>错误页面</h3>
</body>
</html>

webapp/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.js"></script>
    <script>
        $(function () {
            setInterval(function () {
                $("h3:first").load("/timer")
            },1000)

        })



    </script>
</head>
<body>
<h3></h3>

</body>
</html>

webapp/mindex.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/my.js"></script>
</head>
<body>
<h3>hello world</h3>
<img src="images/a.jpg" alt="">
</body>
</html>

webapp/mindex.jsp

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

<br>
${3*2}
<a href="show.do">show查看</a>
</body>
</html>

 

webapp/myup.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>servlet 3文件上传</h3>
<form action="/myupload.do" method="post" enctype="multipart/form-data">
    姓名:<input type="text" name="name"><br>
    文件:<input type="file" name="file"><br>
    <input type="submit" value="提交文件">
</form>

<h3>springmvc文件上传</h3>
<form action="/upload" method="post" enctype="multipart/form-data">
    姓名:<input type="text" name="name"><br>
    文件:<input type="file" name="file"><br>
    <input type="submit" value="提交文件">
</form>

<h3>多文件上传</h3>
<form action="/uploads" method="post" enctype="multipart/form-data">
    姓名:<input type="text" name="name"><br>
    文件:<input type="file" name="file" multiple><br>
    <input type="submit" value="提交文件">
</form>
</body>
</html>

 

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值