springMVC
SpringMVC:前端控制器,映射器,適配器,控制器,試圖解析器
前端控制器
前端控制器在web.xml中配置
<servlet>
<!-- 命名 -->
<servlet-name>springmvc</servlet-name>
<!-- 加載包中的前端控制器 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 讓服務(wù)器已啟動(dòng)就開始加載文件springMVC.xml,用的是contextConfigLocation這個(gè)屬性 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!-- 啟動(dòng)加載 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 對(duì)應(yīng)上面的命名 -->
<servlet-name>springmvc</servlet-name>
<!-- 對(duì)文件進(jìn)行攔截來執(zhí)行上面的程序, "/"代表攔截所有的-->
<url-pattern>/</url-pattern>
</servlet-mapping>
兩種映射器
<!-- 映射器 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- 映射器2 -->
<bean class=" org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<!-- 這里的值要和控制器中的id相對(duì)應(yīng) -->
<prop key="/text1">text</prop>
<prop key="/text1">text</prop>
</props>
</property>
</bean>
兩種適配器
<!-- 適配器 要實(shí)現(xiàn)Controller接口-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!-- 適配器2 要實(shí)現(xiàn) HttpRequestHandler接口 -->
<bean class=" org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>
控制器
<!-- 控制器 -->
<bean class="com.hemi.controller.MyController" name="/text" id="text"></bean>
public class MyController implements org.springframework.web.servlet.mvc.Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String username = req.getParameter("username");
String password = req.getParameter("password");
// req.setAttribute("username", username);
// req.setAttribute("password", password);
ModelAndView view = new ModelAndView();
if("lisi".equals(username)&&"123".equals(password)){
view.setViewName("Hello.jsp");
}
else{
view.setViewName("login.jsp");
}
return view;
}
}
視圖解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
視圖解析器的配置前綴后綴
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/"></property>
<!-- 后綴 -->
<property name="suffix" value=".jsp"></property>
</bean>
注解適配器和映射器
注解適配器和映射器要一起使用才有效
<!-- 掃描包 -->
<context:component-scan base-package="com.hemi.controller"></context:component-scan>
<!-- 配置注解 1-->
<!-- 配置映射器注解 -->
<bean class=" org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping "></bean>
<!-- 配置適配器注解 -->
<bean class=" org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
<!--配置注解2-->
<!-- 終極替換上面的注解 -->
<mvc:annotation-driven></mvc:annotation-driven>
Controller里使用注解
@Controller
public class TextControler{
@RequestMapping(show1)
public ModelAndView show1(){}
}
cotroller里面返回?cái)?shù)據(jù)
ModleAndView類型返回值 返回值用一般用view保存使用 view.addObject方法(域?qū)ο笠部梢裕?/p>
@RequestMapping("show1")
public ModelAndView show1(HttpServletRequest req){
String username = req.getParameter("username");
String password = req.getParameter("password");
ModelAndView view = new ModelAndView();
view.addObject("username", username);
view.addObject("password", password);
view.setViewName("Hello");
return view;
}
String類型返回值返回?cái)?shù)據(jù)可以域?qū)ο?,Modle以及ModleMap來保存數(shù)據(jù)
@RequestMapping("show2")
public String show2(Model model,HttpServletRequest req){
String username = req.getParameter("username");
String password = req.getParameter("password");
model.addAttribute("username", username);
model.addAttribute("password", password);
return "Hello";
}
void類型返回值要用域?qū)ο髞肀4鏀?shù)據(jù)
@RequestMapping("show3")
public void show3(HttpServletRequest req,HttpServletResponse resp){
String username = req.getParameter("username");
String password = req.getParameter("password");
req.setAttribute("username", username);
req.setAttribute("password", password);
try {
req.getRequestDispatcher("Hello.jsp").forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
參數(shù)綁定
簡(jiǎn)單參數(shù)綁定 pojo參數(shù)綁定,自定義類型
簡(jiǎn)單參數(shù)綁定:傳入的數(shù)據(jù)和jsp中寫入request中的數(shù)據(jù)參數(shù)相同,如果想用形參則使用注解@RequestParam("username")是取值 String name是取得別名
Pojo參數(shù)綁定:定義一個(gè)實(shí)體類和jsp中放入的數(shù)據(jù)類型相同,然后傳入實(shí)體類可以獲得參數(shù)
自定義類型: 創(chuàng)建一個(gè)轉(zhuǎn)換類實(shí)現(xiàn)Converter<String, Date>接口 重寫里面的方法進(jìn)行轉(zhuǎn)換,在springMVC.xml中配置將org.springframework.format.support.FormattingConversionServiceFactoryBean類引入里面注入轉(zhuǎn)換類,在注解驅(qū)動(dòng)的屬性中用conversion-service將配置的類加載驅(qū)動(dòng)中,在實(shí)體類需要轉(zhuǎn)換類型的字段(日期)上面添加 @DateTimeFormat(pattern="yyyy-MM-dd")
自定義轉(zhuǎn)換類:
public class DateConvert implements Converter<String, Date>{
@Override
public Date convert(String source) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
springMVC中配置
<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.hemi.controller.convert.DateConvert"></bean>
</list>
</property>
</bean>
User實(shí)體類中配置
private String username;
private String password;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date date;
控制器:
@RequestMapping("show4")
public String show4(Model model,User user){
model.addAttribute("user", user);
return "Hello";
}
}
參數(shù)綁定-數(shù)組,包裝數(shù)據(jù)類型 list集合
login.jsp:
<form action="show5" method="post">
用戶名:<input type="text" name="username"><br>
密碼:<input type="password" name="password"> <br>
日期<input type="text" name="date"><br>
<!--傳遞list集合中裝的是多個(gè)地址對(duì)象-->
<input type="text" placeholder="請(qǐng)輸入地址" name="add[0].addres"><br>
<input type="text" placeholder="請(qǐng)輸入編碼" name="add[0].code"><br>
<input type="text" placeholder="請(qǐng)輸入地址" name="add[1].addres"><br>
<input type="text" placeholder="請(qǐng)輸入編碼" name="add[1].code"><br>
<!--傳遞單個(gè)地址的實(shí)體對(duì)象-->
<input type="text" placeholder="請(qǐng)輸入地址" name="add.addres"><br>
<input type="text" placeholder="請(qǐng)輸入編碼" name="add.code"><br>
<!--傳遞一個(gè)數(shù)組-->
<input type="checkbox" name="hobby" value="basketball">籃球<br>
<input type="checkbox" name="hobby" value="football">籃球<br>
<input type="checkbox" name="hobby" value="tennis">網(wǎng)球
<input type="submit" value="登錄">
</form>
user類:
private String username;
private String password;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date date;
private List<Address> add;
private String[] hobby;
控制器:
@RequestMapping("show5")
public String show5(Model model,User user){
model.addAttribute("user", user);
return "Hello";
}
全局異常處理開發(fā):
1、自定義異常類
2、自定義異常處理器實(shí)現(xiàn) HandlerExceptionResolver接口
3、在springmvc配置文件中配置全局異??刂破?/p>
自定義異常類:
public class CustomException extends Exception{
private String msg;
public CustomException(String msg) {
super(msg);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
自定義異常處理器:
public class ExceptionHandler implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object object,
Exception ex) {
CustomException customException=null;
if (ex instanceof CustomException) {
customException=(CustomException)ex;
}else{
customException=new CustomException("未知錯(cuò)誤");
}
ModelAndView view = new ModelAndView();
view.addObject("error", customException);
view.setViewName("error");
return view;
}
}
springMVC的配置
<!-- 定義全局異常 -->
<bean class="com.hemi.exception.handler.ExceptionHandler"></bean>
靜態(tài)資源的釋放
在配置文件中進(jìn)行配置
<!-- 靜態(tài)資源釋放-->
<mvc:resources location="/image/" mapping="/image/*.*"></mvc:resources>
文件上傳的步驟
1、編寫配置文件
<!-- 配置文件上傳處理 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
2、編寫控制器
上傳單個(gè)文件:
public String upload(MultipartFile file,HttpServletRequest req) throws IllegalStateException, IOException{
if(file==null){
return "uploadFile";
}
//取出文件名
String filename = file.getOriginalFilename();
//根據(jù)文件的虛擬入境找到真實(shí)入境
String path = req.getServletContext().getRealPath("/temp");
File file2 = new File(path);
if (!file2.exists()) {
//創(chuàng)建目錄
file2.mkdirs();
}
//將傳入的文件按照真實(shí)入境和文件名寫出來
file.transferTo(new File(file2,filename));
return "success";
}
批量上傳文件
@RequestMapping("/upload1")
public String upload1(MultipartFile[] file,HttpServletRequest req) throws IllegalStateException, IOException{
if (file.length==0) {
return "uploadFile";
}
for (MultipartFile multipartFile : file) {
String filename = multipartFile.getOriginalFilename();
String realPath = req.getServletContext().getRealPath("/team");
File file2 = new File(realPath);
if (!file2.exists()) {
file2.mkdirs();
}
multipartFile.transferTo(new File(file2,filename));
}
return "success";
}
3、編寫前端表單頁面
注意:把form表單的默認(rèn)的enctype 類型改成 enctype="multipart/form-data"
<form action="upload" method="post" enctype="multipart/form-data">
請(qǐng)上傳文件:<input type="file" name="file">
<br>
<input type="submit" value="upload">
</form>
<hr>
<form action="upload1" method="post" enctype="multipart/form-data">
請(qǐng)上傳文件:<input type="file" name="file">
<br>
請(qǐng)上傳文件:<input type="file" name="file">
<br>
<input type="submit" value="upload1">
</form>