Spring mvc 配置:
Web.xml:
<?xml version="1.0"encoding="UTF-8"?> <web-appxmlns: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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Hello-servlet.xml
(名称必须与web.xm文件中的servlet-name相同,放到web-inf下)
<?xml version="1.0"encoding="UTF-8"?> <beansxmlns="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/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:component-scanbase-package="zttc.itat.controller"/> <mvc:annotation-driven/> <!--将静态文件指定到某个特殊的文件夹中统一处理 --> <mvc:resourceslocation="/resources/" mapping="/resources/**"/> <beanname="/welcome.html"class="zttc.itat.controller.WelcomeController"></bean> <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"> <propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/> <propertyname="prefix" value="/WEB-INF/jsp/"/> <propertyname="suffix" value=".jsp"/> </bean> <!--设置multipartResolver才能完成文件上传 --> <beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="maxUploadSize" value="5000000"></property> </bean> <beanid="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <propertyname="exceptionMappings"> <props> <propkey="zttc.itat.model.UserException">error</prop> </props> </property> </bean> </beans>
UserController .java
@Controller @RequestMapping("/user") public class UserController { private Map<String, User> users = new HashMap<String, User>(); public UserController() { users.put("sdy",new User("sdy","123","宋冬野","[email protected]")); users.put("ldh",new User("ldh","123","刘德华","[email protected]")); users.put("gfc",new User("gfc","123","郭富城","[email protected]")); users.put("lm",new User("lm","123","黎明","[email protected]")); users.put("zxy",new User("zxy","123","张学友","[email protected]")); } //列表页面 @RequestMapping(value = "/users",method = RequestMethod.GET) public String list(Model model){ model.addAttribute("users", users); return "user/list"; } //添加用户页面 @RequestMapping(value = "/add",method = RequestMethod.GET) public String add(Model model){ //开启ModelDriven model.addAttribute(new User()); return "user/add"; } //添加用户 @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()){ //如果有错误直接调整到add视图 return "user/add"; } //System.out.println(attach.getName() + "," + attach.getOriginalFilename() + "," + attach.getContentType()); String realPath = req.getServletContext().getRealPath("/resources/upload"); System.out.println(realPath); for(MultipartFile attach : attachs){ if(attach.isEmpty()) continue; File f = new File(realPath + "/" + attach.getOriginalFilename()); FileUtils.copyInputStreamToFile(attach.getInputStream(), f); } users.put(user.getUsername(), user); return "redirect:users"; } @RequestMapping(value = "/{username}",method = RequestMethod.GET) public String show(@PathVariable String username, Model model){ model.addAttribute(users.get(username)); return "user/show"; } // @RequestMapping(value = "/{username}",method = RequestMethod.GET,params = "json") // @ResponseBody // public User show(@PathVariable String username){ // return users.get(username); // // } @RequestMapping(value="/{username}",method=RequestMethod.GET,params="json") @ResponseBody public User show(@PathVariable String username) { return users.get(username); } @RequestMapping(value = "/{username}/update",method = RequestMethod.GET) public String update(@PathVariable String username, Model model){ model.addAttribute(users.get(username)); return "user/update"; } @RequestMapping(value = "/{username}/update",method = RequestMethod.POST) public String update(@PathVariable String username, User user, BindingResult br){ if(br.hasErrors()){ //如果有错误直接调整到add视图 return "user/update"; } users.put(username, user); return "redirect:/user/users"; } @RequestMapping(value = "/{username}/delete",method = RequestMethod.GET) public String delete(@PathVariable String username){ users.remove(username); return "redirect:/user/users"; } @RequestMapping(value = "/login",method = RequestMethod.POST) public String login(String username, String password, HttpSession session){ if(!users.containsKey(username)){ throw new UserException("用户名不存在!"); } User user = users.get(username); if(!user.getPassword().equals(password)){ throw new UserException("密码错误!"); } session.setAttribute("user", user); return "redirect:/user/users"; } /* @ExceptionHandler(value ={UserException.class}) public String handlerException(UserException e, HttpServletRequest req){ req.setAttribute("e", e); return "error"; }*/ }
Rest风格
/user_show?id=120 /user/120 /user_delete?id=123 /user/123/delete /user_updateInput?id=123 /user/123/update /user_list /users /user/users REST的风格不等于使用了REST技术 GET,POST,PUT,DELETE topic/23/delete
使用hibernate+spring+springmvc完整的实现一个用户管理系统
dao-->service-->controller
增加分页,增加sitemesh
/** * 局部异常处理,仅仅只能处理这个控制器中的异常 */ @ExceptionHandler(value={UserException.class}) public StringhandlerException(UserException e,HttpServletRequest req) { req.setAttribute("e",e); return"error"; } 全局异常处理 <bean id="exceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <propertyname="exceptionMappings"> <props> <propkey="zttc.itat.model.UserException">error</prop> </props> </property> </bean>
<!-- 将静态文件指定到某个特殊的文件夹中统一处理--> <mvc:resourceslocation="/resources/" mapping="/resources/**"/>
Spring mvc 文文件上传
1,UserController.java
//在具体添加用户时,是post请求,就访问以下代码 @RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Validated Useruser,BindingResult br,@RequestParam("attachs")MultipartFile[]attachs,HttpServletRequest req) throws IOException {//一定要紧跟Validate之后写验证结果类 if(br.hasErrors()){ //如果有错误直接跳转到add视图 return"user/add"; } Stringrealpath =req.getSession().getServletContext().getRealPath("/resources/upload"); System.out.println(realpath); for(MultipartFileattach:attachs) { if(attach.isEmpty())continue; Filef = new File(realpath+"/"+attach.getOriginalFilename()); FileUtils.copyInputStreamToFile(attach.getInputStream(),f); } users.put(user.getUsername(),user); return"redirect:/user/users"; }
2,Hello-servlet.xml
<!-- 设置multipartResolver才能完成文件上传--> <bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="maxUploadSize" value="5000000"></property> </bean>
3,jsp
<!-- 此时没有写action,直接提交会提交给/add--> <sf:form method="post"modelAttribute="user" enctype="multipart/form-data"> Username:<sf:inputpath="username"/><sf:errorspath="username"/><br/> Password:<sf:passwordpath="password"/><sf:errorspath="password"/><br/> Nickname:<sf:inputpath="nickname"/><br/> Email:<sf:inputpath="email"/><sf:errors path="email"/><br/> Attach:<inputtype="file" name="attachs"/><br/> <input type="file"name="attachs"/><br/> <inputtype="file" name="attachs"/><br/> <inputtype="submit" value="添加用户"/> </sf:form>
Sitemesh:
步骤:
1, 定义相应的模板文件(main.jsp)
2, 编写装饰器文件,说明哪些页面要引入模板
decorators.xml:
<?xmlversion="1.0" encoding="UTF-8"?> <decoratorsdefaultdir="/WEB-INF/decorators"> <!-- Any urls that are excluded willnever be decorated by Sitemesh --> <excludes> <pattern>/exclude.jsp</pattern> <pattern>/exclude/*</pattern> </excludes> <decorator name="main"page="main.jsp"> <pattern>/*</pattern> </decorator> </decorators>
3, 在web.xml中开启sitemesh的过滤器
<filter> <filter-name>sitemesh</filter-name> <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Spring mvc总结:
1,在xml中配置DispatcherServlet
2,在web-inf下配置:xxx-servlet.xml
3,异常处理分局部异常处理(handlerException方法),和全局异常处理(配置xxx-servlet:SimpleMappingExceptionResolver)
异常处理(handlerException方法示例: /** * 局部异常处理,仅仅只能处理这个控制器中的异常 */ @ExceptionHandler(value={UserException.class}) public StringhandlerException(UserException e,HttpServletRequest req) { req.setAttribute("e",e); return"error"; } 全局异常处理示例: <bean id="exceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <propertyname="exceptionMappings"> <props> <propkey="zttc.itat.model.UserException">error</prop> </props> </property> </bean>
4,页面传值到Controller可以用方法的参数直接接收,或者用@PathVariable接收:
@RequestMapping(value = "/{id}",method = RequestMethod.GET) public Stringshow(@PathVariable int id, Model model){}
5,从Controller传值到页面可以从方法参数注入session,request,或者用Model,ModelMap
6,上传文件可以直接在方法参数中加:
@RequestParam("attach")MultipartFile //上传一个文件,file input的名称为attach @RequestParam("attachs")MultipartFile[] //上传一组文件,file input的名称都为attachs
Spring mvc上传文件示例:
@RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Validated Useruser,BindingResult br,@RequestParam("attachs")MultipartFile[]attachs,HttpServletRequest req) throws IOException {//一定要紧跟Validate之后写验证结果类 if(br.hasErrors()){ //如果有错误直接跳转到add视图 return"user/add"; } Stringrealpath =req.getSession().getServletContext().getRealPath("/resources/upload"); System.out.println(realpath); for(MultipartFileattach:attachs) { if(attach.isEmpty())continue; Filef = new File(realpath+"/"+attach.getOriginalFilename()); FileUtils.copyInputStreamToFile(attach.getInputStream(),f); } users.put(user.getUsername(),user); return"redirect:/user/users"; }
7,spring mvc方法返回json对象示例:
导入json包:jackson-all-1.9.4.jar
@RequestMapping(value="/{username}",method=RequestMethod.GET,params="json") @ResponseBody public User show(@PathVariable Stringusername) { returnusers.get(username); }
时间: 2024-10-15 03:32:46