Spring實戰——構建Spring Web應用程式
本篇部落格記載搭建springmvc的過程,使用Java將DispatcherServlet配置在Servlet容器中,而不是使用web.xml 進行配置。
注意:使用Java配置僅適用於支援servlet3.0的伺服器,如Tomcat7或者更高版本。
專案使用Maven搭建:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.2.6.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- springframework 4 dependencies begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <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>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- springframework 4 dependencies end --> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> </dependencies>
一、Spring MVC起步
1、先看一個圖:
上圖是SpringMVC請求流程圖解。SpringMVC請求流程如下:
①請求離開瀏覽器,會帶著使用者所請求內容的資訊到DispatcherServlet。
②DispatcherServlet會查詢一個或多個處理器對映(handlerMapping)來確定請求的下一站在哪裡。然後會將請求發給 SpringMVC控制器(Controller)。
③選擇了合適的控制器之後,DispatcherServlet就將請求發給Controller,然後請求會卸下負載(就是帶的使用者請求資訊) 耐心等待Controller處理這些資訊。
④控制器在處理完請求之後,通常會產生一些資訊,控制器將這些資訊打包成模型,並標示出用於渲染資料的檢視。
⑤DispatcherServlet將會使用檢視解析器來將邏輯檢視名匹配為一個特定的檢視實現。然後將資料渲染在檢視上(JSP)。
二、搭建SpringMVC
1、配置DispatcherServlet
package com.mfc.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* @author 74790
* 2018-12-23 17:27:39
* 使用javaConfig替代web.xml搭建springmvc
*
* 繼承AbstractAnnotationConfigDispatcherServletInitializer抽象類之後,
* 當部署在Servlet3.0容器中的時候,容器會自動發現它,並用它來配置Servlet上下文
*/
public class WebApplicationConfig extends
AbstractAnnotationConfigDispatcherServletInitializer {
//指定Spring配置,用於掃描元件
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{RootConfig.class};
}
//指定SpringMVC配置
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{WebConfig.class};
}
//將DispatcherServlet對映到"/"
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
2、配置Springmvc:WebConfig.java
package com.mfc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* @author 74790
* 2018-12-23 17:37:04
* SpringMvc配置
* @EnableWebMvc : 啟用springmvc
* @ComponentScan : 掃描controller所在的包
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.mfc.ctrl")
public class WebConfig extends WebMvcConfigurerAdapter{
//配置JSP檢視解析器
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
//配置靜態資源的處理
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
3、配置掃描元件的檔案:RootConfig.java
package com.mfc.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan(basePackages={"com.mfc"},
excludeFilters = {@Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
public class RootConfig {
}
此時、SpringMVC框架已經搭建起來了。
三、SpringMVC之前沒有注意的用法
1、從Controller傳遞資料模型到檢視中的方法
①如果使用model.addAttribute(tUser); 沒有給鍵的話,Spring會推斷鍵的值。一般使用還是建議使用 model.addAttribute("tUser", tUser);
②Controller中的Model可以使用Map代替。
@RequestMapping("testParam1")
public String testParam1(@RequestParam("id")String id, Model model){
System.out.println("傳過來的引數是:"+id);
model.addAttribute("id", id);
TUser tUser = new TUser();
//此時鍵會被spring推斷為:tUser
model.addAttribute(tUser);
//此時鍵為:tUser
model.addAttribute("tUser", tUser);
return "userList";
}
@RequestMapping("testParam1")
public String testParam1(@RequestParam("id")String id, Map<String, Object> model){
System.out.println("傳過來的引數是:"+id);
model.put("id", id);
TUser tUser = new TUser();
model.put("tUser", tUser);
return "userList";
}
2、前端向Controller中傳遞引數除了使用@RequestParam還可以使用@PathVariable。
<a href="<%=server_path%>/tUserCtrl/testParam1.do?id=123">測試URL掛引數</a>
<a href="<%=server_path%>/tUserCtrl/testParam2/1234321">測試URL掛引數</a>
@Controller
@RequestMapping("/tUserCtrl")
public class TUserCtrl {
@RequestMapping("testParam1")
public String testParam1(@RequestParam("id")String id, Model model){
System.out.println("傳過來的引數是:"+id);
model.addAttribute("id", id);
return "userList";
}
@RequestMapping("/testParam2/{id}")
public String testParam2(@PathVariable("id") String id, Model model){
System.out.println("傳過來的引數是:"+id);
model.addAttribute("id", id);
return "userList";
}
}
3、使用@Valid驗證表單:
註解 | 描述 |
@AssertFalse | 所註解的元素必須是Boolean型別,並且值為false |
@AssertTrue | 所註解的元素必須是Boolean型別,並且值為true |
@DecimalMax | 所註解的元素必須是數字,並且他的值要小於或者等於給定的BigDecimalString值 |
@DecimalMin | 所註解的元素必須是數字,並且他的值要大於或者等於給定的BigDecimalString值 |
@Digits | 所註解的元素必須是數字,並且它的值必須有指定的位數 |
@Future | 所註解的元素必須是一個將來的日期 |
@Max | 所註解的元素必須是一個數字,並且它的值要小於或者等於給定的值 |
@Min | 所註解的元素必須是一個數字,並且它的值要大於或者等於給定的值 |
@NotNull | 所註解元素的值必須不能為null |
@Null | 所註解元素的值必須為null |
@Past | 所註解的值必須是一個已過去的日期 |
@Pattern | 所註解的元素的值必須匹配給定的正則表示式 |
@Size | 所註解的元素的值必須是String、集合或陣列,並且它的長度要符合給定的範圍 |
①使用校驗註解的實體類:
package com.mfc.entity;
import javax.validation.constraints.Size;
import com.sun.istack.internal.NotNull;
public class TUser {
//非空,5到16的字元
@NotNull
@Size(min=5,max=16)
private String userName;
@NotNull
@Size(min=5,max=16)
private String pass;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
②實現校驗的Controller
@RequestMapping("addUser")
public String addUser(@Valid TUser tUser, Errors errors){
//校驗表單輸入
if(errors.hasErrors()){
return "index";
}
System.out.println("校驗通過,下面是獲取的密碼:");
System.out.println(tUser.getPass());
return "redirect:/tUserCtrl/findAllUser.do";
}
③頁面表單程式碼
<form action="<%=server_path%>/tUserCtrl/addUser.do" method="post">
userName:<input type="text" name="userName"><br>
pass : <input type="password" name="pass"><br>
<input type="submit" value="submit">
</form>