Jerry's Blog

Recording what I learned everyday

View on GitHub


2 May 2019

Create a JSP project with IntellijIDEA

by Jerry Zhang

#Tip of the Day: //TODO Blog paging



https://www.youtube.com/watch?v=licQZlIenAk

Download Tomcat

Create a new project

  1. Choose Java Enterprise

  2. Application server: choose the tomcat we just downloaded. New -> Tomcat Server -> Choose the Tomcat folder as Tomcat Home.

  3. Check Web Application and JSF (JSF is optional)

  4. Select a project directory. Finish.

Then, we should be able to see a new JSP project.

create

First JSP program

Under Web folder, new -> JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello</title>
</head>
<body>
<%
    int a = 3;
    int b = 4;
    int c = a + b;
    out.println("c = " + c);
%>
</body>
</html>

Then we can check the path root of our web app. Right click the project -> open module settings -> Modules -> Web

root

IMPORTANT: Make sure that the run configuration is correct!

Open the Tomcat configuration, make sure that the URL is http://localhost:8080/

Select the Deployment tab and make sure that the Application context is /

URL

applicationcontext

Then run our application, go to http://localhost:8080/, we should see the default content in index.html. If we go to http://localhost:8080/hello.jsp, we should be able to see the page we just created.

hellojsp

Create a servlet

Under src folder, create a new package, then right click it and choose new, Create new servlet Type a name for the servlet class.

Write a simple servlet

@WebServlet(name = "MyServlet", urlPatterns = {"/a/b/c", "/servlets/hello"})
public class MyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello</h1>");
        out.flush();
    }
}

We assign two urlPatterns, so we can get the page with http://localhost:8080/a/b/c and http://localhost:8080/servlets/hello

abcjsp

tags: Java, - JSP, - IntellijIDEA