简介
由于在昨天看书的过程中遇到点问题,许久才搞定,所以昨天博客就没有更新。
以下内容将是介绍spring mvc在web中的使用,以下配置为纯java方式进行配置的
前提
需要搭建好本地的web环境,这篇博客写的不错,值得参考
搭建spring mvc环境
环境搭建中对部分已经进行注释
- 首先添加依赖
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
<aspectj.version>1.8.10</aspectj.version>
<!-- Java EE 版本号-->
<javaee.version>7.0</javaee.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
<scope>runtime</scope>
</dependency>
<!-- spring 框架包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring测试框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale es_ES
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
- 新建一个class文件夹用于存放java相关文件
- 配置spring mvc(不用web.xml文件,用java方式进行替代)
新建一个包,cn.simfg.note.web.config
然后在新建三个类,SpringWebAppInitializer(替代web.xml),WebConfig(替代springmvc.xml),RootConfig(替代application.xml)
SpringWebAppInitializer.java
package cn.simfg.note.web.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/6
*/
public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//应用配置,类似链接application.xml
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
// 指定配置类,即javaConfig
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
//所有请求都交于spring DispatcherServlet(前端控制器)
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
WebConfig.java
package cn.simfg.note.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/6
*/
@Configuration
//启用注解驱动的spring mvc
@EnableWebMvc
@ComponentScan(basePackages = {"cn.simfg.note.web.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
//视图控制器
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
internalResourceViewResolver.setExposeContextBeansAsAttributes(true);
return internalResourceViewResolver;
}
// 处理静态资源的时候,将请求转发到Servlet容器中默认的Servlet上
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
super.configureDefaultServletHandling(configurer);
configurer.enable();
}
}
RootConfig.java
package cn.simfg.note.web.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/6
*/
@Configuration
@ComponentScan(basePackages = { "cn.simfg.note.web" }, excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig {
}
- 新建一个cn.simfg.note.web.controller包,主要存放控制controller
HomeController
package cn.simfg.note.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/6
*/
//控制器注解
@Controller
public class HomeController {
//映射,用于处理请求
@RequestMapping(value = {"/home","/default"})
public String home() {
return "home";
}
}
修改一下index.jsp文件
<%
//进行重定向
response.sendRedirect("home");
%>
<html>
<body>
<h2>Hello World!</h2>
<a href="home">home</a>
</body>
</html>
然后在WEB-INF下新建一个文件夹views,用于存放视图文件
然后在views文件夹新建一个home.jsp
home.jsp
<%--
Created by IntelliJ IDEA.
User: fubang
Date: 2017/10/6
Time: 下午4:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Spring</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/style.css">
</head>
<body>
<h1>Welcome to Spring</h1>
</body>
</html>
到这里,应该就可以运行了,这时候在运行下,如果看到了welcome to spring这个页面,说明你成功了!
GET方式请求,带参数
get方式,如分页时像后台传递的页数,url类似于:http://localhost:8080/double/other?index=89
首先还是编写控制器
OtherController.java
package cn.simfg.note.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/7
*/
@Controller
public class OtherController {
// 一个生成三个连续字母,当第一个字母为y是,那么就只有两个字母y和z
public List getAbc(int i) {
List<String> other = new ArrayList<String>();
// 65 90 97 122
int index = 0;
int count = 0;
if (i < 65) {
index = 65;
} else if (i < 97 && i > 90) {
index = 97;
} else if (i > 122) {
index = 97;
} else {
index = i;
}
if (index < 91) {
if (91 - index > 3) {
count = 3;
} else {
count = 91 - index;
}
} else {
if (123 - index > 3) {
count = 3;
} else {
count = 123 - index;
}
}
for (int j = 0; j < count; j++) {
other.add((char) (index + j) + "");
}
return other;
}
@RequestMapping(value = "other", method = GET)
// RequestParam中name和value没有区别,都是指参数名称
public String other(Model model, @RequestParam(value = "index",defaultValue = "65") int start) {
/*List<String> other = new ArrayList<String>();
other.add("A");
other.add("B");
other.add("C");*/
model.addAttribute("other", getAbc(start));
return "other";
}
//路径中的字符作为参数使用
//注意PathVariable注解,便是使用路径上的参数
@RequestMapping(value = "link/{start}", method = GET)
public String other(Map model,@PathVariable(name = "start",required = false) int start) {
/*List<String> other = new ArrayList<String>();
other.add("A");
other.add("B");
other.add("C");*/
System.out.println(start);
model.put("other", getAbc(start));
return "other";
}
}
如果需要往页面上传递数据,那么可以忘控制接口中传递一个参数Model或者Map,然后往对象中添加对象就可以了,jsp中使用${}便可以得到
RequestParam注解,可以设置页面上的数据,如name、value是表示也页面上该参数的名称,required用于设置该参数是不是必须的,defaultValue是设置这个参数的默认值
other.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false"%>
<html>
<head>
<title>OTHER</title>
</head>
<body>
<h1>OTHER</h1>
<ol>
<%-- 标签不生效,可以添加 <%@ page isELIgnored="false"%> --%>
<c:forEach items="${other}" var="temp">
<li>${temp}</li>
</c:forEach>
</ol>
</body>
</html>
然后重启服务器,在浏览器中输入对应的url进行访问,如
http://localhost:8080/double/other
http://localhost:8080/double/other?index=89
http://localhost:8080/double/link/1
POST方式
首先新建一个包cn.simfg.note.web.pojo,然后在声明一个pojo类
User.java
package cn.simfg.note.web.pojo;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/7
*/
public class User {
//对请求的参数进行校验
@NotNull
@Size(min = 2, max = 16)
private String name;
@NotNull
@Size(min = 2, max = 16)
private String password;
@NotNull
@Min(16)
private int age;
public User() {
}
public User(String name, String password, int age) {
this.name = name;
this.password = password;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", password='" + password + '\'' + ", age=" + age
+ '}';
}
}
2.编写对应的controller
LoginController.java
package cn.simfg.note.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Map;
import javax.validation.Valid;
import cn.simfg.note.web.pojo.User;
/**
* @Author: simfg
* @Description:
* @Date: 2017/10/7
*/
@Controller
public class LoginController {
@RequestMapping(value = "login",method = RequestMethod.GET)
public String login(Map model) {
model.put("user", new User());
return "login";
}
@RequestMapping(value = "display",method = RequestMethod.POST)
public String display(@Valid @ModelAttribute("user")
User user,Errors errors,Map model){
if (errors.hasErrors()){
return "login";
}
model.put("user",user);
return "display";
}
}
两个jsp
home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>LOGIN</title>
</head>
<body>
<sf:form method="post" commandName="user" action="display">
name:<sf:input path="name" />
<sf:errors path="name"/>
<br>
password:<sf:password path="password"/>
<sf:errors path="password"/>
<br>
age:<sf:input path="age" type="number"/>
<sf:errors path="age"/>
<br>
<input type="submit" value="SUBMIT">
</sf:form>
</body>
</html>
上面引入了spring中表单标签库,其中commandName表示后台返回数据中一定要有一个user的对象,path属性表示该相当于input标签中name,下一篇博客将会详细介绍
display.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>DISPLAY</title>
</head>
<body>
<h1>HELLO,${user.name}</h1>
<hr/>
<p>password:${user.password}</p>
<p>age:${user.age}</p>
</body>
</html>
最后就是测试了
扫描左边二维码,关注个人公众号:SimFG,让我们一起探索世界吧