(1) 請參考Day27 module
(2) 使用JSON相關設置
maven
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.17.1</version>
</dependency>
spring-servlet.xml
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true"
p:simpleDateFormat="yyyy-MM-dd"
p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>
前面幾天我們使用了很多這個註解,他能夠將回傳的內容不透過視圖直接响應。如果直接回傳物件它就會自動幫我們轉成JSON的形式响應,是不是很方便呢
controller
@RestController
public class JsonController {
@ResponseBody
@GetMapping("JsonDemo")
public Employee JsonDemo(){
Employee emp = new Employee("8888", "Ricky");
return emp;
}
}
Employee
public class Employee {
private String empId;
private String empName;
//getter setter constructor toString略
}
如果你的方法都是需返回响應體,那麼可以就可以將@Controller與@ResponseBody寫成@RestController
訪問redirectDemo
訪問redirectGoogle
訪問forwardDemo
訪問forwardGoogle,無法訪問外部網址
因為在web.xml中我們設定所有請求都會導向DispatcherServlet,如果沒特別為靜態資源做請求配置將會無法取得靜態資源。
staticResourceDemo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>staticResourceDemo</title>
</head>
<body>
<h3>tomcat 圖片顯示:</h3>
<img src="/static/images/tomcat.png">
</body>
</html>
public class StaticResourceController
@Controller
public class StaticResourceController {
@GetMapping("staticResourceDemo")
public String staticResourceDemo() {
return "staticResourceDemo";
}
}
放置一張圖片在路徑
訪問staticResourceDemo
springmvc-servlet.xml
<!-- static resources setting -->
<mvc:resources mapping="/static/**" location="/static/">
<mvc:resource-chain resource-cache="true">
<mvc:resolvers>
<mvc:version-resolver>
<mvc:content-version-strategy patterns="/**"/>
</mvc:version-resolver>
</mvc:resolvers>
</mvc:resource-chain>
</mvc:resources>
訪問staticResourceDemo