With the below servlet code,
package com.example.tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("firstname") == null || request.getParameter("lastname") == null){
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
this.getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
}
}
I first receive the request parameters using index.jsp
as shown below:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<form action="servletexample" method="post" >
<table border="0">
<tr>
<td>First Name:</td> <td><input type="text" name="firstname" /></td>
</tr>
<tr>
<td>Last Name:</td> <td><input type="text" name="lastname" /></td>
</tr>
<tr>
<td colspan="2"> <input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
and then the servlet communicate with output.jsp
using requestdispatcher
, as shown below:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<h1>Your first and last name is: </h1>
<%
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
out.print(firstName + " " + lastName);
%>
</body>
</html>
In the above output.jsp
code, request.getParameter
method is used to retrieve the forwarded parameters from servlet.
Now, instead of output.jsp
, I would like to use only html file[with javascript(if required)],
What should be the content of html body?
Note: Going further, Intention is to just use html/javascrip/css as front end and java based web frameworks(like Spring) as back end. My current learning about servlets/jsp is to have smooth transition to Spring framework(backend) that can work with html/javascrip/css