zl程序教程

您现在的位置是:首页 >  其他

当前栏目

最后的大爆发五万字总结SpringMVC教程——三部曲封神之作(建议收藏)

2023-04-18 13:05:38 时间

文章目录

前言

上回分别为各位分享了《六万字最全总结Java数据库编程MyBatis》《爆肝万字!一文最全总结之Spring从入门到入土》。 没有学过的同学,建议先学MyBatis,后学Spring,这次在此基础上我们来学习SpringMVC,此篇学完再无后端!

相关资料:

已上传到Gitee,欢迎start!!

1. Spring MVC 概述

2.1 Spring MVC是什么

​ Spring web mvc是表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来:

1.0 Spring MVC处理流程

l 1)核心控制器:处理特定请求。(例如:以*.action为后缀)

名称:DispatcherServlet

配置:是一个servlet,需要在web.xml中配置。

XML:需要确定核心XML配置文件的位置

l 2)核心XML配置文件:确定Controller位置、确定JSP页面位置

名称:springmvc.xml

l 3)控制器:开发人员编写的主要内容

名称:*Controller

l 流程示意图

2. 入门案例:查询详情 ( xml)

3.1 需求说明

在index.html中点击 Hello SpringMVC 超链接,在 show01 .jsp 页面显示信息。

2.1 思路分析

整体思路:

跟HelloServlet入门案例几乎相同 .

服务器设置一个Controller,相当于之前的Servlet,可以接收请求,把请求在转发给jsp页面.

这里的区别就是需要设置web.xml和springmvc.xml两个配置文件,前者是用来配置核心控制器,后者是用来扫描我们自己书写的Controller的.

书写步骤:

1.拷贝pom文件,SpringMVC.xml文件和web.xml配置文件核心代码.

2.创建HelloController和show01.jsp

项目结构如下:

2.2 实现步骤

2.2.1 拷贝配置文件相关代码

获取pom文件:

参见当前文档末尾的附录

获取springmvc.xml文件

代码如下直接拷贝

获取Web.xml代码配置如下:

  Archetype Created Web Application


    
  
    springmvc
    org.springframework.web.servlet.DispatcherServlet  
    
      contextConfigLocation
      classpath:springmvc.xml  
    
  
  
    springmvc
    *.action  

2.2.2 创建java类和jsp文件

创建HelloController.java 
package com.Maynor.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller  
public class HelloController {

   @RequestMapping("/hello.action")  
   public String show(Model model){

      model.addAttribute("data", "嘿嘿嘿"); 

      return "/WEB-INF/show01.jsp"; 
   }

}

Show01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title



你好啊 老弟儿 ${data}




Index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


Hello World!

入门案例

测试结果: index.jsp页面

点击入门案例结果:

3. 入门查询:查询所有(无xml)

3.2 需求说明

该需求跟上一个入门案例需求完全相同.

在index.html中点击 Hello SpringMVC 超链接,在 show01 .jsp 页面显示信息。

区别在于实现的时候:

使用 WebInitializer类代替web.xml

使用MVCConfig代替springmvc.xml

3.1 思路分析

书写步骤:

1.拷贝pom文件,书写MVCConfig和WebInitializer类.

2.创建HelloController和show01.jsp

项目结构如下:

3.2 步骤实现

3.2.1 拷贝pom文件,创建MVCConfig和WebInitializer类

Pom文件,沿用上一个案例.即附录

MVCConfig类代码如下:

package com.Maynor.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.Maynor.controller")  
public class MVCConfig {
}

传统Web项目中,程序的入口是web.xml文件。

​ 在spring4中提供WebApplicationInitializer接口,表示服务器启动初始化。也就是说接口实现类中编写的内容,就是web.xml文件中配置的内容。

类或方法

描述

AnnotationConfigWebApplicationContext

WEB环境下spring工厂

servletContext.addFilter(name , Class)

添加过滤器,等效

servletContext.addServlet(name , Class)

添加servlet,等效

过滤器相关方法 ServletRegistration.Dynamic

描述

addMapping(urlPatterns)

追加过滤路径

setLoadOnStartup(int)

设置启动顺序

WebInitializer类代码如下:

package com.Maynor.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
   @Override
   public void onStartup(ServletContext servletContext) throws ServletException {

      //1.初始化spring容器
      AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
      applicationContext.register(MVCConfig.class);  
      applicationContext.setServletContext(servletContext);
      //2.设置核心控制器
      ServletRegistration.Dynamic springMVCServlet = servletContext.addServlet("springmvc", new DispatcherServlet(applicationContext)); 
      springMVCServlet.addMapping("*.action"); 
      springMVCServlet.setLoadOnStartup(2);

   }
}

3.2.2 创建HelloController和show01.jsp

HelloController代码:
package com.Maynor.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

   @RequestMapping(path = "/hello.action")
   public String show(Model model){

      model.addAttribute("data", "呵呵呵");
      
      return "/WEB-INF/show01.jsp";

   }


}
Show01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title



    来了 老弟儿 ${data}

测试结果:

练习:

查询所有. 希望得到如下结果:

参考代码:

l 编写JavaBean用于封装数据

public class Item {
	private String name;	//名称
	private Float price;	//价格
	private String detail;	//详情

l 编写业务控制器Controller

@Controller
@RequestMapping("/user")
public class HelloController {

    @RequestMapping("showInfo")
    public String showInfo(Model model){
        System.out.println("展示页面");
        //1 模拟数据
        List list = new ArrayList();
        list.add(new Item("联想笔记本", 6999f, "ThinkPad T430 联想笔记本电脑!"));
        list.add(new Item("苹果手机", 8800f, "iphone X 苹果手机!"));

        //设置数据
        model.addAttribute("list", list);
        return "/showInfo.jsp";
    }
}

l 展示数据

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 86153
  Date: 2019/6/14
  Time: 0:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title



        
    
        名称
        价格
        描述
    
    
            ${item.name }
            ${item.price }
            ${item.detail }

配置类

*MVCConfig
@Configuration
@ComponentScan("com.Maynor.controller")
public class MVCConfiguration {

}


WebInitalizer
public class WebInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		//1 初始化spring容器
		AnnotationConfigWebApplicationContext appliation = new AnnotationConfigWebApplicationContext();
		appliation.register(MVCConfiguration.class);
		appliation.setServletContext(servletContext);
		
		//3 前端控制器
		ServletRegistration.Dynamic springMvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(appliation));  
		springMvcServlet.addMapping("*.action");
		springMvcServlet.setLoadOnStartup(2);

	}

}

测试:

l 步骤2:启动,并访问

http://localhost:8080/s02/user/showInfo.action

4. SSM整合:改造UMS

需求:

改造ums 实现 查询所有用户.

示意图如下:

思路:

  1. 环境搭建:拷贝pom,资源文件和配置文件,初始化数据库和表,创建javaBean
  2. 编写功能:dao,Service,Controller
  3. 编写配置类:SpringConfig,MyBatisConfig,SpringMvcConfig,Web启动类.
  4. 测试

项目最终结构如下:

4.1 搭建环境

4.0.1 创建项目、 拷贝pom文件

<org.springframework.version>4.2.4.RELEASEorg.springframework.version>

<dependencies>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-beansartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-coreartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-expressionartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-context-supportartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aopartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aspectsartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-instrumentartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-messagingartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-ormartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-oxmartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jmsartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-txartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-websocketartifactId>
    <version>${org.springframework.version}version>
  dependency>
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webartifactId>
    <version>${org.springframework.version}version>
  dependency>


  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvc-portletartifactId>
    <version>${org.springframework.version}version>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>${org.springframework.version}version>
  dependency>
  

  
  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>${org.springframework.version}version>
  dependency>

  
  


  <dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
  dependency>
  <dependency>
    <groupId>tk.mybatisgroupId>
    <artifactId>mapperartifactId>
    <version>3.5.2version>
  dependency>
  <dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelperartifactId>
    <version>3.7.5version>
  dependency>
  <dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.4.5version>
  dependency>

  <dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.47version>
  dependency>
  <dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>1.3.2version>
  dependency>
  <dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.10version>
  dependency>

  <dependency>
    <groupId>javax.servletgroupId>
    <artifactId>javax.servlet-apiartifactId>
    <version>3.1.0version>
    <scope>providedscope>
  dependency>


  <dependency>
    <groupId>jstlgroupId>
    <artifactId>jstlartifactId>
    <version>1.2version>
  dependency>


  <dependency>
    <groupId>javax.servlet.jspgroupId>
    <artifactId>jsp-apiartifactId>
    <version>2.1version>
    <scope>providedscope>
  dependency>
  
dependencies>



<plugin>
  <groupId>org.apache.maven.pluginsgroupId>
  <artifactId>maven-compiler-pluginartifactId>
  <version>3.2version>
  <configuration>
    <source>1.8source>
    <target>1.8target>
    <encoding>UTF-8encoding>
    <showWarnings>trueshowWarnings>
  configuration>
plugin>


<plugin>
  <groupId>org.apache.tomcat.mavengroupId>
  <artifactId>tomcat7-maven-pluginartifactId>
  <version>2.1version>
  <configuration>
    <port>8081port>
    <server>tomcat7server>
  configuration>
plugin>

4.0.2 拷贝UMS页面

4.0.3 配置文件

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/ums_db jdbc.username=root jdbc.password=1234

4.0.4 初始化数据库和表

CREATE TABLE t_user (

 uid INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,

 login_name VARCHAR(50) DEFAULT NULL,

 login_pwd VARCHAR(32) DEFAULT NULL,

 age INT(11) DEFAULT NULL,

 birthday DATE DEFAULT NULL,

 sex VARCHAR(1) DEFAULT NULL,

 education VARCHAR(50),

 telephone VARCHAR(11),

 interest VARCHAR(100),

 remark VARCHAR(200)

)
insert  into `t_user`(`uid`,`login_name`,`login_pwd`,`age`,`birthday`,`sex`,`education`,`telephone`,`interest`,`remark`) values (1,'jack','1234',18,'1996-11-11','男',NULL,NULL,NULL,NULL),(2,'rose','1234',21,'1993-11-11','女',NULL,NULL,NULL,NULL),(3,'tom','1234',23,'1996-12-24','男',NULL,NULL,NULL,NULL);

4.0.5 创建JavaBean

@Table(name="t_user")
public class User {
	@Id
	private Integer uid;
	private String loginName;
	private String loginPwd;
	private Integer age;
	private String sex;
	private String birthday;
	private String education;
	private String telephone;
	private String interest;		//爱好:对应数据库(内容:A,B,C)
	private String[] interestArr;	//爱好:对应页面表单
	private String remark;

l 爱好需要特殊处理

	public String getInterest() {
		if(interestArr != null){
			interest = Arrays.toString(interestArr);  //[A,B,C]
			interest = interest.substring(1, interest.length() - 1);	//A,B,C
		}
		return interest;
	}
	public void setInterest(String interest) {
		this.interest = interest;
		if(interest != null){
			interestArr = interest.split(", ");
		}
	}

4.1 编写功能:dao、service、web、jsp页面

4.1.1 编写mapper接口(dao)

package com.Maynor.dao;

import com.Maynor.domain.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper {
}

4.1.2 编写service接口

package com.Maynor.service;

import com.Maynor.domain.User;

import java.util.List;

public interface UserService {

   public List findAll();
   
}

4.1.3 编写service实现类

package com.Maynor.service.impl;

import com.Maynor.dao.UserMapper;
import com.Maynor.domain.User;
import com.Maynor.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import javax.annotation.Resource;
import java.util.List;

@Service(value = "userServiceImpl")
@Transactional
public class UserServiceImpl implements UserService {


   @Resource
   private UserMapper userMapper;

   @Override
   public List findAll() {

      List users = userMapper.selectAll();

      return users;
   }
}

4.1.4 编写Controller

package com.Maynor.controller;


import com.Maynor.domain.User;
import com.Maynor.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserController {

   @Autowired
   private UserService userService;

   @RequestMapping("/findAllUsers.action")
   public String findAll(Model model){

      List userList = userService.findAll();

      model.addAttribute("userList", userList);

      return "/user/list.jsp";
   }


}

4.1.5 编写jsp

List.jsp

Left.jsp

${pageContext.request.contextPath}/findAllUsers.action

4.2 编写配置类

4.2.1 spring配置类

package com.Maynor.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.sql.DataSource;

//配置类
@Configuration
//要扫描的包
@ComponentScan(basePackages = {"com.Maynor"})
//开启事务支持
@EnableTransactionManagement
//读取properties配置文件
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {

   //4.2.4 读取properties的固定代码
   @Bean
   public static PropertySourcesPlaceholderConfigurer create(){

      return new PropertySourcesPlaceholderConfigurer();
   }
   //读取数据库中的相关配置
   @Value("${jdbc.driver}")
   private String driverClass;
   @Value("${jdbc.url}")
   private String url;
   @Value("${jdbc.username}")
   private String username;
   @Value("${jdbc.password}")
   private String password;


   //设置德鲁伊连接池
   @Bean
   public DataSource dataSource(){
      DruidDataSource dataSource = new DruidDataSource();
      dataSource.setPassword(password);
      dataSource.setUsername(username);
      dataSource.setUrl(url);
      dataSource.setDriverClassName(driverClass);
      return dataSource;
   }
   //开启事务管理器
   @Bean
   @Resource
   public DataSourceTransactionManager txManager(DataSource dataSource){
      return  new DataSourceTransactionManager(dataSource);
   }
}

4.2.2 mybatis配置类

package com.Maynor.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.sql.DataSource;

//配置类
@Configuration
//要扫描的包
@ComponentScan(basePackages = {"com.Maynor"})
//开启事务支持
@EnableTransactionManagement
//读取properties配置文件
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {

   //4.2.4 读取properties的固定代码
   @Bean
   public static PropertySourcesPlaceholderConfigurer create(){

      return new PropertySourcesPlaceholderConfigurer();
   }
   //读取数据库中的相关配置
   @Value("${jdbc.driver}")
   private String driverClass;
   @Value("${jdbc.url}")
   private String url;
   @Value("${jdbc.username}")
   private String username;
   @Value("${jdbc.password}")
   private String password;


   //设置德鲁伊连接池
   @Bean
   public DataSource dataSource(){
      DruidDataSource dataSource = new DruidDataSource();
      dataSource.setPassword(password);
      dataSource.setUsername(username);
      dataSource.setUrl(url);
      dataSource.setDriverClassName(driverClass);
      return dataSource;
   }
   //开启事务管理器
   @Bean
   @Resource
   public DataSourceTransactionManager txManager(DataSource dataSource){
      return  new DataSourceTransactionManager(dataSource);
   }
}

4.2.3 spring mvc 配置类【无内容】

package com.Maynor.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//声明为配置类
@Configuration
//设置扫描 controller
@ComponentScan("com.Maynor.controller")
public class SpringMvcConfig {
}

4.2.4 web启动配置类【新内容】

​ 传统Web项目中,程序的入口是web.xml文件。

​ 在spring4中提供WebApplicationInitializer接口,表示服务器启动初始化。也就是说接口实现类中编写的内容,就是web.xml文件中配置的内容。

类或方法

描述

AnnotationConfigWebApplicationContext

WEB环境下spring工厂

servletContext.addFilter(name , Class)

添加过滤器,等效

servletContext.addServlet(name , Class)

添加servlet,等效

过滤器相关方法 ServletRegistration.Dynamic

描述

addMapping(urlPatterns)

追加过滤路径

setLoadOnStartup(int)

设置启动顺序

过滤器相关方法 FilterRegistration.Dynamic

描述

addMappingForUrlPatterns(null, isMatchAfter, urlPatterns)

追加过滤路径参数2:参数3:路径

package com.Maynor.config;


import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
   @Override
   public void onStartup(ServletContext servletContext) throws ServletException {
      //1.初始化 Spring 容器
      AnnotationConfigWebApplicationContext applicationContext  = new AnnotationConfigWebApplicationContext();
      applicationContext.register(SpringMvcConfig.class);
      applicationContext.register(SpringConfig.class);
      applicationContext.register(MybatisConfig.class);
      applicationContext.setServletContext(servletContext);

      //2.设置核心控制器
      ServletRegistration.Dynamic ds = servletContext.addServlet("springmvc", new DispatcherServlet(applicationContext));
      ds.addMapping("*.action");
      ds.setLoadOnStartup(2);


      //3 post乱码配置    
      FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
      encodingFilter.addMappingForUrlPatterns(null, true, "/*");

   }
}

4.3 测试

启动项目,点击用户管理 可以看到如下效果即可.

5. 视图 解析器

5.1 分析

5.2 修改代码

l 其他代码与“查询所有”案例相同,不同内容如下:

5.2.1 编写控制器

l 业务控制器返回“视图”名称

@Controller
@RequestMapping("/user")
public class ItemsController {
	
	@RequestMapping("/itemsList")
	public String itemsList(Model model) throws Exception {
		
		//1 模拟数据
		List list = new ArrayList();
		list.add(new Items("联想笔记本", 6999f, "ThinkPad T430 联想笔记本电脑!"));
		list.add(new Items("苹果手机", 8800f, "iphone X 苹果手机!"));
		
		//设置数据
		model.addAttribute("list", list);
		
		return "itemslist"; //"/WEB-INF/jsp/itemslist.jsp";
	}

}

5.2.2 配置视图解析器

@Configuration
@ComponentScan("com.Maynor.controller")
public class MVCConfiguration {
	@Bean
	public InternalResourceViewResolver viewResolver(){
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/jsp/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}

6. SSM整合:改造UMS(添加视图解析器)

7. 参数 绑定

7.1 简单数据类型

l 在控制器的方法中,只要有对应的参数名,spring mvc就可以自动完成参数封装。

7.1.1 支持的数据类型

l 参数类型推荐使用包装数据类型,因为基础数据类型不可以为null,此时进行访问没有设置参数,程序抛异常。

数据类型

整型:Integer、int

字符串:String

单精度:Float、float

双精度:Double、double

布尔型:Boolean、boolean

7.1.2 @RequestParam

l 如果请求参数名和方法参数名不一致时,需要使用@RequestParam标记对应关系。

l 如果类型是基本类型,此时没有参数,默认抛异常。

解决方案1:可以设置默认值。

解决方案2:可以设置成 包装类型

7.2 绑定POJO类型

JSP页面

		姓名: 

		价格: 

		
	
控制器:
@Controller
@RequestMapping("/user")
public class ItemsController {

	@RequestMapping("additems")
	public String addItems(Items items){
		System.out.println(items);
		return "itemslist";
	}
}

l 分析

l 注意:数据不能是日期,日期必须采用自定义参数绑定。

7.3 POST中文乱码

在web.xml文件中

    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
        encoding
        UTF-8
    
    
        forceEncoding
        true
    


    encodingFilter
    /*

我们采用web启动配置类的方式
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		//1 初始化spring容器
		AnnotationConfigWebApplicationContext appliation = new AnnotationConfigWebApplicationContext();
		appliation.register(MVCConfiguration.class);
		appliation.setServletContext(servletContext);
		
		//2 post乱码配置 
		FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
		encodingFilter.addMappingForUrlPatterns(null, true, "/*");
		
		//3 前端控制器
		ServletRegistration.Dynamic springMvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(appliation));  
		springMvcServlet.addMapping("*.action");
		springMvcServlet.setLoadOnStartup(2);

	}

7.4 绑定包装POJO

提供JavaBean:QueryVo
public class QueryVo {
	private Items items;

	public Items getItems() {
		return items;
	}

	public void setItems(Items items) {
		this.items = items;
	}
}
修改控制器
	@RequestMapping("findall")
	public String findAll(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		return "itemslist";
	}
JSP页面

		姓名: 

		价格: 

7.5 自定义参数绑定

​ 由于日期数据有很多种格式,所以springmvc没办法把字符串转换成日期类型(不够智能,2019/01/01这种格式可以自动转,2019-01-01这种格式就不能了)。所以需要自定义参数绑定。

JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面

		姓名: 

		价格: 

		日期: 

		
	
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

方式一:

1. 在MVCConfig类上添加@EnableWebMvc 注解

2. 在实体类上添加注解@DateTimeFormat

JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面

		姓名: 

		价格: 

		日期: 

		
	
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

7.6 绑定数组

JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面

		姓名: 

		价格: 

		日期: 

		
	
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

7.7 表单数据绑定到List

JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面

		姓名: 

		价格: 

		日期: 

		
	
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

8. @RequestMapping

8.1 多路径映射

l 同时设置多个路径

@RequestMapping(value={"/index","/index2"})
	public String index(){
		return "itemslist";
	}

http://localhost:8080/spring_mvc_day01_05/user/index.action
http://localhost:8080/spring_mvc_day01_05/user/index2.action
//都可以访问 

8.2 窄化请求路径

@RequestMapping放在类名上边,设置请求前缀

@RequestMapping放在方法名上边,设置方法对应请求路径。

完整请求:前缀 + 请求路径

8.3 请求方法限定

l 限定GET方法 @RequestMapping(method = RequestMethod.GET) l 限定POST方法 @RequestMapping(method = RequestMethod.POST) l GET和POST都可以 @RequestMapping(method={RequestMethod.GET,RequestMethod.POST})

9. Controller方法返回值

9.1 返回ModelAndView

controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。

@RequestMapping("/findById")
	public ModelAndView findById(){
		ModelAndView modelAndview = new ModelAndView();
		//设置数据
		modelAndview.addObject("id", "猜猜看");
		//设置视图
		modelAndview.setViewName("itemslist");
		return modelAndview;
	}

9.2 返回void

如果方法返回void,有3种情况:request请求转发、response重定向、给前端响应Json

请求转发
@RequestMapping("/findById2")
public void findById2(HttpServletRequest request , HttpServletResponse response) 
								throws ServletException, IOException{
	request.getRequestDispatcher("/index.jsp").forward(request, response);
}
重定向
@RequestMapping("/findById3")
public void findById3(HttpServletRequest request , HttpServletResponse response) 
								throws ServletException, IOException{
	response.sendRedirect(request.getContextPath() + "/index.jsp");
}
Json 处理
@RequestMapping("/findById4")
public void findById4(HttpServletRequest request , HttpServletResponse response)
								 throws ServletException, IOException{
	response.setCharacterEncoding("UTF-8");
	response.setContentType("application/json;charset=UTF-8");
	String jsonStr = "{"username":"jack"}";
	response.getWriter().write(jsonStr);
}

9.3 返回字符串

9.3.1 逻辑视图名

controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。

@RequestMapping(value={"/index","/index2"})
public String index(){
	return "itemslist";
}

9.3.2 Redirect重定向

​ Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中。

return "redirect:其他路径";

@RequestMapping("/update")
public String update() throws ServletException, IOException{
	return "redirect:queryItem.action";
}

9.3.3 forward转发

​ controller方法执行后继续执行另一个controller方法,如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。

return "forward:其他路径";
@RequestMapping("/updateSubmit")
public String updateSubmit() throws ServletException, IOException{
	return "forward:editItem.action";
}

10. 异常处理器

10.1 异常处理器分析

10.2 自定义异常

public class CustomException extends Exception {

	private static final long serialVersionUID = 8222256702797084775L;

	public CustomException() {
		super();
	}

	public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public CustomException(String message, Throwable cause) {
		super(message, cause);
	}

	public CustomException(String message) {
		super(message);
	}

	public CustomException(Throwable cause) {
		super(cause);
	}
	
}

10.3 异常处理器编写

public class CustomException extends Exception {

	private static final long serialVersionUID = 8222256702797084775L;

	public CustomException() {
		super();
	}

	public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public CustomException(String message, Throwable cause) {
		super(message, cause);
	}

	public CustomException(String message) {
		super(message);
	}

	public CustomException(Throwable cause) {
		super(cause);
	}
	
}

10.4 异常页面

	您的操作出现错误如下:

	${message }

10.5 测试程序

@Controller
@RequestMapping("/user")
public class ItemsController {
	
	@RequestMapping("index")
	public String index(String id) throws CustomException{
		if(id == null){
			throw new CustomException("没有id参数");
		}
		return "itemslist";
	}
}

异常演示

异常演示

11. 上传图片

11.1 单图片上传

11.1.1 JSP页面

		姓名: 

		价格: 

		图片: 

11.1.2 文件上传解析器

		姓名: 

		价格: 

		图片: 

l 使用的commons-fileupload完成上传,确定导入fileupload jar包

  commons-fileupload
  commons-fileupload
  1.2.2



  commons-io
  commons-io
  2.3

11.1.3 Controller实现

需要使用MultipartFile类型表示一个文件上传对象。

方法名

描述

String getOriginalFilename()

获得原始上传文件名

transferTo(File file)

将上传文件转换到一个指定的文件中

String getContentType()

获取文件MIME类型,如image/pjpeg、text/plain等

String getName()

获取表单中文件组件的名字

	@RequestMapping("upload")
	public String upload(String name,Double price,
@RequestParam(required=false,value="picFile") MultipartFile picFile) throws Exception{
		System.out.println("姓名:" + name);
		System.out.println("价格:" + price);
		
		String originalFileName = picFile.getOriginalFilename();
		System.out.println("上传文件名:" + originalFileName);
		//保存文件到指定的位置
		File file = new File("D:\temp", originalFileName);
		picFile.transferTo(file);
		return "itemslist";
	}

11.2 多图片上传

11.2.1 JSP页面

		姓名: 

		价格: 

		图片: 

		图片: 

11.2.2 JavaBean

public class QueryVo {
	private String name;
	private Double price;
	public List picFile;

	//getter and setter

11.2.3 Controller实现

@RequestMapping("upload2")
	public String upload2(QueryVo queryVo) throws Exception{
		System.out.println("姓名:" + queryVo.getName());
		System.out.println("价格:" + queryVo.getPrice());
		
		System.out.println("上传文件个数:" + queryVo.getPicFile().size());
		for(MultipartFile picFile : queryVo.getPicFile()){
			String originalFileName = picFile.getOriginalFilename();
			System.out.println("上传文件名:" + originalFileName);
			//保存文件到指定的位置
			File file = new File("D:\temp", originalFileName);
			picFile.transferTo(file);
		}
		return "itemslist";
	}

12. JSON数据交互

12.1 概述

@RequestBody:将json、xml 等内容 转换 成Java对象。

@ResponseBody:将Java对象 转换 成 json、xml等内容。

12.2 前端发送ajax请求,后端获取json数据

需求:

前端发送ajax请求,后端通过VO自动获取数据打印

  前端代码:
   <%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title

    
    
        $(function () {

            var url = "${pageContext.request.contextPath}/tJson.action";
            var params={
                "name":"zhangsan",
                "price":"123"
            }
            var callBack=function (rel) {
                //后端有返回结果 就会弹窗显示, 没有就不会弹窗
                alert(rel.name+" "+rel.price)
            }
            //发射
            $.post(url,params,callBack,"json")

        })
    


  页面加载完毕就发射ajax 


后端代码: 
 Qvo 
  public class QVo {

    private String name;
    private Double price;
....
}

Controller
@RequestMapping("/tJson.action")
public String testJson(QVo qvo){
    //查看前端传递的json 自动转化的VO结果
    System.out.println(qvo);

    return "/show04.jsp";//随便转发到一个页面,不影响测试结果.
}

测试结果:

12.3 后端给前端响应Json数据.

需求:

跟上一个例子类似, 前端发送请求给后端, 后端接收数据后给前端再相应回一个json数据.

该例子中,需要直接把java对象通过SpringMvc自动转化成json数据. 需要使用两个东西完成.

1. 导入Jackson-databind坐标

2. 在方法的返回值上使用@ResponseBody注解.

具体代码如下:

Pom文件坐标

  com.fasterxml.jackson.core
  jackson-databind
  2.9.7


Controller代码:
@RequestMapping("tj.action")
public @ResponseBody QVo getInfo(String name,Double price){

    System.out.println("接收到前端数据:"+name+" "+price);

    //创建一个对象, 通过SpringMvc自动把这个对象转化成Json响应给前端
    QVo qVo = new QVo("lisiguang", 220.4);
    return qVo;
}

前端:


    $(function () {

        var url = "${pageContext.request.contextPath}/tj.action";
        var params={
            "name":"zhangsan",
            "price":"123"
        }
        var callBack=function (rel) {
            //后端有返回结果 就会弹窗显示, 没有就不会弹窗
            alert(rel.name+" "+rel.price)
        }
        //发射
        $.post(url,params,callBack,"json")

    })

测试结果:

后端:

前端:

13. RESTful支持

13.1 什么是RESTful

​ Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。 l 资源定位:每一个URL都是一个资源。要求url中没有动词,只有名词。没有参数 Url格式:http://blog.csdn.net/beat_the_world/article/details/45621673 l 资源操作:通过HTTP请求方式确定不同的操作。 get查询资源、post新建资源(也可以修改资源)、put更新资源、delete删除资源。 一般使用时还是post和get。 @RequestMapping(value="/viewItems/{id}" , method= RequestMethod.GET ) l RESTful初体验 在URL中包含操作的数据,而不是通过参数进行传递。

13.2 添加jar包

13.3 修改web.xml,支持RESTful

  	springmvc
  	org.springframework.web.servlet.DispatcherServlet
  	
  		contextConfigLocation
  		classpath:springmvc.xml
  	
  
  
  	springmvc
  	/

13.4 JSP页面

Insert title here
	
	
		$(function(){
			alert("静态资源(js)可以使用");
		});
	


	查询id=1

	查询id=999

13.5 Controller实现

通过@RequestMapping可以设置URL模板模式映射。 @RequestMapping(value="/ viewItems/{xxx}") ,{xxx}相当于占位符,可以匹配到/viewItems/1、/viewItems/2 等路径 xxx就是占位符的名称,用于方法参数获得匹配到的数据 通过@PathVariable(“xxx”) 获得从路径匹配到的对应数据

	@RequestMapping("/viewItems/{id}")
	public String viewItems(@PathVariable("id") String id , Model model) {
		model.addAttribute("id", id);
		return "itemslist";
	}

13.6 静态资源问题及解决

l 当程序运行时,首页的js代码将不能执行。

原因:DispatcherServlet中设置url-pattern为 /,静态资源不能成功访问。

解决:配置 mvc:resources

14. 拦截器

14.1 概述

​ Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器执行前后进行处理。

​ 自定义连接性需要实现接口:HandlerInterceptor

14.2 分析

方法名

描述

boolean preHandle()

在处理器(控制器)前执行。返回一个boolean值。true:继续执行处理器。false:程序直接结束。

void postHandle()

在处理器方法执行后,视图显示前执行。

void afterCompletion()

在视图解析成功后执行。

14.3 自定义 拦截器

14.3.1 JSP页面,测试入口

拦截器演示

14.3.2 控制器,测试程序

@Controller
@RequestMapping("/user")
public class ItemsController {
	
	@RequestMapping("index")
	public String index(String id) {
		System.out.println("2.controller");
		return "itemslist";
	}
}

14.3.3 拦截器实现类

package com.Maynor.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor1 implements HandlerInterceptor {
    /*
     * 在方法执行之前执行
     * 如果返回true 继续执行下一个拦截器
     * 如果返回false,请求被终止
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor1拦截器的preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor1拦截器的postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor1拦截器的afterCompletion");
    }
}

14.3.4 注册拦截器

拦截器编写完成之后,需要在SpringMVCConfiguration配置文件中注册

注册步骤:

1 SpringMVCConfiguration实现WebMvcConfigurerAdapter

2 重写AddInterceptors方法

public class SpringMvcConfig  extends WebMvcConfigurerAdapter {
    @Autowired
    private MyInterceptor1 myInterceptor1;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration1 = registry.addInterceptor(myInterceptor1);
        interceptorRegistration1.addPathPatterns("/*");
    }
     //.....
}

14.3.5 执行结果

14.4 多拦截器配置

14.4.1 分析

14.4.2 拦截器实现类

package com.Maynor.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor2 implements HandlerInterceptor {
    /*
     * 在方法执行之前执行
     * 如果返回true 继续执行下一个拦截器
     * 如果返回false,则程序终止
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor2拦截器的preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor2拦截器的postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor2拦截器的afterCompletion");
    }
}

14.4.3 注册 拦截器

@Resource
private MyInterceptor1 myInterceptor1;

@Resource
private MyInterceptor2 myInterceptor2;

@Override
public void addInterceptors(InterceptorRegistry registry) {

    //拦截全部
    InterceptorRegistration interceptorRegistration2 = registry.addInterceptor(myInterceptor2);
    interceptorRegistration2.addPathPatterns("/*");
    //拦截全部
    InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor1);
    interceptorRegistration.addPathPatterns("/*");

}

14.4.4 执行结果

15. 附录

用到的相关配置文件

15.1 SpringMVC01_pom

SpringMVC入门案例1的pom文件核心代码

Pom.xml文件

<properties>
  <org.springframework.version>4.2.4.RELEASEorg.springframework.version>
properties>


<dependencies>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-beansartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-expressionartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-context-supportartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aspectsartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-instrumentartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-messagingartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-ormartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-oxmartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jmsartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-websocketartifactId>
        <version>${org.springframework.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>${org.springframework.version}version>
    dependency>


    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvc-portletartifactId>
        <version>${org.springframework.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>${org.springframework.version}version>
    dependency>
    

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>${org.springframework.version}version>
    dependency>

    
    


    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        <scope>testscope>
    dependency>
    <dependency>
        <groupId>tk.mybatisgroupId>
        <artifactId>mapperartifactId>
        <version>3.5.2version>
    dependency>
    <dependency>
        <groupId>com.github.pagehelpergroupId>
        <artifactId>pagehelperartifactId>
        <version>3.7.5version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.4.5version>
    dependency>

    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.47version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>1.3.2version>
    dependency>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.1.10version>
    dependency>

    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>3.1.0version>
        <scope>providedscope>
    dependency>

    <dependency>
        <groupId>jstlgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>

dependencies>


<plugin>
  <groupId>org.apache.maven.pluginsgroupId>
  <artifactId>maven-compiler-pluginartifactId>
  <version>3.2version>
  <configuration>
    <source>1.8source>
    <target>1.8target>
    <encoding>UTF-8encoding>
    <showWarnings>trueshowWarnings>
  configuration>
plugin>


<plugin>
  <groupId>org.apache.tomcat.mavengroupId>
  <artifactId>tomcat7-maven-pluginartifactId>
  <version>2.1version>
  <configuration>
    <port>8080port>
    <server>tomcat7server>
  configuration>
plugin>