Servlet in Eclipse: The requested resource [/Register/] is not available [duplicate] - servlets

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
Exact error: The requested resource [/Register/] is not available. Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I am using tomcat and Eclipse.
Here is the code:
RegisterDao.java
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterDao {
private String dbUrl = "jdbc:mysql://localhost:3306/explorecalifornia";
private String dbUname = "dbuser";
private String dbPassword = "dbpassword";
private String dbDriver = "com.mysql.cj.jdbc.Driver";
public void loadDriver(String dbDriver)
{
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection()
{
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl, dbUname, dbPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public String insert(Member member)
{
loadDriver(dbDriver);
Connection con = getConnection();
String result = "Data entered successfully";
String sql = "insert into member values(?,?,?,?)";
PreparedStatement ps;
try {
ps = con.prepareStatement(sql);
ps.setString(1, member.getUname());
ps.setString(2, member.getPassword());
ps.setString(3, member.getEmail());
ps.setString(4, member.getPhone());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "Data not entered";
}
return result;
}
}
Register.java
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;
#WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
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.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Member member = new Member(uname, password, email, phone);
RegisterDao rDao = new RegisterDao();
String result = rDao.insert(member);
response.getWriter().print(result);
}
}
web.xml
<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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Registration</display-name>
<welcome-file-list>
<welcome-file>memberRegistration.jsp</welcome-file>
</welcome-file-list>
</web-app>
and memberRegistration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="memberRegistration" method="post">
<table>
<tr><td>User Name: </td><td><input type="text" name="uname"></td></tr>
<tr><td>Password: </td><td><input type="password" name="password"></td></tr>
<tr><td>Email: </td><td><input type="text" name="email"></td></tr>
<tr><td>phone: </td><td><input type="text" name="phone"></td></tr>
<tr><td></td><td><input type="submit" value="register"></td></tr>
</table>
</form>
</body>
</html>

Need to place the servlet class in a java package. You should always put publicly reusable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself.

Related

Spring: #Valid always returns False

I'm new to Spring Framework. I'm trying to get #Valid to work. Data Binding is happening properly but not the validation. hasErrors() is always returning False in the Controller class. Please see below code.
I'm utilizing Spring 4.1.3 and Hibernate validator 6.0.16.
Context xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:property-placeholder location="classpath:/config.properties"/>
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.personal, com.documentum" />
</beans>
Controller:
package com.personal.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.personal.search.model.SearchForm;
import com.personal.search.service.SearchService;
#Controller
public class SearchController {
private SearchService service;
#Autowired
public SearchController(SearchService service) {
this.service = service;
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String searchHome(Model model) {
model.addAttribute(new SearchForm());
return "search/search";
}
#RequestMapping(value="/", method=RequestMethod.POST)
public String searchResults(#Valid SearchForm searchForm, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
System.out.println(searchForm.getObjectName());
model.addAttribute(service.getResults(searchForm));
}
return "search/search";
}
}
View:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%# page session="false" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<sf:form method="POST" commandName="searchForm">
<sf:errors path="*" />
<label>Enter Object Name:</label>
<sf:input path="objectName"/><sf:errors path="objectName" /><br>
<button type="submit" value="Submit">Submit</button>
</sf:form>
<h3>For your search term "${searchForm.objectName}" below are the results: </h3>
<c:forEach items="${searchResultList}" var="searchResult" >
<li>
<div>
<span>
(<c:out value="${searchResult.objectName}" />,
<c:out value="${searchResult.title}" />)</span>
</div>
</li>
</c:forEach>
</body>
</html>
Model:
SearchForm Model:
package com.personal.search.model;
import javax.validation.constraints.NotBlank;
public class SearchForm {
#NotBlank
private String objectName;
public SearchForm() {
}
public SearchForm(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
SearchResult Model:
package com.personal.search.model;
public class SearchResult {
private String objectName;
private String title;
public SearchResult() {
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String name) {
this.objectName = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Service:
package com.personal.search.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.personal.search.dao.SearchDAO;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Service
public class SearchService implements ISearchService {
private SearchDAO dao;
public SearchService() {
}
#Autowired
public SearchService(SearchDAO dao) {
this.dao = dao;
}
#Override
public List<SearchResult> getResults(SearchForm searchform) {
return dao.getSearchObjects(searchform);
}
}
DAO:
package com.personal.search.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import com.documentum.com.DfClientX;
import com.documentum.fc.client.DfServiceException;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Repository
public class SearchDAO {
private String repository;
private String userName;
private String password;
private IDfSessionManager sessionMgr = null;
public SearchDAO() {
}
#Autowired
public SearchDAO(
#Value("${docbase.repository}") String repository,
#Value("${docbase.user}") String userName,
#Value("${docbase.password}") String password)
{
this.repository = repository;
this.userName = userName;
this.password = password;
System.out.println(repository + " " + userName + " " + password);
}
/**
* Creates a IDfSessionManager
*/
private IDfSessionManager getSessionManager()
{
// create a client object using a factory method in DfClientX
DfClientX clientx = new DfClientX();
IDfClient client;
IDfSessionManager sessionMgr = null;
try {
client = clientx.getLocalClient();
// call a factory method to create the session manager
sessionMgr = client.newSessionManager();
addIdentity(clientx, sessionMgr);
} catch (DfException e) {
e.printStackTrace();
}
return sessionMgr;
}
private void addIdentity(DfClientX clientx, IDfSessionManager sessionMgr)
{
// create an IDfLoginInfo object and set its fields
IDfLoginInfo loginInfo = clientx.getLoginInfo();
loginInfo.setUser(userName);
loginInfo.setPassword(password);
if (sessionMgr != null) {
if (sessionMgr.hasIdentity(repository))
{
sessionMgr.clearIdentity(repository);
}
}
try {
sessionMgr.setIdentity(repository, loginInfo);
} catch (DfServiceException e) {
e.printStackTrace();
}
}
public IDfSession getDBSession() {
IDfSession sess = null;
// Get a session using a factory method of session manager.
try {
sess = sessionMgr.getSession(repository);
} catch (DfServiceException e) {
System.out.println(e.getStackTraceAsString());
}
return sess;
}
public void releaseDBSession(IDfSession sess) {
sessionMgr.release(sess);
}
public List<SearchResult> getSearchObjects(SearchForm searchform) {
List<SearchResult> lst = new ArrayList<SearchResult>();
this.sessionMgr = getSessionManager();
IDfSession sess = null;
try
{
sess = getDBSession();
if (sess != null) {
IDfQuery query = new DfClientX().getQuery();
String dqlStr = "select object_name, title from dm_sysobject where object_name like '%" + searchform.getObjectName() + "%'";
System.out.println(dqlStr);
query.setDQL(dqlStr);
IDfCollection co = query.execute(sess, IDfQuery.DF_READ_QUERY);
while (co.next()) {
SearchResult searchresult = new SearchResult();
searchresult.setObjectName(co.getString("object_name"));
searchresult.setTitle(co.getString("title"));
lst.add(searchresult);
}
if (co != null)
co.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (sess != null)
releaseDBSession(sess);
}
return lst;
}
}
I expect the hasErrors() output to be True.
This could be because you have defined the validation as,
#Null
#Size(min=1, max=30)
private String objectName;
Check if when you submit the request to controller the objectName has NULL value or empty string?
For String you must use #NotBlank and not #Null

ClassNotFoundException loading filter

So I have a really simple java EE Web App. It is composed of a Servlet and a jsp.
Servlet is in a package named "Servlets". Filter in another one named "Filters".
Filter is something like this :
#WebFilter(filterName="AuthFilter",
urlPatterns={"/ProgettoWeb2018/*","/profile/*"})
public class AuthFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Hello from filter");
}
}
Now with this set up i get the following error :
java.lang.ClassNotFoundException: Filters.AuthFilter
If i move the filter in the "Servlets" package it works fine tho.
How come?
For better understanding purpose Servlet Filter project view is as follows:
Servlet class is:
package com.whodesire.demos;
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;
#WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WelcomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + request.getParameter("username") + ", Welcome to Secured Servlet<h1>");
out.println("<hr/>");
out.close();
}
}
Servlet Filter class is:
package com.whodesire.demos;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
#WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {
public AuthenticationFilter() { }
public void destroy() {
System.out.println("destroy method is called in " + this.getClass().getName());
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("init method is called in " + this.getClass().getName());
String username = request.getParameter("username");
String password = request.getParameter("passwd");
String ipAddress = request.getRemoteAddr();
System.out.println("\n username and password is : " + username + ", " + password + "\n");
//Either you can write source here to fetch here DAO object for validation
if(username.equals("wsuser") && password.equals("wspassword")) {
System.out.println("User logged in " + ipAddress + " at " + (new Date().toString()));
// pass the request along the filter chain
chain.doFilter(request, response);
}else {
//if failed the servlet filter validation
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Login request rejected in " + ipAddress + " at " + (new Date().toString()) + "</h2>");
out.close();
}
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("init method is called in " + this.getClass().getName());
}
}
Login.html initial page along with CSS(placed as login.css):
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="login.css"/>
<title>Login Form</title>
</head>
<body>
<h2>User Login Form</h2>
<hr/>
<form name="loginForm" method="POST" action="WelcomeServlet">
<div class="login">
<input type="text" placeholder="Username" name="username"/>
<input type="password" placeholder="Password" name="passwd"/>
<input type="submit" value="Login"/>
forgot password?
</div>
</form>
</body>
</html>
#charset "ISO-8859-1";
h2 {
display: block;
font-size: 1.8em;
font-family: sans-serif;
margin-top: 0.83em;
margin-bottom: 0.83em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
.login {
height:110px;
width:190px;
margin:auto;
border:1px #CCC solid;
padding:10px;
}
.login input {
padding:5px;
margin:5px
}
and finally the web.xml Servlet dispatcher configuration:
<?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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>servletFilterDemo</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Authentication</filter-name>
<filter-class>com.whodesire.demos.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Authentication</filter-name>
<url-pattern>/WelcomeServlet</url-pattern>
</filter-mapping>
</web-app>
Hope this will give you a simple insight on Servlet Filter example.

Unable to print from ArrayList of Objects using JSTL [duplicate]

This question already has answers here:
javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
(3 answers)
Closed 6 years ago.
MainServ.java
package servs.com;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 serv.com.Users;
#WebServlet(name="mainServ",urlPatterns={"/mainServ"})
public class haha extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// JDBC driver name and database URL
final String DB_URL="jdbc:mysql://localhost/test";
// Database credentials
final String USER = "root";
final String PASS = "root";
Connection conn = null;
Statement stmt = null;
ArrayList<Users> usersArr = new ArrayList<Users>();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
Users u = new Users();
u.setAge(age);
u.setId(id);
u.setFirst(first);
u.setLast(last);
usersArr.add(u);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
request.setAttribute("users", usersArr);
request.getRequestDispatcher("NewFile.jsp").forward(request,response);
System.out.println(usersArr.size());
}
}
NewFile.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${users}" var="rowss">
<c:forEach items="${rowss}" var="item">
<c:out value="${item}"/>
</c:forEach>
</c:forEach>
<!--
<c:forEach var="user" items="${users}">
<c:out value="${users.first}"/>
<c:out value="${users.last}"/>
<c:out value="${users.ageIp}"/>
<c:out value="${users.id}"/>
</c:forEach>
-->
</body>
</html>
Users.java
package servs.com;
final public class Users {
private int id;
private int age;
private String first;
private String last;
public void setId(int i){
this.id=i;
}
public void setAge(int i){
this.age=i;
}
public void setFirst(String i){
this.first=i;
}
public void setLast(String i){
this.last=i;
}
}
When I am trying to print in NewFile.jsp I am getting following error.
javax.servlet.jsp.JspTagException: Don't know how to iterate over
supplied "items" in <forEach>
I don't know the error is in printing or I am doing something wrong while putting the objects into the Arraylist (userArr). I am getting the data successfully out of the database as I did print it first.
Could you please let me know what I can modify in order to print the data. I would be open If there is any different approach for the same.
After adding Getter methods in class Users the issue was resolved. But I still Havea doubt I never used getter methods anywhere. How come getter methods played any role.??
public String getFirst(){
return this.first;
}
public String getLast(){
return this.last;
}
public int getId(){
return this.id;
}
public int getAge(){
return this.age;
}
This is what I appended at the end of Users.java

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();
...

confusion on servlet config

In Myeclipse I created a web project called web1,and added a servlet called servlet1,the web.xml is as followed:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
but when I typed the address:http://localhost:8080/web/test in the browser,it didn't work.I tried many times but have no answer.what's the problem?thanks a lot!
Here is the code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6214906967399177511L;
/**
* Constructor of the object.
*/
public servlet1() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* #throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Well as usual, you forgot to say super.init(config);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
You're servlet never got initialized, because you overrode method, and forgot to call parents' init.
That's why, if you do not know the internals, do NOT override anything, except if you're sure what are you doing.

Resources