How to link external css in java servlet? - java

I have a report.jsp page which looks like below (NOTE: I have just added codes which are necessary).
<form name="report" action="../printOrganization" method="post">
<table>
<tr>
<td>
Organization name: <input type="text" name="orgName" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" name="action" />
</td>
</tr>
</table>
When user clicks "Submit" button of report.jsp page. The request is sent to servlet called OrganizationServlet. And the request is handle by doPost method. The code in OrganizationServlet looks like below:
public class OrganizationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String organizatio = request.getParameter("orgName");
if (organizatio.equals("ABC")) {
printAllOrganization();
}
}
public void printAllOrganization()
{
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
pw.println("<!DOCTYPE html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n");
pw.println("<html>\n");
pw.println("<head>\n");
pw.println("<title> Print Organization </title>\n");
pw.println("<link rel=\"stylesheet\" type=\"text/css\" HREF=\"../styles/myStyle.css\">\n"); // This style sheet doesn't show effect when program run in browser
pw.println("</head>\n");
pw.println("<body>\n");
//printing all organization code is here!
pw.println("</body>\n");
pw.println("</html>\n");
pw.close();
}
The part of web.xml which handles request is shown below:
<servlet>
<servlet-name>servletForOrganization</servlet-name>
<servlet-class>com.project.report.OrganizationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletForOrganization</servlet-name>
<url-pattern>/printOrganization</url-pattern>
</servlet-mapping>
My css file is located in this path:
MyProject > resource > styles > myStyle.css
When I run my application in the browser, the css style which is in printAllOrganization() method of OrganizationServlet servlet doesn't show any effect. Could someone please help me how to sort this problem. Thank you in advance.

Add in your home JSP file:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<link rel="stylesheet" href="<c:url value="/resource/styles/myStyle.css" />">
Add in dispatcher-servlet.xml:
<mvc:resources mapping="/resource/**" location="/resource/" />
modify your class:
public class OrganizationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String organizatio = request.getParameter("orgName");
if (organizatio.equals("ABC")) {
printAllOrganization(request);
}
}
public void printAllOrganization(HttpServletRequest request) {
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
pw.println("<!DOCTYPE html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n");
pw.println("<html>\n");
pw.println("<head>\n");
pw.println("<title> Print Organization </title>\n");
pw.println("<link rel=\"stylesheet\" type=\"text/css\" HREF=\"" + request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/resource/styles/myStyle.css\">\n");
pw.println("</head>\n");
pw.println("<body>\n");
//printing all organization code is here!
pw.println("</body>\n");
pw.println("</html>\n");
pw.close();
}

Related

How to redirect from one JSP page to another fresh page

I am new to JSP ans servlets. I have written simple jsp code to display registration form when clicked on "SIGN UP" button as below.
signup.jsp looks like
<!DOCTYPE html>
<html>
<body>
<h2>Welcome </h2>
<img src="abcd.jpg" alt=" " style="width:500px;height:228px;">
<form name="main" method="get" action="login.jsp">
<input type="submit" name="ter" value="SIGN IN" >
</form>
</body>
</html>
When I run this signup.jsp is getting displayed with image and "SIGN IN" button. When I click on this button, login page is getting displayed on the same page where signup.jsp displayed. How can i modify the jsp code such that SIGN IN details will come in a fresh page instead on the same page. My login.jsp looks like
<%# include file="index.jsp" %>
<hr/>
<h3>Login Form</h3>
<%
String profile_msg=(String)request.getAttribute("profile_msg");
if(profile_msg!=null){
out.print(profile_msg);
}
String login_msg=(String)request.getAttribute("login_msg");
if(login_msg!=null){
out.print(login_msg);
}
%>
<br/>
<form action="loginprocess.jsp" method="post">
Email:<input type="text" name="email"/><br/><br/>
Password:<input type="password" name="pass"/><br/><br/>
<input type="submit" value="login"/>"
</form>
can anyone suggest me how to write it using JSP only as I am completely new to java script or other technologies also.
This is how my servlet looks like:
#WebServlet("/SignInFunc")
#MultipartConfig
public class MySignInFunc extends HttpServlet {
/** * */
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
rd.forward(request, response);
}
}
when i click on Sign in, fields mentioned in login.jsp are getting displayed on the same page. I want them on fresh page.
You'll need to create WebServlet and post login request, then using HttpServletRequest and then when you'll be sure that user information is correct forward user to necessary page request.getRequestDispatcher("index.jsp").forward(request, response); You'll allso need to add <form action = "login" method = "post"> this kind of thing to your login form and WebServlet would look like this:
#WebServlet("/login")
public class HandleLogin extends HttpServlet {
public HandleLogin() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
...
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
...
response.sendRedirect("/home.jsp");
}
}

RequestDispatcher Showing Page's source code Java Servlet

Everything is working fine else why RequestDispatcher showing source code of page?
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uName=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
try{
DBConnection con=new DBConnection();
if(con.login(uName, uPass)){
HttpSession on = req.getSession();
on.setAttribute("u_id", uName);
res.sendRedirect("dashboard.jsp");
}
else{
RequestDispatcher dis= getServletContext().getRequestDispatcher("/login.jsp");
PrintWriter write = res.getWriter();
write.println("Wrong Username or Passowrd");
dis.include(req, res);
}
}catch(ClassNotFoundException | SQLException e){}
}
}
Page redirecting fine to given url /login.jsp and also showing the error message, but why as source code?
Wrong Username or Passowrd
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="LoginServlet" method="POST" />
<input type="text" name="uEmail" />
<br /><br />
<input type="text" name="uPass" />
<br /><br />
<input type="Submit" name="Register" value="Register" />
<br /><br />
</form>
</body>
</html>
direct link to login.jsp works fine.
from http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
The include method of Request Dispatcher gets the content of the resource that why you are getting the source code in browser.
I think what you want to do is forward the request to login.jsp so use forward method of request dispatcher.
As #JBNizet mentioned in his comment due to your message from Servlet, HTML is going to be invalid.
before dis.include(req,res);
add this line res.setContentType("text/html); it
I was facing the same issue when I used RequestDispacther method and try to return and String massage along with html page then i have found you have to put some kind of tag to the String massage like then use include method
so if my code was
out.println("Terms & Condition not accepted");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
i changed it to "
out.println("<h1>Terms & Conditions not accepted </h1>")
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
"
You need to set the content type of the response.
Add the below line in your doPost method.
response.setContentType("text/html;charset=UTF-8");
Hope it works for you!!

How to make a servlet's received attributes available to other servlets via the ServletContext's attribute mechanism?

I have to take in information from servlets using forms and then make the information(Strings) available to other servlets via the ServletContext's attribute method? I do NOT understand this in the slightest and would really appreciate a step-by-step breakdown. Here is my code. One servlet takes an integer and a float and the other a name and surname.
First Servlet
package myServlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class FirstServlet extends GenericServlet {
public String firstName;
public String surname;
#Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException{
PrintWriter out = res.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println("ServletResponse");
out.println("</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>First name: " + req.getServletContext().getAttribute("firstName") + "</H1><br>");
out.println("<H1>Surname: " + req.getServletContext().getAttribute("surname") + "</H1><br>");
out.println("<H1>Integer: " + req.getServletContext().getAttribute("integer") + "</H1><br>");
out.println("<H1>Floating Point: " + req.getServletContext().getAttribute("float") + "</H1><br>");
out.println("<br><br><br>Back to the forms! ");
out.println("</BODY>");
out.println("</HTML>");
}
}
My Second Servlet
package myServlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class SecondServlet extends GenericServlet {
public String noInteger;
public String noFloat;
#Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException{
PrintWriter out = res.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println("ServletResponse");
out.println("</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>First name: " + req.getServletContext().getAttribute("firstName") + "</H1><br>");
out.println("<H1>Surname: " + req.getServletContext().getAttribute("surname") + "</H1><br>");
out.println("<H1>Integer: " + req.getServletContext().getAttribute("integer") + "</H1><br>");
out.println("<H1>Floating Point: " + req.getServletContext().getAttribute("float") + "</H1><br>");
out.println("<br><br><br>Back to the forms! ");
out.println("</BODY>");
out.println("</HTML>");
}
}
My Index.html file
<html>
<head>
<title>Lab One</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
First Name: <input type="text" name="firstName">
<br>
Surname: <input type="text" name="surname">
<br>
<form action="FirstServlet" method="POST">
<input type ="submit" name="Submit"> </form>
<br>
Integer: <input type="text" name="integer">
<br>
Float: <input type="text" name="float">
<br>
<form action="SecondServlet" method="POST">
<input type ="submit" name="Submit2"> </form>
</body>
</html>
Why don't you add it as a session attribute
HttpSession session = request.getSession();
String firstName= (String)request.getAttribute("firstName");
session.setAttribute("firstName", firstName);
then the other servlet/jsp can read the value as
session.getAttribute ("firstName");
For simplicity you could also set the entire user class (??) as a session attribute
Edit as you are using ServletRequest as opposed HttpServletRequest try using the below to get the servletContext
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getServletContext()

JSP Form Not Connecting with Servlet 404-Error

I'm having a little issue connecting with my servlet so that I can pass some data to a mysql database. I've read a bunch of the threads here, but have had no luck with suggestions to other members.
I have a jsp page named "insertData.jsp" On that page there is a form where the action points to a servlet named "UpdateData". When I click submit on the web page, I get a 404 error stating that the requested resource is not available. I have also updated my web xml file to try to point to the right direction.
So here's my folder setup:
The UpdateData.java is in the controller package of the source packages folder. The name of the project is "RukertContainerTracker".
Here's my jsp page:
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Data</title>
</head>
<body>
<h1>Insert Data Into Container Records</h1>
<H1>The Rukert Terminals Container Tracker </H1>
<form name="Insert Record" action="/UpdateData" method="Post">
Container Number: <input type="text" name="containerNumber"> <br />
Full Out: <input type="date" name="fullOut" /> <br/>
Empty In: <input type="date" name="emptyIn" /> <br/>
Empty Out <input type="date" name="emptyOut" /> <br/>
Full In: <input type="date" name="fullIn" /> <br/>
Comments: <input type="text" name="comments" /> <br/>
<input type="submit" value="Submit" />
</form>
<div>
<a href="javascript:history.back();">
<span class="categoryLabelText">HOME</span>
</a>
</div>
</body>
</html>
My servlet:
package controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateData extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//Get container data from the JSP page
String container=request.getParameter("containerNumber");
String fullOutDate=request.getParameter("fullOut");
String emptyInDate=request.getParameter("emptyIn");
String emptyOutDate=request.getParameter("emptyOut");
String fullInDate=request.getParameter("fullIn");
String comments=request.getParameter("comments");
//Print the above got values in console
System.out.println("The username is" +container);
System.out.println("\nand the password is" +fullOutDate);
String connectionparams="jdbc:mysql://localhost:3306/rukerttracker";
String db="rukerttracker";
String uname="root";
String psword="Colorado1982";
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("com.mysql.jdbc.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection
(connectionparams, uname, psword);
//Add the data into the database
String sql = "insert into containerinventory values (?,?,?,?,?,?)";
try (PreparedStatement prep = connection.prepareStatement(sql)) {
prep.setString(1, container);
prep.setString(2, fullOutDate);
prep.setString(3, emptyInDate);
prep.setString(4, emptyOutDate);
prep.setString(5, fullInDate);
prep.setString(6, comments);
prep.executeUpdate();
}
}catch(Exception E){
System.out.println("The error is=="+E.getMessage());
}
finally{
connection.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/insertData")) {
// TODO: Implement category request
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
And finally my web.xml page:
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>controller.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/chooseLanguage</url-pattern>
<url-pattern>/viewTracker</url-pattern>
<url-pattern>/editTracker</url-pattern>
<url-pattern>/addToCart</url-pattern>
<url-pattern>/viewCompany</url-pattern>
<url-pattern>/category</url-pattern>
<url-pattern>/updateCart</url-pattern>
<url-pattern>/purchase</url-pattern>
<url-pattern>/viewCart</url-pattern>
<url-pattern>/checkout</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateData</servlet-name>
<servlet-class>controller.UpdateData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateData</servlet-name>
<url-pattern>/insertData</url-pattern>
</servlet-mapping>
I have two servlets, I don't know if this matters, but I couldn't get the application to work in the controller servlet, so I created the Update Data servlet.
Any help as to why I keep getting this 404 error would be greatly, greatly appreciated. Thanks for taking the time to look at this.
I think in form you are using POST method and your servlet does not have post method. please check it.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{...}
not available.

Using Tomcat 7 on Ubuntu 12.04 server and Eclipse EE: servlet won't run a class file

Clicking the submit button on my form produces a save dialog box (asking me to save the .class file that is supposed to run as called from POST) instead of a new page with the form partially filled out.
As stated above I am trying to use Tomcat 7.0.40 with my web application called Demonstration. I have been programming the quite simple pages in Eclipse then compiling them and setting up my own .war file for Tomcat. This didn't work after many, many tries so I let Eclipse do the construction of the .war file for me. Still didn't work.
Here is what I think are the relevant pieces of code.
The first file that runs is this HTML stored as webapps\Demonstration\index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="SurveyMark.css">
<meta charset="ISO-8859-1">
<title>SurveyMark - Input Job</title>
</head>
<body>
<form id="job_input_form" action="JobMade" method=POST>
<h1><img id="logo" alt="TJH Logo" src="logo_small.jpg" align="middle"><b> -
SurveyMark - Input Job INDEX.HTML</b></h1>
<div id="job_div" style="width:250px;float:left">
<h3>Job Details</h3>
<label for="job_number">Job Number</label>
<input type="text" name="job_number" id="job_number">
<label for="addendum">Addendum</label>
<input type="text" name="addendum" id="addendum">
<label for="development_name">Development Name</label>
<input type="text" name="development_name" id="development_name">
<label for="job_type">Job Type</label>
<input type="text" name="job_type" id="job_type">
<label for="date_recieved">Date Recieved</label>
<input type="text" name="date_recieved" id="date_recieved">
</div>
<div id="job_location_div" style="width:250px;float:left">
<h3>Job Location</h3>
<label for="unit_number">Unit Number</label>
<input type="text" name="unit_number" id="unit_number">
<div id="legal_street_number_div" style="width:120px;float:left">
........
........Lots more fields all on the same page, displaying properly
</div>
<input type="submit" value="Add Job">
</form>
</body>
</html>
Which attempts to POST's to the following file \webapps\Demonstration\WEB-INF\classes\Demonstration\JobMade.class
(That compiles from this JobMade.java file)
package Demonstration;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
#WebServlet("/JobMade")
public class JobMade extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//String title = "Job Data that has Been Entered";
out.println("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"SurveyMark.css\">" +
"<meta charset=\"ISO-8859-1\">" +
"<title>SurveyMark - Input Job JOBMADE FILE</title>" +
"</head>" +
"<body>" +
"<form id=\"job_input_form\" action=\"AddedJob.html\" method=\"post\">" +
"<input type=\"submit\" value=\"Add Job\">" +
"<h1><img id=\"logo\" alt=\"TJH Logo\" src=\"logo_small.jpg\" align=\"middle\"> - " +
"SurveyMark - Added Job as Follows</h1>");
#SuppressWarnings("rawtypes")
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("<I>No Value</I>");
else
out.print(paramValue);
} else {
out.println("<UL>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
I have lloked at the catalina log files and can't find anything untoward but if there is something specific that would help I am all ears.
Here is the brief yet important web.xml file stored under the WEB-INF directory.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Demonstration</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thank you in advance for your help.
You did not map that servlet anywhere. Neither in the web.xml file, nor using an annotation.

Categories