javascript
Spring MVC 基础
Spring MVC 項目案件見附件
導包
配置web.xml啟動Spring MVC
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
創建一個以web.xml配置的springMVC servlet名稱的文件如:spring-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="com.springmvc.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
rest風格傳參,注入@RequestParam的參數,參數就是地址的一部分,是必需的,如果沒有就找404
@RequestMapping({"/hi","/"})
public String hello(@RequestParam("userName") String userName){
System.out.println(userName);
return "hi";
}
1.使用Map
把數據帶回view
@RequestMapping({ "/hi", "/" })
public String hello(@RequestParam("userName") String userName,
Map<String, Object> context) {
System.out.println(userName);
context.put("userName", userName);
return "hi";
}
2.使用Model
@RequestMapping({ "/hi", "/" })
public String hello(String userName,
Model model) {
System.out.println(userName);
model.addAttribute("userName", userName);
return "hi";
}
<body>
hello ${userName}
</body>
?
實例一個user到創建頁面
方式1
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute(new User());
return "user/add";
}
方式2
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(@ModelAttribute("user") User user) {
return "user/add";
}
//服務器端驗證,可以使用JSR 303 - Bean Validation
1.在bean類里需要驗證的字段,使用相應的注解
public class User {
private String userName;
private String password;
private String nikeName;
private String email;
public User(){}
public User(String userName, String password, String nikeName, String email) {
this.userName = userName;
this.password = password;
this.nikeName = nikeName;
this.email = email;
}
@NotBlank(message="用戶不能為空")
public String getUserName() {
return userName;
}
}
2.controller難度的參數加@Validated注解,后面一定要跟著BindingResult
@RequestMapping(value = "/{userName}/update", method = RequestMethod.POST)
public String update(@PathVariable String userName, @Validated User user,
BindingResult br) {
if (br.hasErrors()) {
return "user/update";
}
users.put(userName, user);
return "redirect:/user/users";
}
3.spring-servlet.xml
啟用MVC注解<mvc:annotation-driven />
異常處理,可以使用局部處理,還有全局處理異常
public class UserException extends RuntimeException {
...
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String userName, String password, HttpSession session) {
if (!users.containsKey(userName)) {
throw new UserException("用戶名不存在!");
}
User u = users.get(userName);
if (!u.getPassword().equals(password)) {
throw new UserException("用戶密碼不正確!");
}
session.setAttribute("loginUser", u);
return "redirect:/user/users";
}
1.局部異常處理
/**
* 局部異常處理
*/
// @ExceptionHandler(value={UserException.class})
// public String handlerException(UserException e,HttpServletRequest req){
// req.setAttribute("e", e);
// return "error";
// }
2.全局異常處理
<!-- 全局異常處理 -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.springmvc.model.UserException">error</prop>
</props>
</property>
</bean>
單文件上傳
<body>
<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">
userName:<sf:input path="userName"/><sf:errors path="userName"/><br />
password:<sf:input path="password"/><sf:errors path="password"/><br />
nikeName:<sf:input path="nikeName"/><br />
email:<sf:input path="email"/><br />
attach:<input type="file" name="attach" />
<input type="submit" value="提交" />
</sf:form>
</body>
spring-servlet.xml
<!-- 設置MultipartResolver才能完成上傳文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"></property>
</bean>
controller
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@Validated User user, BindingResult br,
MultipartFile attach, HttpServletRequest req) throws IOException {
if (br.hasErrors()) {
return "user/add";
}
String path = req.getSession().getServletContext()
.getRealPath("/resources/upload");
File file = new File(path + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), file);
System.out.println(path);
//
// System.out.println(attach.getName() + ","
// + attach.getOriginalFilename() + "," + attach.getContentType());
users.put(user.getUserName(), user);
return "redirect:/user/users";
}
多文件上傳
attach:<input type="file" name="attachs" />
attach:<input type="file" name="attachs" />
attach:<input type="file" name="attachs" />
attach:<input type="file" name="attachs" />
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@Validated User user, BindingResult br,
@RequestParam("attachs") MultipartFile[] attachs,
HttpServletRequest req) throws IOException {
if (br.hasErrors()) {
return "user/add";
}
String path = req.getSession().getServletContext()
.getRealPath("/resources/upload");
for (MultipartFile attach : attachs) {
if(attach.isEmpty()) continue;
File file = new File(path + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), file);
}
System.out.println(path);
//
// System.out.println(attach.getName() + ","
// + attach.getOriginalFilename() + "," + attach.getContentType());
users.put(user.getUserName(), user);
return "redirect:/user/users";
}
返回json數據 :http://localhost:8080/SpringMVC/user/sdy?json
@RequestMapping(value = "/{userName}", method = RequestMethod.GET,params="json")
@ResponseBody
public User show(@PathVariable String userName) {
return users.get(userName);
}
轉載于:https://www.cnblogs.com/Donie/p/4011552.html
總結
以上是生活随笔為你收集整理的Spring MVC 基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql优化点整理
- 下一篇: 快速上手seajs——简单易用Seajs