创建一个maven项目
pom.xml配置文件
<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.uek.objuct</groupId>
<artifactId>spring-app</artifactId>
<version>0.1</version>
<packaging>war</packaging>
<properties>
<project.bulid.sourceEncoding>UTF-8</project.bulid.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<!-- 自定义版本标记 -->
<spring.version>5.1.7.RELEASE</spring.version>
</properties>
<!-- 配置项目所需要的第三方的jar包 -->
<dependencies>
<!--Servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit Junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--Spring 框架 IOC 第一天要引入的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring5 AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java Mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid Druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring与Spring MVC 的整合 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--阿里的fastJSON处理工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
<!-- 4.配置构建插件 -->
<build>
<plugins>
<!-- 编译插件 -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/uservlet</path>
<!-- 实现热部署 不需要每次修改代码后都重启启动Tomcat -->
</configuration>
</plugin>
</plugins>
</build>
</project>
基于注解的配置类(JavaConfig的形式配置)
@Configuration
@EnableWebMvc
@ComponentScan({"mvc"})
public class AppConfig {
/*
* jsp的解析器
* 这个Bean的作用就是告诉Spring MVC你写的jsp文件的位置
* @return
*/
@Bean
public UrlBasedViewResolver setupViewResolver(){
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/"); //位置(受保护的,不可以直接访问)
resolver.setSuffix(".jsp"); //jsp文件的后缀,你在写页面的时候就省略掉后缀
resolver.setViewClass(JstlView.class);
return resolver;
}
}
Tomcat启动的时候会检测是否有WebApplicationInitializer接口的类,
若检测到有这个类,就会实例化它,并调用它的onStartup方法
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("starup invoker the method...");
//1.构造Spring容器
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
//2.Spring容器加载配置
ctx.register(AppConfig.class);
//3.Spring容器接管ServletContext应用上下文对象
ctx.setServletContext(servletContext);
//4.添加Servlet(至少添加一个Servlet,SpringMVC框架实现的入口Servlet)
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
实体类
public class User {
private String name;
private int age;
public User(){}
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
练习
@Controller
@RequestMapping("user")
public class HelloController {
@RequestMapping("/hello")
public void hello(){
System.out.println("hello 大帅哥");
}
@RequestMapping("/hi")
public void hi(){
System.out.println("hi 对面的女孩看过来");
}
@RequestMapping("/index") //映射路径
public String index(HttpServletRequest request,HttpServletResponse response){ //方法名
System.out.println(request.getParameter("name"));
System.out.println(request.getParameter("password"));
/*try {
PrintWriter out = response.getWriter();
out.write("hello word");
out.close();
} catch (IOException e) {
e.printStackTrace();
}*/
return "index"; //页面的名字
}
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("/date")
@ResponseBody
public String aaa(){
//1.先从后台查数据
List<User> users = new ArrayList<User>();
users.add(new User("zhangsan",18));
users.add(new User("lisi",19));
users.add(new User("wangwu",20));
//2.用alibaba的fastJson工具 拼接字符串
String jsonStr = JSON.toJSONString(users);
return jsonStr;
/*return "[{'name':zhangsan,'age':18}],"
+"{'name':lisi,'age':19},"
+"{'name':wangwu,'age':20}]"; 自己拼接字符串*/
}
/*
* 返回得是页面,并且可以给页面传递数据
* @return
*/
@RequestMapping("/test")
public ModelAndView bbb(HttpServletRequest request,HttpServletResponse response) {
ModelAndView mv = new ModelAndView("test");
mv.addObject("message", "my love");
mv.addObject("username",new ArrayList<User>());
return mv;
//底层:
/*request.setAttribute("message", "hello");
try {
request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
}
@RequestMapping("/users1")
@ResponseBody
public String getUser1(int pageNo,int pageSize){
System.out.println(pageNo);
System.out.println(pageSize);
return "[]";
}
@RequestMapping("/users2")
@ResponseBody
public String getUser2(HttpServletRequest request,HttpServletResponse response){
request.getParameter("pagaNo");
request.getParameter("pageSize");
return "[]";
}
//RestFul形式的接口:
@RequestMapping("/users3/{pageNo}/{pageSize}")
@ResponseBody
public String getUser3(@PathVariable("pageNo") int pageNo,@PathVariable("pageSize") int pageSize){
System.out.println(pageNo);
System.out.println(pageSize);
return "[]";
}
/*
@RequestMapping(value="/c",method=RequestMethod.POST)
@ResponseBody
public String c(){
System.out.println("aaaa");
return "";
}*/
//get请求
@GetMapping("/get")
public void test(){
System.out.println("get request");
}
//POST
@PostMapping("/post")
public void test1(){
System.out.println("post request");
}
}
在webapp下新建文件夹WEB-INF
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<p>Hello nihao</p>
<form action="c" method="post">
<input type="submit" value="submit">
</form>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h2>我想要你带你去烂漫的土耳其,然后一起去东京和巴黎</h2>
</body>
</html>
test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${ message }
</body>
</html>
jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_chat
jdbc.username=root
jdbc.password=