@muyanfeixiang
2017-01-12T17:27:23.000000Z
字数 2562
阅读 1337
JavaWeb
Spring
SpringMVC
上一小节使用了servlet,本小节使用jsp,jsp类似asp.net mvc中cshtml文件。
首先在pom.xml文件中添加jsp模块依赖,如下。
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.2</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
</exclusion>
</exclusions>
</dependency>
在web中的WEB-INF下添加jsp文件夹,添加Greet.jsp文件
Greet.jsp文件内容如下
<%--
Created by IntelliJ IDEA.
User: liuyb
Date: 2017/1/12
Time: 16:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>From Greet jsp</title>
</head>
<body>
<p>Hello From Greet.jsp 文件</p>
</body>
</html>
当然此时jsp还不能被使用,首先需要在web.xml中添加相应的配置。如下
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspf</url-pattern>
<page-encoding>UTF-8</page-encoding>
<scripting-invalid>false</scripting-invalid>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
<default-content-type>text/html</default-content-type>
</jsp-property-group>
</jsp-config>
再次需要修改GreetServlet,来指定返回的jsp文件,修改如下
package com.liuyb;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by liuyb on 2017/1/12.
*/
@WebServlet(
name = "greetServlet",
urlPatterns = {"/greet"},
loadOnStartup = 1
)
@MultipartConfig(
fileSizeThreshold = 5_242_880, //5MB
maxFileSize = 20_971_520L, //20MB
maxRequestSize = 41_943_040L //40MB
)
public class GreetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF/jsp/Greet.jsp")
.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("Hello Post From GreetServlet");
}
}
然后运行程序,在浏览器输入http://localhost:8080/greet
可以看到如下