Springmvc是一个基于MVC的web框架,属于Spring的一个模块。
idea构建一个Springmvc项目:
1.创建一个没有骨架的maven项目:
2.导入jar包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
</dependencies>
3.将maven项目变为web项目:
右键项目:
添加web支持:
引入jar包:
(1)
(2)
在web-inf下面新建一个文件夹lib
往lib里面添加jar包:
配置Tomcat:
在WEB-INF下面配置dispatchServlet并制定Springmv的配置文件:
<?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">
<!--字符过滤器,防止乱码,必须放在最上面-->
<filter>
<filter-name>enciding</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>enciding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--指定SPringmvc文件的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Springmvc.xml</param-value>
</init-param>
<!--serlvet默认加载时第一次访问的时候,下面设置将加载提前到容器加载时-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在配置文件中配置 映射器,适配器,视图解析器,并制定要使用的Controller:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
">
<!--处理器映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--将Controller引入到容器内-->
<bean id="/hello" class="Contranal.MyCon"/>
</beans>
public class MyCon implements Controller {
public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
//创建视图对象
ModelAndView mv =new ModelAndView();
//设置消息
String result="HelloWorld";
//将消息放到作用域
mv.addObject("msg",result);
//设置视图名称,视图解析器会进行拼接
mv.setViewName("test");
return mv;
}
}
Springmvc的注解开发
SPringmvc配置文件内容:
<?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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--扫描包 使其内部的注解生效-->
<context:component-scan base-package="ConAnno"/>
<!--Tomcat自带一个dispatchServlet,但是开发人员自己写了一个dispatchServlet
所以当访问静态资源时,开发人员写的无法处理,就交给Tomcat默认的Servelt处理-->
<mvc:default-servlet-handler/>
<!--替代映射器和适配器-->
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
测试类,会跳转到hello.jsp页面:
Restful风格
@Controller
public class Controller {
//localhost:8080/add?a=1&b=2 这是平常的风格 RequestMapping默认跳转方式为get
//但是后面可以添加跳转方式
//localhost:8080/add/1/2 这是resultful风格访问
@RequestMapping(value="/add/{a}/{b}",method = RequestMethod.GET)
public String add(@PathVariable int a,@PathVariable int b, Model model){
int res=a+b;
model.addAttribute("msg","结果为"+res);
return "hello";
}
}
关于RequestMapping里一些属性的设置:
@Controller
public class Controller1 {
//method限制客户端请求只能是method的值才会处理请求
@RequestMapping(value="/test",method= RequestMethod.GET)
public String test( String name, Model model){
model.addAttribute("msg",name);
System.out.println(name);
return "hello";
}
//params可以让请求必须携带参数或者不准携带什么参数
//下面演示的就是请求必须有username不能有age
@RequestMapping(value = "/test2",params = {"username","!age"})
public String test2(User user){
System.out.println(user);
return "hello";
}
//设置请求头,规定请求必须和下面header里设置的一样才能处理请求
@PostMapping(value = "/test3",headers = {})
//@RequestParam中的value设置是和前端参数名与下面方法参数的一个映射
//当required=false的时候,前端可以没有这个name属性不报错
//defaultValue当值为null的时候可以设置默认值
public String test3(@RequestParam(value="name",required = false,defaultValue = "damin") String name, Model model){
System.out.println(name);
model.addAttribute("msg",name);
return "hello";
}
}
JSON
fastjson和Jackson
导入依赖:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
</dependencies>
Jackson的使用:
//RestController是跟ResponseBody一样的效果但是比后者强大
//加在类上面,使其整个都不走适配器
@Controller
public class UserController {
@RequestMapping("/t")
@ResponseBody//让下面的方法返回一个字符串
public String test() throws JsonProcessingException {
//jackson用来转化字符串的一个类,创建一个对象
ObjectMapper mapper =new ObjectMapper();
User user =new User("阿斯顿",2);
//使用这个方法可以将对象变为json字符串表示
String s = mapper.writeValueAsString(user);
return s;
}
@ResponseBody
@RequestMapping("/t1")
public String test2() throws JsonProcessingException {
ObjectMapper o =new ObjectMapper();
User user1 =new User("是吧",2);
User user2 =new User("阿斯顿",5);
List<User> list=new ArrayList<User>();
list.add(user1);
list.add(user2);
String s = o.writeValueAsString(list);
return s;
}
}
fastjson的使用:
@RestController
public class FastJson {
@RequestMapping("/fast")
public String fastjson(){
ArrayList<User> users = new ArrayList<User>();
User user1 = new User("zz", 22);
User user2 = new User("zz", 22);
User user3 = new User("zz", 22);
User user4 = new User("zz", 22);
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
//直接使用JSON调用静态方法
String s = JSON.toJSONString(users);
return s;
}
}
AJAX的使用
拦截器
实现HandlerInterceptor接口:
public class Myinterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("处理前...");
//return false是不放行,return true是放行
return true;
}
//代码异常不会运行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("处理后");
}
//只要放行就会运行,即使代码异常,相当于finally
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("清理后");
}
}
配置文件中配置:
SPringmvc的一些操作
一个实体类中有另一个实体类的对象
在前端的表单中可以这样表示:
当Controller接收时,可以直接接收一个对象:
文件的上传与下载:
在配置文件中配置文件解析器:
<!--配置文件上传解析器,id名字必须是这个,因为Springmvc将File类封装了,所以需要解析-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
执行操作:
@Controller
public class TestDownimg {
//文件下载
@RequestMapping("/down")
public ResponseEntity<byte[]> down(HttpSession session) throws IOException {
//获取下载文件的路径
//session.getServletContext().getRealPath获取项目的路径,括号中写一个可以到写的内容的路径
String path = session.getServletContext().getRealPath("img");
//获取下载文件的路径,File.separator是文件路径中斜线的表示方式
String realpath=path+ File.separator+"1.png";
//创建流
FileInputStream is = new FileInputStream(realpath);
//准备一个数组放下载的文件,is.available()会从io流获取文件最大的字节数
byte[] bytes = new byte[is.available()];
is.read(bytes);
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename=zzz");
//设置状态码
HttpStatus status = HttpStatus.OK;
//创建实体,将上面的数组,请求头,状态码放进去
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(bytes,headers,status);
return entity;
}
//文件上传,注意形参和前端表单name一致
@RequestMapping(value = "/up",method = RequestMethod.POST)
public String uoload(@RequestParam("file") CommonsMultipartFile uploadFile, HttpSession session) throws IOException {
//上传的文件名
String filename = uploadFile.getOriginalFilename();
//设置上传文件放的位置
String realPath = session.getServletContext().getRealPath("/photo");
System.out.println(realPath);
//创建文件
File file = new File(realPath);
if(!file.exists()){
file.mkdir();
}
//执行上传操作
uploadFile.transferTo(new File(file+"/"+filename));
return "success";
}
}