孔浩Spring mvc 笔记

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

孔浩Spring mvc 笔记的相关文章

Spring Mvc笔记

Spring Mvc工作流程与模块功能 Spring Web MVC DispatcherServlet 的请求处理的工作流程如下图所示: 工作流程 (1)收到一个 HTTP 请求后, DispatcherServlet 根据HandlerMapping来选择并且调用适当的控制器 . (2)控制器接受请求,并基于使用的 GET 或 POST 方法来调用适当的 service 方法.Service 方法将设置基于定义的业务逻辑的模型数据,并返回视图名称到 DispatcherServlet 中.

Spring Mvc 笔记二之异常和文件上传

spring mvc的异常与文件上传 1.异常: spring注解版的异常有局部异常和全局异常                1.局部异常对单个controller有效;(在controller类写一个处理异常的方法) @ExceptionHandler(value={UserException.class}) public String handlerExceptionTest(UserException e ,HttpServletRequest request){ request.setA

Spring MVC 笔记及简单了解

1.Springmvc是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的. 1.1  Springmvc 架构图 1.DispacherServlet前端控制器 负责用户请求和响应,是一个中央控制器(调度),调用HandlerMapping查找Ha

Spring MVC笔记(三) Spring MVC表单处理

创建动态WEB工程 FormHandling,并添加SpringMVC相关jar包(同Hello world示例一致),添加DispatcherServlet配置,如下: web.xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http

Spring MVC笔记(七) springMVC文件上传

创建springMVC工程 SpringMVCFileUpload,导入springMVC相关jar以及commons-io.jar.commons-fileupload.jar: 创建springMVC默认配置文件 SpringMVCFileUpload-servlet.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework

Spring MVC笔记(八) 控制器类名称处理映射

ControllerClassNameHandlerMapping类是基于约定的处理程序映射类,它将URL请求映射到配置中提到的控制器的名称.这个类接受控制器名称并将其转换为带有前导"/"的小写形式. 例如HelloController映射到URL: "/hello*". 创建springMVC工程: ControllerNameHandlerMapping-servlet.xml配置如下: <?xml version="1.0" enco

Spring MVC 学习笔记(二):@RequestMapping用法详解

一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置 <servlet>     <servlet-name>servletName</servlet-name>     <servlet-class>ServletClass</servlet-class> </servlet>

[Spring MVC]学习笔记--DispatcherServlet

在上一篇我们介绍了Servlet,这一篇主要来看一下MVC中用到的DispatcherServlet(继承自HttpServlet). 1. DispatcherServlet在web.xml中被声明. <web-app> <servlet> <servlet-name>example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet&l

Spring MVC学习笔记(一)--------准备篇

这一系列笔记将带你一步一步的进入Spring MVC,高手勿喷. 首先你得安装以下的工具: JDK,虽然JDK8已经发布了一段时间了,但是由于我们并不会使用到里面的新特性,所以JDK6以上版本皆可以(需加入到PATH环境变量中): Servlet Container,为了能运行WEB应用程序,因此需要一个Web Container,这里我们建议Tomcat即可: IDE,一个好的IDE不仅能提高你开发的效率,还能降低你学习的成本,我们选择的是IntelliJ: 构建工具,推荐使用Gradle,它