第五课 从零开始学Spring boot 之 (JSP 和 Servlet)

一、JSP相关配置

JSP (Spring Boot官方不推荐,STS创建的项目会在src/main/resources 下有个templates 目录,这里就是让我们放模版文件的,然后并没有生成诸如 SpringMVC 中的webapp目录)

1、在pom.xml文件添加依赖;

	
		 <!-- tomcat 的支持.-->  
       <dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-tomcat</artifactId>  
           <scope>provided</scope>  
       </dependency>  
       <dependency>
    		<groupId>org.apache.tomcat.embed</groupId>
    		<artifactId>tomcat-embed-jasper</artifactId>
    		<scope>provided</scope>  
		</dependency>
       <!-- servlet 依赖. -->  
       <dependency>  
           <groupId>javax.servlet</groupId>  
           <artifactId>javax.servlet-api</artifactId>  
           <scope>provided</scope>  
       </dependency>  
       
       <!--  
           JSTL(JSP Standard Tag Library,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。JSTL只能运行在支持JSP1.2和Servlet2.3规范的容器上,如tomcat 4.x。在JSP 2.0中也是作为标准支持的。  
           不然报异常信息:  
           javax.servlet.ServletException: Circular view path [/helloJsp]: would dispatch back to the current handler URL [/helloJsp] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)  
        --> 
       <dependency>  
           <groupId>javax.servlet</groupId>  
           <artifactId>jstl</artifactId>  
       </dependency> 
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
            <exclusions>  
	        <exclusion>  
	            <groupId>com.alibaba</groupId>  
	            <artifactId>jconsole</artifactId>  
	        </exclusion>  
	        <exclusion>  
	            <groupId>com.alibaba</groupId>  
	            <artifactId>tools</artifactId>  
	        </exclusion>  
    		</exclusions>  
		</dependency>

jdk版本

<!-- Jdk编译版本 -->
<build>
    <plugins>		   
        <finalName>spring-boot-jsp</finalName>
           <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
              </configuration>
           </plugin>
    </plugins>
</build>

2、配置application.properties支持jsp

因为spring-boot 不推荐JSP,想使用JSP需要配置application.properties 

添加src/main/resources/application.properties内容:

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp
# 自定义属性,可以在Controller中读取
application.hello=Hello Angel From application

3、编写测试Controller

@Controller
public class IndexController {
	
	  // 从application.properties 中读取配置,如取不到默认值为Hello Shanhy  
    @Value("${application.hello:Hello Angel}")  
    private String hello;  
      
    @RequestMapping("/helloJsp")  
    public String helloJsp(Map<String,Object> map){  
          System.out.println("HelloController.helloJsp().hello="+hello);  
          map.put("hello", hello);  
          return "hello";  
    } 
}

4、编写JSP页面

 src/main 下面创建 webapp/WEB-INF/jsp 目录用来存放我们的jsp页面helloJsp.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>  
    helloJsp  
    <hr>  
    ${hello}  
     
</body>  
</html>

右键Run As  Java Application访问:http://127.0.0.1:8080/helloJsp 可以访问到:

helloJsp


Hello Angel From application



二、Servlet 相关配置

Web开发使用 Controller 基本上可以完成大部分需求,但是我们还可能会用到 ServletFilterListenerInterceptor 等等。

当使用Spring-Boot时,嵌入式Servlet容器通过扫描注解的方式注册ServletFilterServlet规范的所有监听器(如HttpSessionListener监听器)。

Spring boot 的主 Servlet  DispatcherServlet,其默认的url-pattern“/”。也许我们在应用中还需要定义更多Servlet,该如何使用SpringBoot来完成呢?

spring boot中添加自己的Servlet有两种方法,代码注册Servlet和注解自动注册(FilterListener也是如此)。 


一、代码注册通过ServletRegistrationBean FilterRegistrationBean  ServletListenerRegistrationBean 获得控制。 

也可以通过实现 ServletContextInitializer 接口直接注册,如下:

package com.gongh.config;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * 自定义servlet1
 * @author gh
 * @version v.0.1
 */
public class MyServlet1 extends HttpServlet{
	static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("=====MyServlet1 doGet()======");
        doPost(req, resp);

    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    	System.out.println("=====MyServlet1 doPost()======");
        resp.setContentType("text/html"); 
        
        PrintWriter out = resp.getWriter(); 
        out.println("<html>"); 
        out.println("<head>"); 
        out.println("<title>Hello World</title>"); 
        out.println("</head>"); 
        out.println("<body>"); 
        out.println("<h1>this is MyServlet1</h1>"); 
        out.println("</body>"); 
        out.println("</html>");

    }

}

 然后在App.java启动类中进行注册

@SpringBootApplication
@ServletComponentScan //是的spring能够扫描到我们自己编写的servlet和filter。
public class App extends WebMvcConfigurerAdapter{
	    
	  public static void main(String[] args) {  
	          SpringApplication.run(App.class, args);  
	  }  
	  
	  @Bean
      public ServletRegistrationBean MyServlet1(){
            return new ServletRegistrationBean(new MyServlet1(),"/myServlet/*");
      }}
	  

右键Run As Java Application进行访问http://127.0.0.1:8080/myServlet


二、在 SpringBootApplication 使用@ServletComponentScan注解后,ServletFilterListener 可以直接通过 @WebServlet@WebFilter@WebListener 注解自动注册,无需其他代码。


package com.gongh.config;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义servlet2
 * @author gh
 * @version v.0.1
 */
@WebServlet(urlPatterns="/myServlet2/*", description="Servlet的说明")
public class MyServlet2 extends HttpServlet{
      
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("=====MyServlet2 doGet()======");
        doPost(req, resp);

    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    	System.out.println("=====MyServlet2 doPost()======");
        resp.setContentType("text/html"); 
        
        PrintWriter out = resp.getWriter(); 
        out.println("<html>"); 
        out.println("<head>"); 
        out.println("<title>Hello World</title>"); 
        out.println("</head>"); 
        out.println("<body>"); 
        out.println("<h1>this is MyServlet2</h1>"); 
        out.println("</body>"); 
        out.println("</html>");

    }

}


右键Run As Java Application进行访问http://127.0.0.1:8080/myServlet2



猜你喜欢

转载自blog.csdn.net/gonghua0502/article/details/80169204
今日推荐