I am able to get the Custom 404 Error Page if I include webApp root directory myweb in the URL path -
http://localhost/myweb/users/david
I added the following entry in web.xml to get custom 404 page -
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/pageNotFound.jsp</location>
</error-page>
However, I am still getting Spring default 404 Error Page when I hit the following URL -
http://localhost/users/david
Why it is not working without webApp root directory in the URL path? Is there any way to get same custom 404 Not Found Page for this as well?
EDIT:
My relevant web.xml code -
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myweb</param-value>
</context-param>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>com.gridpoint.energy.web.common.servlet.listeners.RequestContextInitializer</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- Dispatch Servlet -->
<servlet>
<servlet-name>services-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>services-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>services-servlet</servlet-name>
<url-pattern>/applications/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>services-servlet</servlet-name>
<url-pattern>/healthCheck</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/pageNotFound.jsp</location>
</error-page>
In my case I created customer controller ErrorController using Spring mvc 4.
I set next configuration web.xml.
<error-page>
<location>/errors</location>
</error-page>
Next. I created the controller. I shared the class. (ModelAndView is the path of my .jsp (exception/errorPage)).
#Controller
public class ErrorController {
#RequestMapping(value = "errors", method = RequestMethod.GET)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest, ModelMap model) {
ModelAndView errorPage = new ModelAndView("exception/errorPage");
String errorMsg = "";
String customerMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code: 400. Bad Request";
customerMsg = "";
break;
}
case 401: {
errorMsg = "Http Error Code: 401. Unauthorized";
customerMsg = "";
break;
}
case 403: {
errorMsg = "Http Error Code: 403. access denied";
customerMsg = "";
break;
}
case 404: {
errorMsg = "Http Error Code: 404. Resource not found";
customerMsg = "";
break;
}
case 500: {
errorMsg = "Http Error Code: 500. Internal Server Error";
customerMsg = "";
break;
}
}
errorPage.addObject("errorMsg", errorMsg);
errorPage.addObject("customerMsg", customerMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest
.getAttribute("javax.servlet.error.status_code");
}
}
Shared the basic errorPage.jsp
<!DOCTYPE html>
<html lang="es">
<head>
<title>Error</title>
</head>
<body>
<table>
<tr>
<td>
<h1>${errorMsg}</h1>
</td>
</tr>
<tr>
<td>
<h1>${customerMsg}</h1>
</td>
</tr>
<tr>
</tr>
</table>
</body>
</html>
I hope this example to help you.
Related
I was trying to use the facebook API to post a message to share a page I am making as a project to learn to use APIs.
And I'm running into the following problem.
I tried to post and I was redirected to facebook where I accepted a bunch of permisions and then I was redirected to the url "MyUrl/oauth2callback/Facebook?code=A very large code" and got a 404 Not Found error.
I'm not sure what the problem is and I have been trying to find it for the past 3 days, here is the resource I am using:
import org.restlet.resource.ClientResource;
public class FacebookPostResource {
private String uri = "https://graph.facebook.com/me/feed";
private String access_token = null;
public FacebookPostResource(String access_token) {
this.access_token = access_token;
}
public boolean publishPost(String message){
String normalizedMessage=message.replace(' ', '+');
ClientResource cr=new ClientResource(uri+"?access_token="+access_token);
cr.post("message="+normalizedMessage);
return true;
}
}
Here is the Controller:
public class FacebookPostController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6818025976353856770L;
private static final Logger log =
Logger.getLogger(FacebookPostController.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
String accessToken=(String)req.getSession().getAttribute("Facebook-
token");
if(accessToken!=null && !"".equals(accessToken)){
FacebookPostResource fbResource=new
FacebookPostResource(accessToken);
fbResource.publishPost(req.getParameter("message"));
req.getRequestDispatcher("/").forward(req,resp);
}else{
log.info("Trying to acces to Facebook without an acces token,
redirecting to OAuth servlet");
req.getRequestDispatcher("/AuthController/Facebook").forward(req,resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
doGet(req,resp);
}
}
Here is My scope configuration:
{
"Facebook":{
"tokenUrl":"https://graph.facebook.com/v2.8/oauth/access_token",
"clientId":"MyID",
"clientSecret":"MySecret" ,
"authorizationFormUrl":"https://www.facebook.com/v2.8/dialog/oauth",
"scopes":["user_posts", "user_friends"]
}
}
Here is the JSP where I write the post:
<c:if test='${empty sessionScope["Facebook-token"]}'>
<c:redirect url = "/AuthController/Facebook"/>
</c:if>
<h1>Publicar Post en Facebook</h1>
<div class="container">
<p class="message"></p>
<form action="/facebookPostCreation" method="post">
Mensaje: <textarea name="message"></textarea>
<br>
<div class="bottom_links">
<button type="submit" class="button">Publicar en
Facebook</button>
<button type="button"
onClick="javascript:window.location.href='index.html'"
class="button">Cancel</button>
</div>
</form>
</div>
And finally here is my web.xml
...
<servlet>
<servlet-name>FacebookPostCreation</servlet-name>
<servlet-class>aiss.controller.FacebookPostController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FacebookPostCreation</servlet-name>
<url-pattern>/facebookPostCreation</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookAuthController</display-name>
<servlet-name>FacebookAuthController</servlet-name>
<servlet-class>aiss.controller.oauth.GenericAuthController</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookAuthController</servlet-name>
<url-pattern>/AuthController/Facebook</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookOAuth2Callback</display-name>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<servlet-class>aiss.controller.oauth.OAuth2Callback</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
<init-param>
<param-name>onSuccess</param-name>
<param-value>redirect:/facebookFriendsListing</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<url-pattern>/OAuth2Callback/Facebook</url-pattern>
</servlet-mapping>
Try using my code
https://github.com/OswaldoRosalesA/FacebookAPIJava.git
Use Debuger.java to Test.
I use the Graph API
https://developers.facebook.com/docs/graph-api
I have a from and when the form is filled and submitted I wanted the request to be http://localhost:8080/restroo/admin/adminLog but it gives http://localhost:808/adminLogand getting 404 error. I don't know why I am having this problem and actually I was having problem in using two controllers in spring.
web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have spring-servlet.xml
admin.jsp
<form method="post" action="/adminLog" modelAttribute="adminUser">
First Name: <input type = "text" name = "userName">
<br />
password <input type = "password" name = "password" />
<input type = "submit" value = "Submit" />
</form>
AdminPageController.java
#Controller
#RequestMapping("/admin/*")
public class AdminPageController {
#Autowired
AdminUser adminUser;
#Autowired
MenuItems menuItems;
#Autowired
MenuItemsDao menuItemsDao;
#Autowired
AdminLoginDao adminLoginDao;
#RequestMapping(value="", method=RequestMethod.GET)
public ModelAndView addMenuItems(#ModelAttribute MenuItems menuItems){
// if(menuItems != null){
// menuItemsDao.addItems(menuItems);
// }
return new ModelAndView("admin");
}
#RequestMapping(value="/adminLog", method=RequestMethod.POST)
public ModelAndView adminLogin(#ModelAttribute("adminUser") AdminUser ad){
List<AdminUser> adminUser = adminLoginDao.adminLogin();
int len = adminUser.size();
for(int i=1;i<=len;i++){
String userN = adminUser.get(i).getUserName();
String pass = adminUser.get(i).getPassword();
if(userN.equals(ad.getUserName()) && (pass.equals(ad.getPassword()))){
return new ModelAndView("adminLogin");
}
}
return new ModelAndView("admin");
}
}
You are using Internal Resource View Resolver It is not able fetch view Not In Web-INF Floader.
Find This http://www.baeldung.com/spring-mvc-view-resolver-tutorial.
You have to change servlet mapping by adding a prefix for the API of the whole app:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/restroo</url-pattern>
</servlet-mapping>
I am getting the following error when I click on 'Add To Cart'.
PUT http://localhost:8080/emusicstore/rest/cart/add/97 403 ()
viewProduct.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<div class="page-header">
<h1>Product Detail</h1>
<p class="lead">Here is the detail information of the product!</p>
</div>
<div class="container" ng-app = "cartApp">
<div class="row">
<div class="col-md-5">
<img src="<c:url value="/resources/images/${product.productId}.png" /> " alt="image"
style="width:100%"/>
</div>
<div class="col-md-5">
<h3>${product.productName}</h3>
<p>${product.productDescription}</p>
<p>
<strong>Manufacturer</strong> : ${product.productManufacturer}
</p>
<p>
<strong>Category</strong> : ${product.productCategory}
</p>
<p>
<strong>Condition</strong> : ${product.productCondition}
</p>
<h4>${product.productPrice} USD</h4>
<br>
<c:set var="role" scope="page" value="${param.role}" />
<c:set var="url" scope="page" value="/productList" />
<c:if test="${role='admin'}">
<c:set var="url" scope="page" value="/admin/productInventory" />
</c:if>
<p ng-controller="cartCtrl">
Back
<a href="#" class="btn btn-warning btn-large"
ng-click="addToCart('${product.productId}')"><span
class="glyphicon glyphicon-shopping-cart"></span>Add To Cart</a>
<span class="glyphicon glyphicon-hand-right"></span>View Cart
</p>
</div>
</div>
</div>
<script src="<c:url value="/resources/js/controller.js" /> "></script>
controller.js
var cartApp = angular.module ("cartApp", []);
cartApp.controller("cartCtrl", function ($scope, $http){
$scope.refreshCart = function (cartId) {
$http.get('/emusicstore/rest/cart/'+$scope.cartId).success(function (data) {
$scope.cart=data;
});
};
$scope.clearCart = function () {
$http.delete('/emusicstore/rest/cart/'+$scope.cartId).success($scope.refreshCart($scope.cartId));
};
$scope.initCartId = function (cartId) {
$scope.cartId = cartId;
$scope.refreshCart(cartId);
};
$scope.addToCart = function (productId) {
$http.put('/emusicstore/rest/cart/add/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
alert("Product successfully added to the cart!")
});
};
$scope.removeFromCart = function (productId) {
$http.put('/emusicstore/rest/cart/remove/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
});
};
});
CartController.java
package com.store.emusicstore.controller;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.store.emusicstore.dao.CartDao;
import com.store.emusicstore.dao.ProductDao;
import com.store.emusicstore.model.Cart;
import com.store.emusicstore.model.CartItem;
import com.store.emusicstore.model.Product;
#Controller
#RequestMapping("/rest/cart")
public class CartController {
#Autowired
private CartDao cartDao;
#Autowired
private ProductDao productDao;
#RequestMapping(value="/{cartId}" , method = RequestMethod.GET)
public #ResponseBody Cart read(#PathVariable(value ="cartId") String cartId){
return cartDao.read(cartId);
}
#RequestMapping(value="/{cartId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void update(#PathVariable(value = "cartId" ) String cartId, #RequestBody Cart cart) {
cartDao.update(cartId, cart);
}
#RequestMapping(value = "/{cartId}", method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(#PathVariable(value="cartId") String cartId) {
cartDao.delete(cartId);
}
#RequestMapping(value="/add/{productId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(#PathVariable (value = "productId") String productId, HttpServletRequest request) {
System.out.println("Inside addItem()");
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
if(cart == null) {
cart = cartDao.create(new Cart(sessionId));
}
Product product = productDao.getProductById(Long.valueOf(productId));
if (product == null) {
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
#RequestMapping(value="/remove/{productId}", method=RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void removeItem(#PathVariable Long productId, HttpServletRequest request) {
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
Product product = productDao.getProductById(productId);
if (product == null || cart == null) {
throw new IllegalArgumentException(new Exception());
}
cart.removeCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
#ExceptionHandler(IllegalArgumentException.class)
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal request, please verify your payload")
public void handleClientErrors(Exception e){}
#ExceptionHandler(Exception.class)
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server")
public void handleServerErrors(Exception e){}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Things I have tried inorder to resolve this but DID NOT WORK :
Set 'readonly' as false in tomcat's web.xml
Disabled csrf by adding
security:csrf disabled="true"
in root-context inside security:http tag.
Added CorsFilter
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,authorization,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
I am still not able to get rid of the 403 error when it sends the put request.
I don't know if that is the problem, but just from reading your code:
in your js:
$scope.addToCart = function (productId) {
$http.put('/emusicstore/rest/cart/add/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
alert("Product successfully added to the cart!")
});};
and in your java:
#RequestMapping(value="/add/{productId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(#PathVariable (value = "productId") String productId, HttpServletRequest request) {
System.out.println("Inside addItem()");
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
if(cart == null) {
cart = cartDao.create(new Cart(sessionId));
}
Product product = productDao.getProductById(Long.valueOf(productId));
if (product == null) {
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
you're java returns no data in the response, but in the js your function expects the data.
note that 403 is usually bad mapping or security issues.
This is my login part which I need to compare user input with data in the database.
So If a lecturer tries to enter the system, he or she will get into lecturer interface(lecturer.html) and same goes to the student.
But right now, when I try to enter the system using either lecturer or student ID, the system will direct me to the log in interface.
I hope someone can help me to solve this :)
This is the query for Java DB (LogIn.java)
public class LogIn extends HttpServlet {
static final String dbURI = "jdbc:derby://localhost:1527/webdb";
String str = SELECT DEMO.REGISTRATION.*, \n" +
DEMO.STUDENT.STUD_PASSWORD,DEMO.LECTURER.LECT_PASSWORD
FROM DEMO.REGISTRATION
LEFT OUTER JOIN DEMO.STUDENT
ON REGISTRATION.STUDENT_ID = STUDENT.STUDENT_ID
LEFT OUTER JOIN DEMO.LECTURER
ON REGISTRATION.LECTURER_ID = LECTURER.LECTURER_ID;";
Connection theConnection = null;
And this is the rest of codes (LogIn.java)
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String matricI = request.getParameter("matricin");
String passwordI = request.getParameter("passwordin");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>\n" +
" <head>\n" +
" <title>SPEDT | UKM</title>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
" <link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\">\n" +
" <link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css\">\n" +
" <script src=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js\"></script>\n" +
" </head>\n" +
" \n" +
" <body>\n" +
" \n" +
" <div class=\"navbar navbar-inverse \" role=\"navigation\">\n" +
" <div class=\"container\">\n" +
" <div class=\"navbar-header\">\n" +
" <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\">\n" +
" <span class=\"sr-only\">Toggle navigation</span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" </button>\n" +
" <a class=\"navbar-brand\" href=\"#\">Sistem Penilaian Esei Dalam Talian</a>\n" +
" </div>\n" +
" <div class=\"navbar-collapse collapse\">\n" +
" <form class=\"navbar-form navbar-right\" role=\"form\" method=\"get\" action=\"http://localhost:8080/Spedt/LogIn\">\n" +
" <a class=\"btn btn-danger\" role=\"button\" href=\"http://localhost:8080/Spedt/start.html\">Keluar</a>\n" +
" </form>\n" +
" </div><!--/.navbar-collapse -->\n" +
" </div>\n" +
" </div>\n" +
"</html>");
// Load database driver
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException cnfe){
System.out.println(cnfe);
}
// Create a Connection to contacts db Data source
try {
theConnection = DriverManager.getConnection(dbURI,"demo","demo");
} catch (SQLException sqle) {
System.out.println(sqle);
}
// prepare statement for inserting data into table
try {
PreparedStatement theStatement=theConnection.prepareStatement(str);
request.setAttribute("matricin",matricI);
request.setAttribute("passwordin",passwordI);
Statement st = theConnection.createStatement();
ResultSet rs = st.executeQuery(str);
String m = matricI;
String p = passwordI;
while (rs.next()) {
String matricS = rs.getString("STUDENT_ID");
String passwordS = rs.getString("STUD_PASSWORD");
String matricL = rs.getString("LECTURER_ID");
String passwordL = rs.getString("LECT_PASSWORD");
if(m.equals(matricS) && p.equals(passwordS)){
response.sendRedirect("http://localhost:8080/Spedt/StudentInput");
return;}
else if(m.equals(matricL) && p.equals(passwordL)){
response.sendRedirect("http://localhost:8080/Spedt/Lecturer.html");
return;}
else {
out.println("<p class=\"bg-danger container\">Sila masukkan No. Matrik dan Kata Laluan yang betul !</p>");
}
}
}
catch (SQLException sqle) {
System.out.println(sqle);
}
theConnection.close(); //Close database Connection
}catch(Exception e) {
out.println(e.getMessage());//Print trapped error.
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
and this is the html
<form class="navbar-form navbar-right" role="form" method="get" action="http://localhost:8080/Spedt/LogIn">
<div class="form-group">
<input type="text" name="matricin" placeholder="No. Matrik" class="form-control">
</div>
<div class="form-group">
<input type="password" name="passwordin" placeholder="Kata Laluan" class="form-control">
</div>
<button type="submit" class="btn btn-success">Masuk</button>
</form>
This is my web.xml
<?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>InputData</servlet-name>
<servlet-class>mypkg.InputData</servlet-class>
</servlet>
<servlet>
<servlet-name>GetData</servlet-name>
<servlet-class>mypkg.GetData</servlet-class>
</servlet>
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>mypkg.LogIn</servlet-class>
</servlet>
<servlet>
<servlet-name>Lecturer</servlet-name>
<servlet-class>mypkg.Lecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>mypkg.Student</servlet-class>
</servlet>
<servlet>
<servlet-name>LogOut</servlet-name>
<servlet-class>mypkg.LogOut</servlet-class>
</servlet>
<servlet>
<servlet-name>LecturerInput</servlet-name>
<servlet-class>mypkg.LecturerInput</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataLecturer</servlet-name>
<servlet-class>mypkg.GetDataLecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>mypkg.NewServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>InputLecturer</servlet-name>
<servlet-class>mypkg.InputLecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataLect</servlet-name>
<servlet-class>mypkg.GetDataLect</servlet-class>
</servlet>
<servlet>
<servlet-name>StudentInput</servlet-name>
<servlet-class>mypkg.StudentInput</servlet-class>
</servlet>
<servlet>
<servlet-name>InputStudent</servlet-name>
<servlet-class>mypkg.InputStudent</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataStud</servlet-name>
<servlet-class>mypkg.GetDataStud</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InputData</servlet-name>
<url-pattern>/InputData</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetData</servlet-name>
<url-pattern>/GetData</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogIn</servlet-name>
<url-pattern>/LogIn</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Lecturer</servlet-name>
<url-pattern>/Lecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogOut</servlet-name>
<url-pattern>/LogOut</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LecturerInput</servlet-name>
<url-pattern>/LecturerInput</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataLecturer</servlet-name>
<url-pattern>/GetDataLecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InputLecturer</servlet-name>
<url-pattern>/InputLecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataLect</servlet-name>
<url-pattern>/GetDataLect</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>StudentInput</servlet-name>
<url-pattern>/StudentInput</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InputStudent</servlet-name>
<url-pattern>/InputStudent</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataStud</servlet-name>
<url-pattern>/GetDataStud</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I hope someone can help me to solve this problem.thanks :)
In your code you don't need to specify full URL in action you can just Specify abc.jsp or ServletName which is there in web.xml.
<form class="navbar-form navbar-right" role="form" method="get" action="LogIn">
Secondly you need to specify onClick in Submit button of your form.
<button type="submit" class="btn btn-success" onclick="action">Masuk</button>
EDIT
I'm getting this, every time I try to log in.
localhost:8080/Spedt/LogIn?matricin=A138&passwordin=92
So it's working and you need to do some stuff in your LogIn Servlet as your doGet method is Empty and better to Use POST for LogIn!!!
ohhh..
In this case control is not reaching to servlet so how would you expect to run redirect!!
In action part of your html you have written action="http://localhost:8080/Spedt/LogIn"
you should use action for your servlet which you have define in web.xml file
see your xml file is
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>mypkg.LogIn</servlet-class>
</servlet>
if your write action=LogIn then you will go to mypkg.LogIn servlet
I have below config in web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
I have controller as below.
#Controller
public class SomeController {
#RequestMapping(value = "/getData", method = RequestMethod.GET)
public ModelAndView showExtendedUi(#RequestParam("geo") String geo, #RequestParam("tab") String tab, #RequestParam("gid") String gid, HttpServletResponse response) {
//logic
}
}
Now how can i specify URL in jquery ajax call?
$.ajax({
type: "GET",
url: "getData.do",
dataType: "json",
success: function(responseJson) {
alert("json"+responseJson);
},
error: function(xhr, status, error) {
alert('Failed to get details: ' + error);
}
});
From looking at the code above, you should just be able to go to the following url (assuming 8080 port as default Tomcat port).
http://localhost:8080/getData.do?geo=1&tab=1&gid=1
This should show you in a browser the JSON you require. If the JSON appears on the page here, just do $.getJSON() from jQuery as it has built in methods for pulling back JSON. You can see the documentation on this method here.