JSP or Servlet PrintWriter - java

I recently began implementing java into my website but I've been reading that the method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
//code
out.println("</html>");
out.close();
}
Is outdated and rarely used due to jsp. What are the benefits of doing one versus the other?

The advantage of using JSP over pure servlets is that it is more convenient to write (and to modify) regular HTML than to have plenty of out.println statements that generate the HTML. With JSP, you can mix Java code freely with your HTML code (using tags JSP provides like <%= %>). Your JSP page ultimately compiles to a servlet, the servlet runs, and the response is sent back to the browser.
Pure Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>")
out.println("<p>The date is: " + (new Java.util.date()).toLocaleString() +"</p>");
out.println("</body>")
out.println("</html>");
out.close();
}
JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
....
<body>
<p>The date is: <%= (new Java.util.date()).toLocaleString() %></p> //mixing HTML and Java
</body>
</html>

Technically you can write presentation and business logic in both jsp and servlets. It's widely considered a good practice to to implement the MVC pattern in your webapp, so you want to implement the view in the JSP, use the servlets as the controller and EJBs for the model. Generating the html with your servlet break this separation, that's why it's generally to avoid.
I'm not aware of any benefit from generating the html in a servlet.

Servlet intended for Control and Business Logic.
JSP intended for Presentation Logic.

Related

Cannot retrieve data from Servlet [duplicate]

How do I generate an HTML response in a Java servlet?
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
#WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Our Servlets wiki page
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
Calling a servlet from JSP file on page load
How to transfer data from JSP to servlet when submitting HTML form
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to use Servlets and Ajax?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
You need to have a doGet method as:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
You can see this link for a simple hello world servlet
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}

Index.html is not showing when I open my servlet [duplicate]

How do I generate an HTML response in a Java servlet?
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
#WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Our Servlets wiki page
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
Calling a servlet from JSP file on page load
How to transfer data from JSP to servlet when submitting HTML form
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to use Servlets and Ajax?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
You need to have a doGet method as:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
You can see this link for a simple hello world servlet
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}

How I load css and js of Bootstrap in a web java application (jsp)?

If I use the controller (Servlet) don't see the Boostrap styles.
The events are:
[1] Load login.jsp
[2] Send login information to SessionController (Servlet) throught POST.
[3] SessionController save the information in the Session, create an attribute in the session for indicate to FormsController his work:
request.getSession().setAttribute("user", request.getParameter("usuario"));
request.getSession().setAttribute("pass", request.getParameter("clave"));
request.getSession().setAttribute("pg", "showAll");
request.getRequestDispatcher("FormsController").forward(request, response);`
In this moment pg = "showAll" and SessionController call to FormsController.
[4] FormsController search information in the DataBase and redirect to formularios/datos.jsp
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
switch (request.getParameter("p")) {
case "new":
request.getRequestDispatcher("formularios/nuevoformulario.jsp").forward(request, response);
break;
case "showAll":
DBFormulario f = new DBFormulario(request.getSession().getAttribute("user").toString(), request.getSession().getAttribute("pass").toString());
try {
request.getSession().setAttribute("formularios", f.consultarFormularios());
request.getRequestDispatcher("formularios/datos.jsp").forward(request, response);
} catch (DBExceptionsManager ex) {
Logger.getLogger(FormsController.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
}
More information:
index.jsp:
<meta http-equiv="refresh" content="0;URL=login/login.jsp" />
login.jsp:
http://s2.subirimagenes.com/imagen/9582471login.png
datos.jsp:
http://s2.subirimagenes.com/imagen/9582472datos.png
Views:
http://s2.subirimagenes.com/imagen/previo/thump_9582470sin-ttulo.png
The better way to load the resource files I think is to use the tag jstl core library which provides the tag url to proper URL encoding, for using this library you have to import the jstl/core tag library in your jsp and you will get great benefits of the library which contains if-else, for and many more conditions statements.
To import the library, <%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> write this in your jsp,
and re-write your link tag like below,
<link rel="stylesheet" type="text/css" href="<c:url value='/css/bootstrap.min.css'">

sendRedirect() doens't work

I looked for a solution on this forum, but i didn't find anything that suits my problem.
I have a very simplce code
a jsp page
<html>
<body>
<jsp:include page="/servletName"/>
</body>
</html>
and a servlet
#WebServlet("/servletName")
public class reindirizzaController extends HttpServlet {
private static final long serialVersionUID = 1L;
public reindirizzaController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String redirectURL = "http://www.google.it";
response.sendRedirect(redirectURL);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
No redirect is done. I'm stuck in the jsp page and i get no error. I also tried to add return; after the response.
Since you are calling the servlet through Include, it does not make you redirect. It simply ignores.
From docs of include()
includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.
The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
First, it is bad practice to call a servlet from a jsp. As you are using #WebServlet("/servletName"), you can directly call it at http://host/context/servletName
If you really need to call it from a jsp, you must forward to the servlet instead of including it as Suresh Atta explained. So you should use :
<jsp:forward page="/servletName"/>
When you do a JSP include directive, you're essentially plopping the code you're including right on the page. In your example, you would be doing the sendRedirect in your JSP. Even if you got the redirect to work miraculously, you would get an error saying that your response has already been committed. This is because by the time your browser loads the JSP, it is already reading from the server's response. The server cannot send another response while it is already sending a response to your browser.
One way to approach this is instead of doing an include directive, create a form with your servlet path as the action. Something like:
<form name="someForm" action="/servletPath/servletName">
<!-- some stuff here if you want -->
</form>
And then in your body tag, have it submit the form on load:
<body onLoad="document.someForm.submit();">

How do you mix up java with html and javascript?

I have this little java project in which I have to use jsp files.
I have an html with a login button that triggers the following function:
var loginCall = "user/login";
var logoutCall = "user/logout";
var signupCall = "user/signup";
function login() {
var login = baseUrl + loginCall + "?";
var loginFormElements = document.forms.loginForm.elements;
login = addParam(login, USER_NAME, loginFormElements.userName.value, false);
login = addParam(login, PASSWORD, loginFormElements.password.value, true);
simpleHttpRequest(login, function(responseText){
var status = evalJSON(responseText);
if (status.errorCode == 200) {
var res = status.results;
var sessionId = res[0].sessionId;
setCookie(SESSION_ID,sessionId);
window.location="http://localhost:8080/"+baseUrl+"/main.html";
} else {
showError(status.errorCode, "Username or password was incorrect.")
}
}, function(status, statusText){console.log('z');
showError(status, statusText);
});
}
As far as I can see a httpRequest is made and sent with data to baseUrl + loginCall, meaning localhost/something/user/login?name=somename&pass=somepass
This is where I'm stuck, do I have to make a java file somewhere somehow, that takes the request information, works it up with the database and returns an answer?
If so, where, how? Do I have to name it login/user.java?
Can anyone point me to the right direction, if not give me some code example or explanation of what I have to do next?
You need to have another look at the JSP MVC
The jsp page should hold the html and javascript and java code. If you want to call a separate .java class, you need to write that class as a servlet then call it.
So in your .jsp you have you html and javascript just like you have it there, then any java you include in these brackets <% %>
Have a look at the tutorials here http://www.jsptut.com/
And i see your doing a login page. I used this brilliant tutorial for creating a log in system which helped me understand how jsp and servlets worked.
http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/Full%20Login%20Example.aspx
Also check out this image which should help you understand the concept. Remember servlets are pure java classes, used for mostly java but can also output html, jsp's are used for mostly html (& javascript) but can include jsp. So the servlets do the work, then the jsp gets the computed values so that they can be utilized by JavaScript. that's how i think of it anyway, may be wrong
http://met.guc.edu.eg/OnlineTutorials/static/article_media/jsp%20-%20servlets/LoginExample%20[4].jpg
All the best
If you are not using any MVC framework then best approach would be to extending HttpServlet classes for handling requests and doing all heavy lifting tasks such as business logic processing,accessing/updating databases etc. and then dispatching the request to .jsp files for presentation.In .jsp.You can also add custom objects to request scope that you wish to access on '.jsp' pages + using expression language you can access most request related implicit objects
I taken a typical example of flow in brief.You may can an idea and explore in deep yourself.
Here is java servlet class that will handle a posted form.
public class doLogin extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String username= request.getParameter("username"); // get username/pasword from form
String password = request.getParameter("password");
// This is your imaginary method for checking user authentication from database
if(checkUserAuthentication(username,password)){
/*
user is authenticated.Now fetch data for user to be shown on homepage
User is another class that holds user info. Initialize it with data received from database
*/
user userData = new User;
user.setName(...);
user.setAge(...);
user.setInfo(...);
// etc
}
RequestDispatcher view = req.getRequestDispatcher("login.jsp");
req.setAttribute("userdata", userData); // set user object in current request scope
view.forward(req, resp);//forward to login.jsp
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
}
but you need a form with some action to invoke above ServletClass
<form action="/checkLogin" method="POST">
<input type="text" name="username" value="">
<input type="password" name="password" value="">
<input type="submit" name="login" value="Login">
</form>
To tell your Servlet container to invoke doLogin class on form login button click
you have to configure it in deployment descriptor file web.xml which is part of standard dynamic web application in java
In web.xml' following xml snippet make apllication server aware ofdoLogin` class
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yourdomain.doLogin</servlet-class>
</servlet>
But its not mapped to any url yet,It is configured as below in <servlet-mapping> section in web.xml
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/checkLogin</url-pattern>
</servlet-mapping>
Now any post request to url /checkLogin will invole doPost method on doLogin class
After successful login request will be trasfered to 'login.jsp' page.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
You can use java code in sciptlet <% %> syntax to access userData object
<%
User data = (User)request.getAttribute('userData');
%>
Better and tidy approach is to use expression language
${ pageContext.request.userData.name }
Above expression calls getName() method on object of User class using java beans naming conventions
Here, you can learn more about expression language
May be some time later I can improve this and provide you more insight.Hope that helps :)

Categories