#WebServlet on Tomcat 7 getting 404 Error - servlets

Tomcat 7 running on Windows 7, using servlet annotation, is giving me a 404 error when I try this URL:
http://localhost:8080/LoginExample/
Tomcat is using JRE 1.7, and the servlet class is contained within folder .../webapps/LoginExample. It was compiled using Java 1.7. I have no Web.xml. It deploys without error.
Here is the class:
package com.journaldev.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet(
description = "Login Servlet",
urlPatterns = { "/LoginServlet" },
initParams = {
#WebInitParam(name = "user", value = "Pankaj"),
#WebInitParam(name = "password", value = "journaldev")
})
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
//we can create DB connection resource here and set it to Servlet context
if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&
getServletContext().getInitParameter("dbUser").equals("mysql_user") &&
getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))
getServletContext().setAttribute("DB_Success", "True");
else throw new ServletException("DB Connection error");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
//get servlet config init params
String userID = getServletConfig().getInitParameter("user");
String password = getServletConfig().getInitParameter("password");
//logging example
log("User="+user+"::password="+pwd);
if(userID.equals(user) && password.equals(pwd)){
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}

Your servlet class LoginServlet is designed to handle only '/LoginServlet' url and in http://localhost:8080/LoginExample/ you are using '/' as url.
You must use http://localhost:8080/LoginExample/LoginServlet
OR
<form action="LoginServlet" method="post">
....
....
</form>

Related

How to resolve view in thymleaf + Springboot?

Currently, i have function, which is to convert the data from MYSQL to CSV. The CSV function contain the webconfig where use the viewResolver. The problem is, when i used below function, the page cannot view but the CSV file can be download and vice versa. Is there anything that i need to configure ?
-Configure ContentNegotiatingViewResolver
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
WebConfig- full code
package com.portal.dmtt.csvDownload.config;
import com.portal.dmtt.csvDownload.viewResolver.CsvViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import java.util.ArrayList;
import java.util.List;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true);
}
/*
* Configure ContentNegotiatingViewResolver
*/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
}
Export Controller
package com.portal.dmtt.csvDownload.controller;
import com.portal.dmtt.repo.dmttDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExportController {
#Autowired
private dmttDAO dmttDAO;
/**
* Handle request to download an Excel document
*/
#GetMapping("/dl")
public String download(Model model) {
model.addAttribute("results", dmttDAO.getAllResultSet());
return "";
}
}
Abstract View
package com.portal.dmtt.csvDownload.view;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public abstract class AbstractCsvView extends AbstractView {
private static final String CONTENT_TYPE = "text/csv";
public AbstractCsvView() {
setContentType(CONTENT_TYPE);
}
#Override
protected boolean generatesDownloadContent() {
return true;
}
#Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
buildCsvDocument(model, request, response);
}
protected abstract void buildCsvDocument(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
CSV View
package com.portal.dmtt.csvDownload.view;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class CsvView extends AbstractCsvView {
#Override
protected void buildCsvDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse
response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"my-csv-file.csv\"");
List<FN_Result_Set> fnResultSetList = (List<FN_Result_Set>) model.get("results");
String[] header = {"SP_ID", "SP_ID", "XFER_XMIT_STATUS", "XFER_FILE_NAME", "UPDATE_TS", "YYMM", "REMARKS"};
try {
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
csvWriter.writeHeader(header);
for (FN_Result_Set user : fnResultSetList) {
csvWriter.write(user, header);
}
csvWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
View Resolver
package com.portal.dmtt.csvDownload.viewResolver;
import com.portal.dmtt.csvDownload.view.CsvView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
public class CsvViewResolver implements ViewResolver {
#Override
public View resolveViewName(String s, Locale locale) throws Exception {
return new CsvView();
}
}
One of the problems is that your CSVViewResolver is resolving a view for any view name. You may want to return null from CSVViewResolver.resolveViewName() if s, the view name, is not empty .
Another issue is that the browser (at least my Chrome) doesn't send text/csv as Accept header, but text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Set the media type explicitly in configureContentNegotiation for CSV:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true)
.mediaType("csv", MediaType.parseMediaType("text/csv"));
}
Remove the Bean contentNegotiatingViewResolver
You shouldn't create a contentNegotiatingViewResolver as one is provided by Spring Boot. If you provide one, you will have two of this type, and yours will not have the Thymeleaf ViewResolver. As your CSVViewResolver will return a view for any view name, the view will be resolved in the ContentNegotiatingViewResolver provided by you, not in the one provided by Spring.
Details:
The csvViewResolver bean will be picked up by the Spring Boot's ContentNegotiatingViewResolver along others like BeanNameViewResolver, ThymeleafViewResolver, ViewResolverComposite, InternalResourceViewResolver.
To debug this set a breakpoint on DispatcherServlet.resolveViewName:
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
HttpServletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
}
}
return null;
}

Spring 4 mvc I always get Request method 'POST' not supported

My issue is that I get always Request method 'POST' not supported !
I'm trying to test my rest web webservice. Here is the WS :
#RequestMapping(value = "/addGouvernorate", method = RequestMethod.POST, produces = { "application/json" })
public ResponseEntity<Gouvernorate> addGouvernorateee(#RequestBody Gouvernorate gouvernorate) throws IOException {
gouvernorateService.addGouvernorat(gouvernorate);
return new ResponseEntity<Gouvernorate>(gouvernorate, HttpStatus.OK);
}
i'm trying to call it with jsoup as follows :
package test.sofiane.rqs;
import java.io.IOException;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.springframework.security.crypto.codec.Base64;
public class Test {
public static void main(String[] args) throws IOException {
String base64login = new String(Base64.encode("sof:1".getBytes()));
Response docs = Jsoup.connect("http://localhost:8080/site/data/addGouvernorate")
.data("name", "name")
.data("delegation", "delegation")
.data("district", "district")
.data("postalCode", "postalCode")
.method(Method.POST)
.execute();
}
}
I get the exception :
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=405, URL=http://localhost:8080/mintad/data/addGouvernorate
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:459)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:434)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:181)
at test.sofiane.rqs.Test.main(Test.java:21)
And with Postman application I get
Etat HTTP 405 - Request method 'POST' not supported
I'm using spring security also.
as follow
package com.site.spring.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* #author Sofiane
*/
#Configuration
#EnableWebSecurity
#ComponentScan
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
#Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
//.antMatchers("/admin/**").denyAll()//.access("hasRole('ADMIN')")
.and().formLogin().loginPage("/login")
.defaultSuccessUrl("/welcome").usernameParameter("username").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/404");
// #formatter:off
}
}
A guess : it can be the csrftoken which I have to send since I'm behind spring security but how to generate it ?
Please help because it's driving me insane guys

Servlet and XQuery

I wrote a java class to run a simple XQuery on a XML database (Using Saxon xqj). The query works well in this class. But I want to access this class from a servlet. The problem is that the servlet doesn't find the java class, It gets java.lang.ClassNotFoundException: javax.xml.xquery.XQException when I run the servlet. Any Ideas please?
The Java class is as simple as This:
import java.util.Properties;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import javax.xml.xquery.XQSequence;
import javax.xml.namespace.QName;
import net.sf.saxon.xqj.SaxonXQDataSource;
import org.xml.sax.SAXException;
public class XMLClass {
public static String xmldata() throws XQException{
XQConnection con;
String output = null;
final String sep = System.getProperty("line.separator");
String fileName= "cd_book.xml";
con = new SaxonXQDataSource().getConnection();
System.out.println("Connected");
String queryString = "declare variable $docName as xs:string external;"+sep +
"for $x in doc($docName)/*" +
" return $x";
XQPreparedExpression expr = con.prepareExpression(queryString);
expr.bindObject(new QName("docName"), fileName, null);
XQResultSequence rs = expr.executeQuery();
String result =rs.getSequenceAsString(new Properties());
return result;
}
}
And the Servlet is:
import java.io.IOException;
import java.io.PrintWriter;
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.xml.xquery.XQException;
public class ServletXML extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletXML() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
XMLClass.xmldata();
} catch (XQException e) {
e.printStackTrace()
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Then xml your class may be missing from your classpath. How are you compiling and running this?
Also it is good practice to place both into one or more packages and import your class from your servlet if it is in a different package.

ClassNotFoundException of com.mysql.jdbc.Driver, when using servlets

this wierd problem is very interrupting me for a long time. I have a class name Connector inside dynamic web application in eclipse, with these code:
public class Connector {
private static final String dbURL = "jdbc:mysql://localhost:3306/";
private Connection con;
public Connector(String userName, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(dbURL, userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
System.err.print("Unidentified exception has acurred!");
e.printStackTrace();
}
}
when I'm using it from different Class in the same package, named portal, it works fine, but when I'm trying to use it from servlet in package servlets, named LoginHandle.java, I get ClassNotFoundException.
The Class is in the build path of all classes, and I checked it by trying to import it from the servlet, but when I create new instance, it is not being recognized. I tried to move the servlet to the package of the connector, and vise versa, and it didn't affect. Here is the servlet's code:
package servlets;
import java.io.IOException;
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 portal.Connector;
import portal.UserTableAnalyzer;
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginHandle() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String referer = request.getHeader("Referer");
String pageName = referer.substring(referer.lastIndexOf('/') + 1);
if(pageName.equals("Login.jsp"))
{
HttpSession session = request.getSession(false);
Connector c = new Connector("root", "16180339887");
c.executeUpdate("USE Main");
String id = request.getParameter("id"), password = request.getParameter("password");
String query = "SELECT FROM Users WHERE id ='" + id + "' AND password = '" + password + "'";
String[][] result = c.executeQuery(query);
UserTableAnalyzer uta = new UserTableAnalyzer(result);
if(result.length > 0)
{
session.setAttribute("userID", uta.getID(0));
session.setAttribute("role", uta.getRole(0));
response.sendRedirect("Main.jsp");
}
else
{
request.setAttribute("wrongDetails", new Boolean(true));
response.sendRedirect("Login.jsp");
}
}
else
response.getWriter().print(pageName);
}
}
sorry if my english is bad, or if details are missing
Your driver is not in the server classpath, build path has nothing to do with that.
You didn't write which application server are you using. You also should use DataSource in servlets, rather than DriverManager. Here is sample configuration for Tomcat.
UPDATE
For Tomcat 7 you need to do the following:
Put mysql jar in the $CATALINA_HOME/lib
Configure Datasource in context
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/databaseName"/>
Use Datasource in servlet (pseudo code)
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(lookup="jdbc/testDB")
private DataSource ds;
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection c = ds.getConnection();
...

Unable to send the value of two attributes to JSP from servlet using requestdispatcher

Please help . Below is my code to redirect the request with two attributes to JSP but both of the below two attributes returns the value of passWord .
1)user_Name
2)Pass_word
for example , ABC is my username and XYZ is my password which is get from the "FORM" but my second value i.e the value of the passWord variable is appears in both of the attribute.
printing inside the jsp page :
user_Name: XYS (Should be ABC instead of XYZ)
pass_Word: XYZ
servlet :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class JndiConn extends HttpServlet implements Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
RequestDispatcher rd=request.getRequestDispatcher ("GetParameter.jsp");
System.out.println(userName);
System.out.println(passWord);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Connection connection = getConnection();
if (connection != null) {
String sql = "SELECT count(1) FROM scott.login_user where login_id ='"+userName+"' and password='"+passWord+"'";
String sql1 = "select SYSDATE from dual";
System.out.println(sql);
try{
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int number=rs.getInt("count(1)");
System.out.println("Result value is "+number);
if(number==1)
{
System.out.println("THE LOGIN SUCCESS FOR::"+userName);
String sql2 = "INSERT INTO SCOTT.LOGIN_USER VALUES(3,'VINOTH','vinoth55','SCOTT',to_date('08/06/13','DD/MM/RR'),105)";
PreparedStatement statement1 = connection.prepareStatement(sql2);
ResultSet rs1 = statement1.executeQuery();
rd.forward(request, response);
}
else{
System.out.println("THE LOGIN FAILURE FOR "+userName);
rd.forward(request, response);
}
}
connection.close();
}catch(Exception e){
System.out.println(e);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
private Connection getConnection() {
Connection connection = null;
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("vinothprd");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
Below is my JSP to print the user_Name and pass_Word :
JSP:
String user_Name="";
String userName=(String)request.getAttribute(user_Name);
String pass_Word="";
String passWord=(String)request.getAttribute(pass_Word);
System.out.println("user_Name: "+userName);
System.out.println("pass_Word: "+passWord);
Thanks for your help in advance...
In Servlet you are setting, attributes using empty value.
String user_Name="";
request.setAttribute(user_Name,userName);
String pass_Word="";
request.setAttribute(pass_Word,passWord);
First of all, this is wrong and I don't know why you are doing this.
In JSP, When you access request.getAttribute(user_Name); // which is empty "",
you will get the value of password as username was overridden.
Solution:
You should set attribute like
EDIT Servlet
String userName=request.getParameter("Username");
String passWord=request.getParameter("password");
String user_Name="userName";
request.setAttribute(user_Name, userName);
String pass_Word="passWord";
request.setAttribute(pass_Word, passWord);
then in JSP
String user_Name="userName"
String userName=(String) request.getAttribute(user_Name);
String pass_Word="passWord";
String passWord=(String)request.getAttribute(pass_Word);
See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#setAttribute

Resources