few months ago i've worked on this project for my university (a quiz game) and all was fine! Now i've re-opened the eclipse project but i don't know why, it doesn't work! I've already searched in the old topic, because i know this is a recurrent problem, but i don't know how to solve it! I think is just a configuration problem because i've wrote the entire project on another workstation and there all was fine. Now i'm trying to run the servlet on my Mac with Eclipse Mars and tomcat 8.0.
Here i report the code of one of my servlet and the xml file.
package servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.DbHelper;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbHelper dbHelper = null;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = config.getServletContext();
String driver = context.getInitParameter("dbDriver");
String path = context.getInitParameter("dbUrl");
String user = context.getInitParameter("dbUser");
String pass = context.getInitParameter("dbPassword");
try {
dbHelper = new DbHelper(driver, path, user, pass);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
#Override
public void destroy() {
super.destroy();
if(dbHelper!=null){
try {
dbHelper.destroy();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String username=request.getParameter("username");
String password=request.getParameter("password");
try {if (dbHelper.isPlayer(username, password)){
session.setAttribute("username",username);
response.sendRedirect("Player");
} else
if (dbHelper.isAuthor(username, password)){
session.setAttribute("username",username);
response.sendRedirect("Author");
}else{
request.setAttribute("error", 1);
request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("html/error.html");
}
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
The XML file :
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>CheckMyBrain</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>
<context-param>
<description>Database URL</description>
<param-name>dbUrl</param-name>
<param-value>jdbc:mysql://localhost:3306/Quiz</param-value>
</context-param>
<context-param>
<description>Database user</description>
<param-name>dbUser</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<description>Database password</description>
<param-name>dbPassword</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<description>Database driver</description>
<param-name>dbDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>smtpHost</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>smtpPort</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>smtpUser</param-name>
<param-value>checkmybrain37#gmail.com</param-value>
</context-param>
<context-param>
<param-name>smtpPass</param-name>
<param-value>stosultomcat</param-value>
</context-param>
</web-app>
folders here
Tomcat location is not on workspace metadata.
When i run the Servlet
Related
Genuinely Stumped I'm new to Trying to Develop in java and I'm struggling with creating a user login page.
I want to check if the user has a session and has a key available that I've set at authentication if not I want them to be forwarded to the loginPage.jsp
The code that I've provided works when I don't use the following mapping for my servlet.
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/</url-pattern> -- This works by itself only works on paths not .jsp files
<url-pattern>*.jsp</url-pattern> -- if i include this i only get blank webpages
</servlet-mapping>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Project1</display-name>
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>ControlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/</url-pattern> //Works when by itself
<url-pattern>*.jsp</url-pattern> //breaks when i enabled this
</servlet-mapping>
<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>
Control Servlet.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ControlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// // TODO Auto-generated method stub
HttpSession session = request.getSession(false);
if (session == null) {
// Not created yet. Now do so yourself.
session = request.getSession();
} else {
// Already created.
}
//Check if User is Logged in
String pathInfo = (request.getPathInfo() != null) ? request.getPathInfo() : request.getServletPath();
System.err.println("check1");
System.err.println(session.getAttribute("name") == null);
System.err.println("check2");
System.err.println(!"/loginPage.jsp".equals(pathInfo));
System.err.println(pathInfo);
if (session.getAttribute("name") == null && !"/loginPage.jsp".equals(pathInfo))
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/loginPage.jsp");
requestDispatcher.forward(request, response);
//response.sendRedirect("loginPage.jsp");
System.err.println("did this ever happen?");
}else {
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
How can I add a HTML comment on every HTML and JSP page?
I've tried to modify it with a filter and it could only modify the JSP pages and not the HTML pages.
I used a filter like this:
package com.app.server.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class WaterMarkFilter implements Filter {
private List<String> extensionsToFilter = new ArrayList<>();
#Override
public void init(FilterConfig filterConfig) throws ServletException {
String[] extensions = filterConfig.getInitParameter("extensionsToFilter").split(",");
for (String extension : extensions) {
extensionsToFilter.add(extension.trim());
}
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
postFilter(request, response);
}
#Override
public void destroy() {
}
private void postFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
String path = ((HttpServletRequest) request).getRequestURI();
if (canIntercept(path)) {
response.getWriter().write("modified");
response.getWriter().close();
}
}
private boolean canIntercept(String path) {
if (path.equals("/")) {
return true;
}
for (String extension : extensionsToFilter) {
if (path.endsWith("." + extension)) {
return true;
}
}
return false;
}
}
This is the Web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>com.app.configuration ShoppingCartService</servlet-name>
<servlet-class>com.app.server.servlet.ShoppingCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>com.app.configuration ShoppingCartService</servlet-name>
<url-pattern>/application/ShoppingCartServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.app.server.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/application/test</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.app.server.ApplicationInitializer</listener-class>
</listener>
<filter>
<filter-name>WaterMarkFilter</filter-name>
<filter-class>com.app.server.filter.WaterMarkFilter</filter-class>
<init-param>
<param-name>extensionsToFilter</param-name>
<param-value>jsp, html</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>WaterMarkFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
The actual question is how to manipulate the ServletResponse using Filter.
My detailed answer with full code example and many links is here
Short:
In the doFilter implementation:
before the chain.doFilter call, prepare a HttpServletResponseWrapper and a PrintWriter
after the call, write in the PrintWriter a copy of the wrapped response + "the text you want"
Bellow are the code changes in order the filter to work with HTML too:
public class WaterMarkFilter implements Filter {
private ServletRequest request;
private PrintWriter out;
private CharResponseWrapper wrapper;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
this.request = request;
out = response.getWriter();
wrapper = new CharResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, wrapper);
postFilter();
out.close();
}
private void postFilter() throws IOException, ServletException {
String path = ((HttpServletRequest) request).getRequestURI();
if (canIntercept(path)) {
out.write(wrapper.toString() + "modified");
}
else {
out.write(wrapper.toString());
}
}
}
The CharResponseWrapper is the same as in my detailed answer here.
There is also a better example how to include text into already created html.
Just adding text at the end is good only for plain text files.
For HTML - It is better to insert the text inside the HTML. The example there is with <head> tag, but it could be adapted to insert to <body> tag.
I have the following Java servlet:
package com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Teste extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setAttribute("teste", "Test");
request.getSession().setAttribute("teste", "Test Session");
RequestDispatcher rd = request.getRequestDispatcher("teste.jsp");
rd.forward(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
And the following web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Teste</servlet-name>
<servlet-class>com.controller.Teste</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Teste</servlet-name>
<url-pattern>/teste</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I can access the servlet through the url http://localhost:8084/myapp/teste
What I want is change the url-pattern to /teste/edit, but when I do that, and try to access the servlet through the url http://localhost:8084/myapp/teste/edit I get the following 404 error:
HTTP Status 404 - /TrabalhoPSW/teste/teste.jsp
type Status report
message /TrabalhoPSW/teste/teste.jsp
description The requested resource is not available. Apache
Tomcat/8.0.27
Why is this happening? How can I fix this?
The problem was the JSP file that the servlet was trying to find. when I changed from
request.getRequestDispatcher("teste.jsp");
to
request.getRequestDispatcher("/teste.jsp");
It worked normally.
if you need than your servlet works with /path and /path/to, Change the mapping of servlet in web.xml to:
<url-pattern>/teste/*</url-pattern>
Hi I am trying to run a servlet which gets the data from a simple html form and stores in oracle database and displays a message "Data Saved". I am using Eclipse Luna, Tomcat 7.0 and Oracle 11g Express Edition. When I run the the program I get this error.
java.sql.SQLException: Io exception: Got minus one from a read call
during JDBC connection with oracle 11g
Here is my web.xml file
<?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" 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>StudentManagement</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>StudentRegServlet</servlet-name>
<servlet-class>com.serv.pkg.StudentRegServlet</servlet-class>
<init-param>
<description></description>
<param-name>username</param-name>
<param-value>scott</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>tiger</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StudentRegServlet</servlet-name>
<url-pattern>/stdreg</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CourseRegServlet</servlet-name>
<servlet-class>com.serv.pkg.CourseRegServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>test</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>test</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CourseRegServlet</servlet-name>
<url-pattern>/coursereg</url-pattern>
</servlet-mapping>
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:#localhost:8080:XE</param-value>
</context-param>
</web-app>
My Servlet
package com.serv.pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
/**
* Servlet implementation class CourseRegServlet
*/
#WebServlet("/CourseRegServlet")
public class CourseRegServlet extends GenericServlet {
private Connection conn;
#Override
public void init(ServletConfig config)throws ServletException
{
System.out.println("Executing init method from coursereg.html");
ServletContext sc = config.getServletContext( );
String driver=sc.getInitParameter("driver");
String url=sc.getInitParameter("url");
String username=config.getInitParameter("username");
String password=config.getInitParameter("password");
try {
Class.forName(driver);
System.out.println("driver loaded");
conn=DriverManager.getConnection(url, username, password );
} catch ( Exception e) {
System.out.println("catching from init" +e);
}
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println("Executing service method from coursereg.html");
int cid = Integer.parseInt(request.getParameter("cid"));
String c_name = request.getParameter("c_name");
int fee = Integer.parseInt(request.getParameter("fee"));
try {
System.out.println("exe1");
PreparedStatement stmt=conn.prepareStatement("insert into course values(?,?,?)");
System.out.println("exe2");
stmt.setInt(1, cid);
stmt.setString(2, c_name);
stmt.setInt(3, fee);
int i = stmt.executeUpdate();
if(i!=0){
System.out.println("course registered");
}else
{
System.out.println("registration failed");
}
} catch ( Exception e) {
System.out.println(e);
}
out.println("Data saved");
}
public void destroy(){
try {
System.out.println("Executing destroy method from coursereg.html");
conn.close();
} catch ( Exception e) {
System.out.println(e);
}
}
}
The default port for the database listener is 1521, not 8080 (which is the default HTTP port, from XML DB); so your URL should be:
<param-value>jdbc:oracle:thin:#localhost:1521:XE</param-value>
If your listener is on a non-standard port then use that instead. Also the :XE part means it'll try to connect with the SID XE. You might prefer to use the service name, which is hopefully also XE, which would be denoted by a slash instead of a colon:
<param-value>jdbc:oracle:thin:#localhost:1521/XE</param-value>
I have developed a web application
if i run the application in tomcat 6 it asks for username and password
but after 3 attempsts it shows
the web.xml document is
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>LoginRemote</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>
<servlet>
<description></description>
<display-name>remoteSample</display-name>
<servlet-name>remoteSample</servlet-name>
<servlet-class>com.src.remoteSample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>remoteSample</servlet-name>
<url-pattern>/remoteSample</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Secure</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Authentication required</realm-name>
</login-config>
<security-role>
<role-name>*</role-name>
</security-role>
</web-app>
i want to get the remote user's user name and password what should i do for it?
this is my servlet code
package com.src;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.buf.Base64;
public class remoteSample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public remoteSample() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
System.out.println("login info:"+request.getRemoteUser());
System.out.println("Authentication type:"+request.getAuthType());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
should i change something in my server's tomcat-server.xml and web.xml?
check that realm name you are using in server & remote user is matched with following name or not.
<realm-name>Authentication required</realm-name>
please check this link for more information regarding exception