1. 程式人生 > 實用技巧 >springmvc響應型別和放行靜態資源

springmvc響應型別和放行靜態資源

一、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>org.example</groupId>
    <artifactId>A03springmvc</artifactId>
    <version>1.0
-SNAPSHOT</version> <packaging>war</packaging> <name>A03springmvc Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8
</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.2.8.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5
</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.2</version> </dependency> </dependencies> <build> <finalName>A03springmvc</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>

二、springmvc的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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--掃描元件-->
    <context:component-scan base-package="com.wuxi"></context:component-scan>
    <!--檢視解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--引數型別裝換器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.wuxi.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>
    <!--配置排程器不攔截靜態資源-->
    <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    <!--開啟springmvc框架註解的支援-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
</beans>

三、controller

package com.wuxi.controllers;

import com.wuxi.beans.Address;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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


@Controller
public class HelloController {
    @RequestMapping("/retString")
    public String retString(Model model) {
        model.addAttribute("name", "櫻木花道");
        model.addAttribute("age", 18);
        // 請求轉發
        return "success";
        // 請求妝發
//        return "forward:/WEB-INF/pages/success.jsp";
        // 重定向
//        return "redirect:/error.jsp";
    }

    @RequestMapping("/retVoid")
    public void retVoid(HttpServletRequest req, HttpServletResponse res) {
        // 請求轉發
//        try {
//            req.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(req, res);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // 重定向
//        try {
//            res.sendRedirect(req.getContextPath() + "/error.jsp");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 設定響應內容
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/html;charset=UTF-8");
        try {
            res.getWriter().write("這是一段中文");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    @RequestMapping("/retModelAndView")
    public ModelAndView retModelAndView() {
        ModelAndView mv = new ModelAndView();
        // 向request域儲存資料
        mv.addObject("name", "流川楓");
        mv.addObject("age", 19);
        // 設定請求轉發的頁面
        mv.setViewName("success");
        return mv;
    }

    @RequestMapping("/retAjax")
    @ResponseBody
    public Address retAjax(@RequestBody Address address) {
        address.setProvince(address.getProvince() + address.getProvince());
        address.setCity(address.getCity() + address.getCity());
        return address;
    }
}

四、jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>springmvc</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(function () {
            $("#retAjax").click(function () {
                $.ajax({
                    url: "retAjax",
                    type: "post",
                    data: JSON.stringify({
                        province: "江蘇省",
                        city: "無錫市"
                    }),
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        console.log(data)
                    }
                })
            })
        })
    </script>
</head>
<body>
<a href="retString">retString</a><br/>
<a href="retVoid">retVoid</a><br/>
<a href="retModelAndView">retModelAndView</a><br/>
<a href="javascript:;" id="retAjax">retAjax</a><br/>
</body>
</html>