SpringMVC

SpringMVC:

<packaging>war</packaging>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <path>/</path>
                <port>9005</port>
            </configuration>
        </plugin>
    </plugins>
</build>

web.xml:

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>springmvc</servlet-name>
    <!--DispatcherServlet:前端控制器-->
    <!--HandlerMapping:处理器映射器-->
    <!--Handler:处理器-->
    <!--HandlAdapter:处理器适配器-->
    <!--ViewResolver:视图解析器-->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>

<!--除了jsp的所有请求-->
    <url-pattern>/</url-pattern>
</servlet-mapping>

springmvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 配置controller扫描包 -->
    <context:component-scan base-package="com.fly.controller"/>
    <!--<!– 配置处理器映射器 –>-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>-->
    <!--<!– 配置处理器适配器 –>-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>-->

    <!--注解驱动 替代注解处理器和适配器的配置
    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
    -->
    <mvc:annotation-driven/>
    <!-- 静态资源 -->
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/"/>
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

ItemController:

@Controller
public class ItemController {
    @RequestMapping("/index.action")
    public ModelAndView queryItemList(){
        List<Item> list = new ArrayList<Item>();
        list.add(new Item(1,"aaa",12,new Date()));
        list.add(new Item(2,"bbb",12,new Date()));
        list.add(new Item(3,"ccc",12,new Date()));
        list.add(new Item(4,"ddd",12,new Date()));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
        // 设置视图jsp,需要设置视图的物理地址
//        modelAndView.setViewName("/index.jsp");
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>index</title>
</head>
<body>
<table>
    <c:forEach items="${itemList}" var="item">
        <tr>
            <td>${item.name}</td>
            <td>${item.price}</td>
            <td><fmt:formatDate value="${item.createtime}" pattern="yy-MM-dd HH:mm:ss"/> </td>
        </tr>
    </c:forEach>
</table>


</body>
</html>

补充:

@Controller
@SessionAttributes("session3")//SpringMVC 就会自动将 @SessionAttributes 定义的属性注入到 ModelMap 对象
//如果方法体没有标注@SessionAttributes("session3"),那么scope为request,如果标注了,那么scope为session
//不去调用 SessionStatus 的 setComplete() 方法,这个对象就会一直保留在 Session 中
public class TestController {
    /**
     * 默认保证参数名称和请求中传递的参数名相同
     * //@RequestParam(required=true) 强制要求必须有某个参数
     */
    @RequestMapping("/demo1")
    public String demo(@RequestParam(value = "name",defaultValue = "无名")String name1,@RequestParam(value = "age",defaultValue = "0")int age1){
        System.out.println("demo:"+name1+" "+age1);
        return "success";
    }

    /**
     * 多个同名参数情况
     */
    @RequestMapping("/demo2")
    public String demo2(@RequestParam("hover") List<String> list){
        System.out.println(list);
        return "success";
    }
    @RequestMapping("demo3/{id}/{name}")
    public String demo3(@PathVariable String name,@PathVariable("id") int age){
        System.out.println(name +" "+age);
        return "success";
    }
    @RequestMapping("demo4")
    @ResponseBody
    public Item demo4(){
        Item item = new Item();
        item.setName("张三");
        item.setPrice(12);
        item.setCreatetime(new Date());
        return item;
    }
    @RequestMapping(value = "demo5",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String demo5(){
        return "成功";
    }
    //作用域传值
    @RequestMapping("/demo6")
    public String demo6(HttpServletRequest request, HttpSession session){
        //request作用域
        request.setAttribute("req","req的值");
        //session作用域
        request.getSession().setAttribute("session1","session1的值");
        session.setAttribute("session2","session2的值");
        //application作用域
        request.getServletContext().setAttribute("application","application的值");
        return "demo6";
    }

    /**
     * request 作用域中其他实现
     */
    //使用map
    @RequestMapping(value = "/demo61")
    public String demo61(Map<String,Object>map){
        //spring 会对 map 集合通过 BindingAwareModelMap 进行实例化
        System.out.println(map.getClass());
        map.put("map","map的值");
        return "demo6";
    }
    //使用Model 接口
    @RequestMapping(value = "/demo62")
    public String demo62(Model model){
        model.addAttribute("model","model的值");
        return "demo6";
    }
    //使用ModelAndView 类
    @RequestMapping(value = "/demo63")
    public ModelAndView demo63(){
        ModelAndView modelAndView = new ModelAndView("demo6");
        modelAndView.addObject("modelAndView","modelAndView的值");
        return modelAndView;
    }
    //获取sessionScope的值
    @RequestMapping(value = "/demo7")
    public String demo7(@SessionAttribute String session1){
        System.out.println(session1);
        return "demo6";
    }
    @RequestMapping(value = "/demo77")
    public String demo77(){
        return "demo6";
    }
    //request或session存值
    //名称随意
    @ModelAttribute("session3")
    public Item addString(){
        Item item = new Item();
//        item.setId(111);
        return item;
    }
    //参数session3的值来源于addString()方法中的model属性
    @RequestMapping(value = "/demo71")
    public String demo71(@ModelAttribute("session3") Item item){
        item.setName("session3Name");
        return "success";
    }
    @RequestMapping(value = "/demo72")
    public String demo72(ModelMap modelMap, SessionStatus sessionStatus){
        Item item = (Item) modelMap.get("session3");
        if (item!=null){
            sessionStatus.setComplete();
        }
        return "success";
    }
}

demo6.jsp

<body>
<h4>demo6</h4>
req:${requestScope.req} <br>
session1:${sessionScope.session1} <br>
session2:${sessionScope.session2} <br>
application:${applicationScope.application} <br>
<hr>
map:${requestScope.map} <br>
model:${requestScope.model} <br>
modelAndView:${requestScope.modelAndView} <br>
session3:${sessionScope.session3} <br>
</body>

Springmvc整合mybatis:

<packaging>war</packaging>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    <!--aop-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <path>/</path>
                <port>9006</port>
            </configuration>
        </plugin>
    </plugins>
    <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 配置spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext*.xml</param-value>
    </context-param>

    <!-- 使用监听器加载Spring配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--<url-pattern>*.action</url-pattern>-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--解决post乱码问题-->
    <!--
    对于get请求中文参数出现乱码解决方法有两个:
    修改tomcat配置文件添加编码与工程编码一致,如下:
    <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

    另外一种方法对参数进行重新编码:
    String userName new
    String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
    ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
    -->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--数据库连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>

<property name="typeAliasesPackage" value="com.fly.pojo"/>
        <!-- 加载mybatis的全局配置文件 -->
      <!--<property name="configLocation" value="classpath:SqlMapConfig.xml"/>-->

    </bean>
    <!-- 配置Mapper扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.fly.mapper"/>
    </bean>

    <context:component-scan base-package="com.fly.service.impl"/>
    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.fly.service.*.*(..))"/>
    </aop:config>
</beans>

springmvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 配置controller扫描包 -->
    <context:component-scan base-package="com.fly.controller"/>

    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--转换器配置-->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.fly.Converter.DataConverter"/>
            </set>
        </property>
    </bean>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/"/>
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

SqlMapConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.fly.pojo"/>
    </typeAliases>
</configuration>

ItemMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fly.mapper.ItemMapper">
    <select id="queryItemList" resultType="item">
        select * from items
    </select>
    <select id="queryItemById" parameterType="int" resultType="item">
        select * from items where id=#{id}
    </select>
</mapper>

ItemServiceImpl:

@Service
public class ItemServiceImpl implements ItemService {

//    @Autowired
    @Resource
    private ItemMapper itemMapper;

    public List<Item> queryItemList() {
        return itemMapper.queryItemList();
    }

    public Item queryItemById(int id) {
        return itemMapper.queryItemById(id);
    }
}

ItemController:

@Controller
public class ItemController {
//    @Autowired
    @Resource(name = "itemServiceImpl")
    private ItemService itemService;

    @RequestMapping("/index.action")
    public String queryItemList(Model model){
        System.out.println("index...");
        List<Item> list = itemService.queryItemList();
        model.addAttribute("itemList",list);
        return "index";
    }
    @RequestMapping("/index1.action")
    public String queryItemById(HttpServletRequest request,Model model){
        int id = Integer.valueOf(request.getParameter("id"));
        Item item = itemService.queryItemById(id);
        model.addAttribute("item",item);
        return "index";
    }
    @RequestMapping("/index2.action")
    public String queryItemById2(int id,Model model){
        Item item = itemService.queryItemById(id);
        model.addAttribute("item",item);
        return "index";
    }
}

DataConverter:

/**
 * 自定义时间转换器
 * S:source,需要转换的源的类型
 * T:target,需要转换的目标类型
 */
public class DataConverter implements Converter<String, Date> {
    public Date convert(String s) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(s);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

返回:

Controller方法形参上可以定义requestresponse,使用requestresponse指定响应结果:

1、使用request转发页面,如下:

request.getRequestDispatcher("页面路径").forward(request, response);

request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);

 

2、可以通过response页面重定向:

response.sendRedirect("url")

response.sendRedirect("/springmvc-web2/itemEdit.action");

 

3、可以通过response指定响应结果,例如响应json数据如下:

response.getWriter().print("{\"abc\":123}");

Redirect重定向

return "redirect:/itemEdit.action?itemId=" + item.getId();

forward转发

return "forward: /itemEdit.action";

 

异常处理器:

public class MyException extends Exception{
    private String message;

    public MyException() {
    }

    public MyException(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

 

public class CustomHandleException implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        // 定义异常信息
        String msg;
        // 判断异常类型
        if (e instanceof MyException){
            msg = e.getMessage();
        }else {
            // 从堆栈中获取异常信息
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            e.printStackTrace(printWriter);
            msg = writer.toString();
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",msg);
        modelAndView.setViewName("error");
        return modelAndView;

    }
}

springmvc.xml

<!--配置全局异常处理器-->
<bean id="customHandleException" class="com.fly.exception.CustomHandleException"/>

上传:

<!--上传-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

springmvc.xml:

<!--异常解析器
文件上传大于设置值的异常处理
-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error</prop>
        </props>
    </property>
</bean>
<!--配置全局异常处理器-->
<!--<bean id="customHandleException" class="com.fly.exception.CustomHandleException"/>-->
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置文件上传大小 -->
    <property name="maxUploadSize" value="50" />
</bean>

UpdateController:

@Controller
public class UpdateController {
    @RequestMapping("/update")
    public String update(MultipartFile picFile) throws IOException {
        String s = UUID.randomUUID().toString().replace("-","");
        String originalFilename = picFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
         //方式一
//        picFile.transferTo(new File("c:/upload/"+s+substring));
        //方式二
        FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File("c:/upload/"+s+substring));

        System.out.println("上传。。。");
        return "redirect:success";
    }
    @RequestMapping("/success")
    public String success(){
        return "success";
    }
}

update.jsp:

<h4>文件上传</h4>
<form method="post" action="/update" enctype="multipart/form-data">
    <input type="file" name="picFile">
    <input type="submit">
</form>

文件下载:

@Controller
public class DownLoadController {
    @RequestMapping("/download")
    public void download(String file,HttpServletResponse res, HttpServletRequest req) throws IOException {
        //设置响应流中文件进行
        res.setHeader("Content-Disposition","attachment;filename="+file);
        ServletOutputStream os = res.getOutputStream();
        //webapp的files目录下
        byte[] bytes = FileUtils.readFileToByteArray(new File(req.getServletContext().getRealPath("files"), file));
        os.write(bytes);
        os.flush();
        os.close();
    }
}

Json:

springMVC支持json,必须加入json的处理jar

<!--json-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>

/**

 * 测试json的交互

 */

@RequestMapping("testJson")

// @ResponseBody

public @ResponseBody Item testJson(@RequestBody Item item) {

return item;

}

 

/**

 * 使用RESTful风格开发接口

 */

@RequestMapping("item/{id}")

@ResponseBody

public Item queryItemById(@PathVariable("id") Integer ids) {

Item item = this.itemService.queryItemById(ids);

return item;

}

如果@RequestMapping中表示为"item/{id}"id和形参名称一致,@PathVariable不用指定名称。如果不一致,例如"item/{ItemId}"则需要指定名称@PathVariable("itemId")

拦截器:

MyHandlerInterceptor:

/**
 * SpringMVC 拦截器和 Filter 的区别:
 * 拦截器只能拦截 Controller
 * Filter 可以拦截任何请求
 */

public class MyHandlerInterceptor implements HandlerInterceptor {
    // Controller执行前调用此方法
    // 返回true表示继续执行,返回false中止执行
    // 这里可以加入登录校验、权限拦截等
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
//        return false;
        return true;
    }
    // controller执行后但未返回视图前调用此方法
    // 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示

//敏感词过滤
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }
    // controller执行后且视图返回后调用此方法
    // 这里可得到执行controller时的异常信息
    // 这里可记录操作日志
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

springmvc.xml:

<!--拦截器配置-->
<mvc:interceptors>
    <mvc:interceptor>
        <!-- 所有的请求都进入拦截器 -->
        <mvc:mapping path="/**"/>
        <!-- 配置具体的拦截器 -->
        <bean class="com.fly.interceptor.MyHandlerInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

拦截器栈:

拦截器栈
多个拦截器同时生效时,组成了拦截器栈
顺序:先进后出.
执行顺序和在 springmvc.xml 中配置顺序有关
设置先配置拦截器 A 在配置拦截器 B 执行顺序为
preHandle(A) --> preHandle(B) --> 控制器方法 --> postHandle(B) --> postHanle(A) --> JSP --> afterCompletion(B) --> afterCompletion(A)

springMVC运行原理:

SpringMVC 运行原理:
如果在 web.xml 中设置 DispatcherServlet <url-pattern>/,
当用户 , , DispatcherServlet.
DispatcherServlet HandlerMapping DefaultAnnotationHandlerMapping URL,
HandlerAdatper AnnotationMethodHandlerAdapter Controller 中的 HandlerMethod.
HandlerMethod 执行完成后会返回View,会被 ViewResovler 进行视图解析,
解析后调用 jsp 对应的.class 文件并运行,最终把运行.class 文件的结果响应给客户端.

 

posted @ 2018-12-24 13:11  fly_bk  阅读(145)  评论(0)    收藏  举报