一、SpringMVC的注解开发
1.1创建项目
1.2完善项目
1.3导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wangxing.springwebmvc2</groupId>
<artifactId>Spring-Web-MVC2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring-Web-MVC2 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!--配置JSP依赖包-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<!--配置JSTL的依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>Spring-Web-MVC2</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
1.4配置web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
1.5配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置自动扫描包-->
<context:component-scan base-package="com.wangxing.springmvc.controller"></context:component-scan>
<!--配置识图视图解析器-->
<!--org.springframework.web.servlet.view.InternalResourceViewResolver-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=""></property>
</bean>
</beans>
1.6创建控制器
package com.wangxing.springmvc.controller;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
//@RequestMapping("/*hello")
//@RequestMapping(value = "/?hello")
// @RequestMapping(value = "/**/hello")
public class HelloController {
/*' ?' 匹配任何单字符
' * ' 匹配任意数量的字符
' ** ' 匹配多个路径
* */
// @RequestMapping(value = "/?test1.do")
// @RequestMapping("/*test1.do")
@RequestMapping(value = "/test1.do", method = RequestMethod.POST)
public ModelAndView testRequest(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("info","hello,wangxing");
modelAndView.setViewName("forward:test.jsp");
// modelAndView.setViewName("redirect:test.jsp");
return modelAndView;
}
}
//http://localhost:8080/springmvc2/ahello/atest1.do
//http://localhost:8080/springmvc2/abchello/abctest1.do
//http://localhost:8080/springmvc2/abc/hello/def/test1.do
//http://localhost:8080/springmvc2/hello/test1.do
二、@Controller注解
@Controller---表示我们所编写的java类是一个处理请求的控制器类。
只能作用在java类。
可以使用@Component去代替,在javaweb程序中是分层出来的为了表名java类是一个控制器,我们才使用@Controller
@Controller中包含有@Component。
@Controller与我们在spring中学习的@Service和@Repository将应用程序标记为不同的层。
数据访问层------@Repository
业务访问层------@Service
Web层【控制层】----@Controller
webapp------------静态资源
三、@RequestMapping
设置控制器类/请求处理方法的访问路径的
@RequestMapping可以作用在java类上,表示配置这个java类的访问路径;
如果控制器类中没有@RequestMapping("/hello"),那么我们要访问请求处理方法就可以直接使用请求处理方法上@RequestMapping("/test1.do")的访问路径。
@RequestMapping也可以作用在请求处理方法上,表示配置这个请求处理方法的访问路径。
@RequestMapping的常用的属性
1.value表示设置访问路径[可以省略]
@RequestMapping(value = "/test1.do")
可以省略
@RequestMapping("/test1.do")
设置访问路径的时候可以设置通配符
? : 匹配任何单字符
例如:@RequestMapping("/?hello.test")
http://localhost:8080/spingmvc2/atest1.do
http://localhost:8080/spingmvc2/test1.do //错误
http://localhost:8080/spingmvc2/hhhtest1.do //错误
* : 匹配任意数量的字符
例如:@RequestMapping("/*hello.test")
http://localhost:8080/spingmvc2/test1.do
http://localhost:8080/spingmvc2/wtest1.do
http://localhost:8080/spingmvc2/wwwtest1.do
例如:@RequestMapping("/*/hello.test")
http://localhost:8080/spingmvc2/w/test1.do
http://localhost:8080/spingmvc2/www/test1.do
http://localhost:8080/spingmvc2/test1.do //错误
http://localhost:8080/spingmvc2/hhhh/www/test1.do //错误
** : 匹配多个路径
例如:@RequestMapping("/**/hello.test")
http://localhost:8080/spingmvc2/test1.do
http://localhost:8080/spingmvc2/w/test1.do
http://localhost:8080/spingmvc2/www/test1.do
http://localhost:8080/spingmvc2/hhh/www/test1.do
2.method--限制请求的访问方式【GET、POST.....】
表现形式:@RequestMapping(value = "/login.do",method = RequestMethod.POST )
Index.jsp
<%@page language="java" pageEncoding="UTF-8" %>
<html>
<body>
<form action="test1.do" method="get">
<input type="submit" value="测试Method属性"/>
</form>
</body>
</html>
package com.wangxing.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController{
@RequestMapping(value = "/test1.do",method = RequestMethod.POST)
public ModelAndView testRequest(){
ModelAndView mav=new ModelAndView();
mav.addObject("info","hello,网星软件");
mav.setViewName("test.jsp");
return mav;
}
}
将index.jsp页面中的表单提交放射修改成post即可成功。
只能处理get请求
@RequestMapping(value = "/gethello.do",method = RequestMethod.GET)
@GetMapping(value = "/gethello.do")
只能处理post请求
@RequestMapping(value = "/gethello.do",method = RequestMethod.POST)
@PostMapping(value = "/gethello.do")
四、请求处理方法接收请求参数值
1.@PathVariable 定义在方法上获取请求url路径上的参数数据
例如:
请求处理方法:
package com.wangxing.springmvc3.controller.test1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @PathVariable 定义在方法上获取请求url路径上的参数数据
* http://localhost:8080/demo3/test/testPathVariable/zhangsan/123456/23/xian
* web.xml文件的中央中央控制的<url-pattern>*.do</url-pattern>
* */
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/testPathVariable/{username}/{password}/{age}/{address}.do")
public void testPathVariable(@PathVariable("username") String name,
@PathVariable("password") String pass,
@PathVariable("age") String age,
@PathVariable("address") String address
){
System.out.println("name=="+name);
System.out.println("pass=="+pass);
System.out.println("age=="+age);
System.out.println("address=="+address);
}
}
http请求:http://localhost:8080/spingmvc2/get1/zhangsan/123456
注意:web.xml文件的中央中央控制的<url-pattern>*.do</url-pattern>
2.@RequestParam 定义在方法上,获取请求中通过key=value方式传递的参数数据
例如:
请求处理方法
package com.wangxing.springmvc3.controller.test2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping(value = "/hello")
public class controller2 {
/**
* @RequestParam 定义在方法上,获取请求中通过key=value方式传递的参数数据
* 无论是get请求/post请求都可以使用
*/
@RequestMapping("/testRequestParam.do")
public void testRequestParam(@RequestParam("username") String name, @RequestParam("password") String pass, String age, String address){
System.out.println("username=="+name);
System.out.println("password=="+pass);
System.out.println("age=="+age);
System.out.println("address=="+address);
}
}
http请求:http://localhost:8080/spingmvc2/testRequestParam.do?username=lisi&password=000000
web.xml文件的中央中央控制器的<url-pattern>*.do</url-pattern>
请求处理方法:@RequestMapping(value = "/testRequestParam.do",method = RequestMethod.GET)
http请求:http://localhost:8080/spingmvc2/testRequestParam.do?username=lisi&password=000000
3.在请求处理方法中定义对应参数变量,参数变量的名称与页面元素的name属性值相同
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="./my/testReqParam.do" method="post">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
年龄:<input type="text" name="age" /><br>
地址:<input type="text" name="address" /><br>
<input type="submit" value="提交" /><br>
</form>
</body>
</html>
package com.wangxing.springmvc3.controller.test3;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/my")
public class MyController {
/**
* 4.在请求处理方法中定义对应参数变量,参数变量的名称与页面元素的name属性值相同
*
*/
@RequestMapping("/testReqParam.do")
public void testReqReqParam(String username,String password,String myage,String myaddress){
System.out.println("username=="+username);
System.out.println("password=="+password);
System.out.println("myage=="+myage);
System.out.println("myaddress=="+myaddress);
}
}
4.将需要提交的请求参数值封装到java对象中【java对象的成员变量的名称一定要与页面元素的name属性值相同】
例如:
package com.wangxing.springmvc3.controller.test4.personbean;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class UserBean {
private String username;
private String password;
private int myage;
private String myaddress;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date day;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMyage() {
return myage;
}
public void setMyage(int myage) {
this.myage = myage;
}
public String getMyaddress() {
return myaddress;
}
public void setMyaddress(String myaddress) {
this.myaddress = myaddress;
}
public Date getDay() {
return day;
}
public void setDay(Date day) {
this.day = day;
}
}
package com.wangxing.springmvc3.controller.test4.controller;
import com.wangxing.springmvc3.controller.test4.personbean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class controller {
/**
* 将需要提交的请求参数值封装进java对象中
* 【java对象的成员变量的名称一定要与页面元素中name的属性值相同】
* @return
*/
@RequestMapping("/testUserBean.do")
public void getReqParam(UserBean userBean){
System.out.println("username=="+userBean.getUsername());
System.out.println("password=="+userBean.getPassword());
System.out.println("myage=="+userBean.getMyage());
System.out.println("myaddress=="+userBean.getMyaddress());
System.out.println("day=="+userBean.getDay());
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="testReqParam.do" method="post">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
年龄:<input type="text" name="age" /><br>
地址:<input type="text" name="address" /><br>
<input type="submit" value="提交" /><br>
</form>
</body>
</html>
2.
package com.wangxing.springmvc3.controller.test4.controller;
import com.wangxing.springmvc3.controller.test4.personbean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller("controller22")
public class controller2 {
@RequestMapping(value = "/getpara.do",method = RequestMethod.POST)
public ModelAndView getReqParam(UserBean userBean){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("userbean",userBean);
modelAndView.setViewName("/jsp/test.jsp");
return modelAndView;
}
}
<%@ page import="org.springframework.web.servlet.ModelAndView" %><%--
Created by IntelliJ IDEA.
User: 14336
Date: 2021/4/17
Time: 9:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>test</title>
</head>
<body>
<h1>${userbean.username}</h1>
<h1>${userbean.password}</h1>
<h1>${userbean.myage}</h1>
<h1>${userbean.myaddress}</h1>
</body>
</html>
注意:java对象的成员变量的名称一定要与页面元素的name属性值相同
5.HttpServletRequest对象的getParameter()方法接收数据
package com.wangxing.springmvc3.controller.test5.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/dox")
public class DoxController {
/**
* HttpServletRequest对象的getParameter()方法接口数据
*/
@RequestMapping("/testHttpServletReq.do")
public void testHttpServletReq(HttpServletRequest request){
System.out.println("username=="+request.getParameter("username"));
System.out.println("password=="+request.getParameter("password"));
System.out.println("myage=="+request.getParameter("myage"));
System.out.println("myaddress=="+request.getParameter("myaddress"));
}
}
http请求:http://localhost:8080/spingmvc2/testHttpServletReq.do?username=wangwu&password=111111
6.将被提交的请求参数组织成json数据【后面介绍】
SpringMVC访问静态资源
当我们使用SPringMVC访问HTML文件的时候出现404错误,因为SpringMVC不支持静态资源的访问【.html / .js / .css /.jpg.....】
方案一:激活Tomcat的defaultServlet来处理静态文件[web.xml]
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
要写在DispatcherServlet的前面, 让defaultServlet先拦截,这个就不会进入Spring了,我想性能是最好的吧。
方案二: 在spring3.0.4以后版本提供了mvc:resources
<!--对静态资源文件的访问-->
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />