I was creating a quiz application in java to host on Google App Engine. However when I am trying to Deploy it, it gives an error that unable to compile JSP java Class. Even if I try to upload a blank JSP. On local server, everything works fine.
The error is shown below.
Console Error on Eclipse:
------------ Deploying frontend ------------
Preparing to deploy:
Created staging directory at:
'/var/folders/2y/f99pqznd5m3g21gbjl7rgjc40000gn/T/appcfg966104224651839827.tmp'
Scanning for jsp files.
Compiling jsp files.
com.google.appengine.tools.admin.JspCompilationException: Failed to
compile the generated JSP java files. Sep 02, 2015 6:35:38 PM
org.apache.jasper.JspC processFile INFO: Built File: /index.jsp
Debugging information may be found in
/private/var/folders/2y/f99pqznd5m3g21gbjl7rgjc40000gn/T/appengine-deploy2339970973769784997.log
I have already tried to find solution regarding this. However no success till now.
The JSP file is shown below. Its not doing anything, still I am getting the error:
index.jsp
<html>
<head>
<meta charset="UTF-8">
<title>TechnoQuiz | Registration</title>
<meta
content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
name='viewport'>
<link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet"
type="text/css" />
<link
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"
rel="stylesheet" type="text/css" />
<link href="../../dist/css/AdminLTE.min.css" rel="stylesheet"
type="text/css" />
</head>
<body class="register-page"
style="background-repeat: repeat; background-image: url('dist/img/carbon_pattern.png');">
<div class="register-box">
<div class="register-box-body">
<div class="register-logo">
<a><b>ZapQuiz</b>.Space</a>
</div>
<hr>
<p class="login-box-msg">Please fill in the details below</p>
<form name="regform">
<div class="form-group has-feedback">
<input name="fullname" type="text" class="form-control"
placeholder="Full name" /> <span
class="glyphicon glyphicon-user form-control-feedback"></span>
<p id="err1" class="text-red hidden">Can't be Empty</p>
</div>
<div id="email" class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email"
required /> <span
class="glyphicon glyphicon-envelope form-control-feedback"></span>
<p id="err2" class="text-red hidden">Can't be Empty</p>
</div>
<div id="phone" class="form-group has-feedback">
<input type="tel" class="form-control" placeholder="Phone" /> <span
class="glyphicon glyphicon-phone form-control-feedback"></span>
<p id="err3" class="text-red hidden">Can't be Empty</p>
</div>
<div class="row">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
</div>
</div>
<hr>
<p class="login-box-msg">
Powered by <strong>Xibeat Technologies</strong>
</p>
</form>
</div>
</div>
<script src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="../../bootstrap/js/bootstrap.min.js"
type="text/javascript"></script>
</body>
</html>
I tried to resolve the issue by going through the generated Java class in the Temp Directory. However, I don't see anything wrong.
Generated JAVA class by AppEngine in the Temp Directory
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<html>\n<head>\n<meta charset=\"UTF-8\">\n<title>TechnoQuiz | Registration</title>\n<meta\n\tcontent='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'\n\tname='viewport'>\n\n<link href=\"../../bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\"\n\ttype=\"text/css\" />\n<link\n\thref=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\"\n\trel=\"stylesheet\" type=\"text/css\" />\n<link href=\"../../dist/css/AdminLTE.min.css\" rel=\"stylesheet\"\n\ttype=\"text/css\" />\n\n</head>\n<body class=\"register-page\"\n\tstyle=\"background-repeat: repeat; background-image: url('dist/img/carbon_pattern.png');\">\n\t<div class=\"register-box\">\n\n\t\t<div class=\"register-box-body\">\n\t\t\t<div class=\"register-logo\">\n\t\t\t\t<a><b>ZapQuiz</b>.Space</a>\n\t\t\t</div>\n\t\t\t<hr>\n\t\t\t<p class=\"login-box-msg\">Please fill in the details below</p>\n\n\t\t\t<form name=\"regform\">\n\n\t\t\t\t<div class=\"form-group has-feedback\">\n\t\t\t\t\t<input name=\"fullname\" type=\"text\" class=\"form-control\"\n\t\t\t\t\t\tplaceholder=\"Full name\" /> <span\n\t\t\t\t\t\tclass=\"glyphicon glyphicon-user form-control-feedback\"></span>\n");
out.write("\t\t\t\t\t<p id=\"err1\" class=\"text-red hidden\">Can't be Empty</p>\n\n\t\t\t\t</div>\n\t\t\t\t<div id=\"email\" class=\"form-group has-feedback\">\n\t\t\t\t\t<input type=\"email\" class=\"form-control\" placeholder=\"Email\"\n\t\t\t\t\t\trequired /> <span\n\t\t\t\t\t\tclass=\"glyphicon glyphicon-envelope form-control-feedback\"></span>\n\t\t\t\t\t<p id=\"err2\" class=\"text-red hidden\">Can't be Empty</p>\n\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"phone\" class=\"form-group has-feedback\">\n\t\t\t\t\t<input type=\"tel\" class=\"form-control\" placeholder=\"Phone\" /> <span\n\t\t\t\t\t\tclass=\"glyphicon glyphicon-phone form-control-feedback\"></span>\n\t\t\t\t\t<p id=\"err3\" class=\"text-red hidden\">Can't be Empty</p>\n\t\t\t\t</div>\n\n\t\t\t\t<div class=\"row\">\n\n\t\t\t\t\t<div class=\"col-xs-12\">\n\t\t\t\t\t\t<button type=\"submit\" class=\"btn btn-primary btn-block btn-flat\">Register</button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<hr>\n\t\t\t\t<p class=\"login-box-msg\">\n\t\t\t\t\tPowered by <strong>Xibeat Technologies</strong>\n\t\t\t\t</p>\n\n\t\t\t</form>\n\n\t\t</div>\n\n\t</div>\n\n\n\n\t<script src=\"../../plugins/jQuery/jQuery-2.1.4.min.js\"></script>\n\t<script src=\"../../bootstrap/js/bootstrap.min.js\"\n");
out.write("\t\ttype=\"text/javascript\"></script>\n\n\n\n</body>\n</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
Finally, Here is the AppEngine-web.xml File and Web.xml file. In case it may come handy.
appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>zapquiz-1054</application>
<version>1</version>
<!--
Allows App Engine to send multiple requests to one instance in parallel:
-->
<threadsafe>true</threadsafe>
<!-- Configure java.util.logging -->
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
</system-properties>
</appengine-web-app>
web.xml
<?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" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thanks and Regards,
Prasun
UPDATE: Log file is shown below
Unable to update:
com.google.appengine.tools.admin.JspCompilationException: Failed to
compile the generated JSP java files. at
com.google.appengine.tools.admin.Application.compileJavaFiles(Application.java:854)
at
com.google.appengine.tools.admin.Application.compileJsps(Application.java:815)
at
com.google.appengine.tools.admin.Application.createStagingDirectory(Application.java:629)
at
com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:509)
at
com.google.appengine.tools.admin.AppAdminImpl.update(AppAdminImpl.java:55)
at
com.google.appengine.eclipse.core.proxy.AppEngineBridgeImpl.deploy(AppEngineBridgeImpl.java:433)
at
com.google.appengine.eclipse.core.deploy.DeployProjectJob.runInWorkspace(DeployProjectJob.java:158)
at
org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:38)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)
Related
I have a Servlet and jsp project in which it takes the name and pass. when I want it to save it in the MySQL database using JDBC mysql-connector, it shows this error. Please help me I'm stuck in this for a long time.
Screenshots are at the bottom of the page...
I'm using IntelliJ JetBrains and tomcat 10.
__ This is the servlet class 👇 __
#WebServlet(name = "ServletOne", value = "/ServletOne")
public class ServletOne extends HttpServlet {
private Connection con;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
//get all the data incoming from the request(user)..
String name = request.getParameter("user_name");
String password = request.getParameter("user_password");
String email = request.getParameter("user_email");
if (con == null) {
try {
//load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
//create a connection to jdbc
Connection con = DriverManager.getConnection("jdbc:mysql://localhost3306/register", "root", "root");
//query
String q = "insert into user(name, password, email) values(?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(q);
//set values
preparedStatement.setString(1, name);
preparedStatement.setString(2, password);
preparedStatement.setString(3, email);
//fire query
preparedStatement.executeUpdate();
out.println("<br><h1>ur information have been saved into MySQL Database :)</h1>");
} catch (Exception e) {
e.printStackTrace();
out.println("<h3>An Error has occurred while connecting to MySQL Database.</h3>");
}
} else
out.println("Database connection terminated");
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
__ signup.jsp file 👇 __
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>signup</title>
<!-- importing the css materialize library -->
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<body style="background: url(Images/GenshinMona.jpg); background-size: contain; background-attachment: fixed;">
<div class="container">
<div class="row">
<div class="col m6 offset-m3">
<div class="card">
<div class="card-content">
<h3 style="margin-top:10px;" class="center-align">Register Here</h3>
<%--
creating our own form...
** method is for do and post,
** action is for the servlet class name
--%>
<div class="form center-align">
<form method="post" action="ServletOne">
<input type="text" name="user_name" placeholder="Enter your name">
<input type="password" name="user_password" placeholder="Enter your password">
<input type="email" name="user_email" placeholder="Enter your email address">
<br> <br>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right"></i>
</button>
<br> <br>
<button type="reset" class="reset pink darken-4">Reset All</button>
</form>
</div>
<%--creating our own loader i.e. a circle loading thingy--%>
<div class="loader center-align" style="margin-top: 10px; display: none;">
<div class="progress">
<div class="indeterminate"></div>
<h5>Please wait while we save ur data...</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<%--Jquery Library--%>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<%--check to see if the jquery library works or not--%>
<script>
$(document).ready(function() {
console.log("Jquery working properly. Page is ready!")
})
</script>
</body>
</html>
__ index.jsp 👇 __
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<h1><%= "Hello World!" %>
</h1>
<br/>
Hello Servlet
</body>
</html>
__ web.xml 👇 __
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
</web-app>
When I comment out the jdbc part, and let's say I want to show all the info, it'll work. But when I want to save it in the database, it refuses and throws exception.
like this 👉 out.println(name + password + email);
================================================================
These are the screenshots of it (both the stackTrace and in the web)👇
before submitting:
before submitting..
after submitting..
And the stack traces 👇
before submitting..
after submitting and the exceptions...
sorry the question has gotten really long. really appreciate your answer🙏🙏🙏
Connection con = DriverManager.getConnection("jdbc:mysql://localhost3306/register", "root", "root");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/register", "root", "root");
I started to work with thymeleaf in a basic project. When I want to display a message in the sign up page the th:text does not work. I used already th:text in other .html files and it works there but in the signUp.html doesn't.
Here is my controller where I set the message:
package com.teszt.thymeleaftest.controller;
#Controller
#RequestMapping("/login")
#AllArgsConstructor
public class MemberController {
MembersService membersService;
#GetMapping("/login")
public String showLoginPage(){
return "/login/login";
}
#GetMapping("/signUp")
public String showSignUpPage(Model theModel){
Members theMember = new Members();
theModel.addAttribute("member", theMember);
return "/login/signUp";
}
#PostMapping("/save")
public String saveMember(#ModelAttribute("member") Members theMember, ModelMap modelMap){
Members tempMember = membersService.findByEmail(theMember.getEmail());
if(tempMember != null){
modelMap.addAttribute("error", "Email is already exist!");
return "redirect:/login/signUp";
}else{
membersService.save(theMember);
//prevent duplication
return "redirect:/login/login";
}
}
}
Here is my signUp.html
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title>Signup</title>
</head>
<body>
<div class="container">
<h3>Signup</h3>
<hr>
<p class="h4 mb-4">Signup</p>
<form action="#" th:action="#{/login/save}" th:object="${member}" method="POST">
<input type="text" th:field="*{firstName}" class="form-control mb-4 col-4" placeholder="First name">
<input type="text" th:field="*{lastName}" class="form-control mb-4 col-4" placeholder="Last name">
<input type="text" th:field="*{email}" class="form-control mb-4 col-4" placeholder="Email">
<input type="password" th:field="*{password}" class="form-control mb-4 col-4" placeholder="Password">
<button type="submit" class="btn btn-info col-2">Save</button>
<p th:text="${error}" />
</form>
<br>
Do you have an account? <a th:href="#{/login/login}">Click here</a>
</div>
</body>
</html>
As I mentioned above this is the only html where the th:text does not works, everywhere else is good.
I hope somebody can help me!
When you use a redirect:, you lose all your model attributes (because it's loading a new page). You need to use a FlashAttribute instead. Like this:
#PostMapping("/save")
public String saveMember(#ModelAttribute("member") Members theMember, ModelMap modelMap, RedirectAttributes redirAttrs){
Members tempMember = membersService.findByEmail(theMember.getEmail());
if(tempMember != null){
redirAttrs.addFlashAttribute("error", "Email is already exist!");
return "redirect:/login/signUp";
}else{
membersService.save(theMember);
//prevent duplication
return "redirect:/login/login";
}
}
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
My web program will allow a user to enter first name and last name and after the user press the submit button, it will print the first name and last name.
I receive an HTTP error 404 after the user presses the "Submit" button.
Error
This is my File structure
My codes
PrintFormContent.java
package form;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
#WebServlet("/PrintFormContent")
public class PrintFormContent extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PrintFormContent() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fname = request.getParameter("name");
String lname = request.getParameter("lname");
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>First Name</p>" + fname);
out.print("<p>Last Name</p>" + lname);
}catch(IOException e){
e.printStackTrace();
} }
}
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<form id="PrintFormContent" name="PrintFormContent" role="form"
action="/testForm/form/PrintFormContent" method="POST">
<div class="form-group row">
<label for="fname" class="col-md-2">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="fname"
placeholder="Enter First Name" name="fname" />
</div>
</div>
<div class="form-group row">
<label for="lname" class="col-md-2">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="lname"
placeholder="Enter Last Name" name="lname" />
</div>
</div>
<div style="text-align: center;">
<button id="btn" type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</body>
</html>
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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>testForm</display-name>
<servlet>
<servlet-name>PrintFormContent</servlet-name>
<servlet-class>PrintFormContent</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>/testForm/program/form/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Please Help.
you declared your servlet to PrintFormContent but you send your request to /testForm/form/PrintFormContent. You need to change it in the form-declaration:
<form id="PrintFormContent" name="PrintFormContent" role="form"
action="/PrintFormContent" method="POST">
btw. don't forget to change parameter name in the servlet to fname:
String fname = request.getParameter("fname");
try to add this to web.xml, somehow your anotation seems not to work
<servlet-mapping>
<servlet-name>PrintFormContent</servlet-name>
<url-pattern>/PrintFormContent</url-pattern>
</servlet-mapping>
check this, maybe you have the same problem: webservlet-annotation-doesnt-work-with-tomcat-8
How to do that when submiting my form at JSP page it will not reload? Here is user sending message and AJAX script (its in my jsp) get back all messages for user. But when i send message (do POST method) it refreshing my page that take some time to loading all messages with AJAX.
Help pls!!!
This is my JSP page
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/security/tags"
prefix="security"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Сообщения | Haine and Vold</title>
<link rel="shortcut icon" href="<c:url value="/resources/faviicon/iconHV.ico"/>" type="image/x-icon">
<link href="<c:url value="/resources/bootstrap/bootstrap.css"/>"
rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/CSS/styles.css"/>" rel="stylesheet"
type="text/css">
<link href="<c:url value="/resources/CSS/tableMessFixedHeader.css"/>" rel="stylesheet"
type="text/css">
<script src="<c:url value="/resources/Angular/angular.min.js"/>"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Haine and Vold</a>
</div>
<div class="collapse navbar-collapse"
id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><spring:message
code="label.menuprofile" /><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/haine/user"><spring:message
code="label.menuprofile" /></a></li>
<li><a href="/haine/user/updateinfo"><spring:message
code="label.menusettinginfo" /></a></li>
</ul></li>
<li><a href="/haine/user/messages"><spring:message
code="label.menumessages" /> (${allUserMess})</a></li>
<li><a href="/haine/user/search"><spring:message
code="label.menusearch" /></a></li>
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><spring:message
code="label.menuinformation" /><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/haine/user/rules"><spring:message
code="label.menurules" /></a></li>
<li class="divider"></li>
<li><a href="/haine/user/feedback"><spring:message
code="label.menusendfeedback" /></a></li>
</ul></li>
<security:authorize ifAnyGranted="ROLE_ADMIN">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><spring:message
code="label.menuadministration" /><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/haine/admin"><spring:message
code="label.menuadminpanel" /></a></li>
<li><a href="/haine/admin/feedbacklist"><spring:message
code="label.menufeedbacks" />(${countOfFeedbacks})</a></li>
<li><a href="/haine/admin/newusers"><spring:message
code="label.newusers" />(${countOfNewUsers})</a></li>
</ul></li>
</security:authorize>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="?locale=ru"><img
src="<c:url value="/resources/languageicons/rus.png"/>"
alt="Russian Language" title="Сменить язык интерфейса на русский"></a>
</li>
<li><a href="?locale=en"><img
src="<c:url value="/resources/languageicons/usa.png"/>"
alt="USA Language" title="Change interface language to american"></a>
</li>
</ul>
<c:url var="logoutUrl" value="/j_spring_security_logout" />
<form class="navbar-form navbar-right" action="${logoutUrl}"
method="post">
<button class="btn btn-default" type="submit">
<spring:message code="label.logoutbutton" />
</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</div>
</nav>
<div class="container">
<img class="img-responsive logo" src="/haine/resources/logo.jpg">
</div>
<br>
<div class="scrollTableMessages" id="mess">
</div>
<form:form method="POST" modelAttribute="message"
accept-charset="utf-8" ng-app="vandh" ng-controller="validateCtrl"
name="messageForm" novalidation="true">
<form:textarea path="text" class="form-control" rows="1"
id="message" ng-model="message" required="true"></form:textarea>
<div style="color: black"
ng-show="messageForm.message.$dirty && messageForm.message.$invalid">
<span ng-show="messageForm.message.$error.required"><spring:message
code="label.entermessage" /></span>
</div>
<br>
<div class="text-center">
<button class="btn btn-success" type="submit"><spring:message
code="label.sendmessage"/></button>
</div>
</form:form>
<script>
var app = angular.module('vandh', []);
app.controller('validateCtrl', function($scope) {
$scope.message = '';
});
</script>
</body>
<script src="<c:url value="/resources/Jquery/jquery-2.1.4.min.js"/>"
type="text/javascript"></script>
<script src="<c:url value="/resources/bootstrap/bootstrap.js"/>"
type="text/javascript"></script>
<script>
</script>
<script>
var oldC = 0, newC = -1;
function getMessages() {
$.ajax({
type : 'GET',
url : '/haine/user/countofmess/${iddialog}',
success : function(rs)
{
newC = rs;
if(oldC != newC)
{
$.ajax({
type : 'GET',
url : '/haine/user/mess/${iddialog}',
success : function(r)
{
$('#mess').html(r);
document.getElementById("mess").scrollTop = 9999;
console.log(r);
},
error : function(r) {
alert(r);
}
});
oldC = newC;
}
},
error : function(rs) {
alert(rs);
}
});
}
setInterval(getMessages, 1000);
</script>
</html>
And this is my controller
#RequestMapping(value = "/user/messages/{iddialog}", method = RequestMethod.POST)
public String messages(#ModelAttribute("message") Message message, #RequestParam(value = "text") String text,
#PathVariable(value = "iddialog") int iddialog, Model model, Principal principal) {
if(checkingMessage(text)!=true)
{
sendMessage(iddialog, text, principal.getName());
System.out.println("message sent!");
return "messagesWithUser";
}
else
{
return "redirect:/user/messages";
}
}
It depends on your Spring version.
if you are using Spring 3, JQuery you could do someting like this:
JSP
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!doctype html>
<html lang="es" >
<head></head>
<body>
Your Name: <input type='text' id='name'>
<button id='send-button'>Send</button>
<div id='state-bar'></div>
<script>
window.onload=function() {
var stateBar=$("#state-bar");
var name=$("#name");
var sendButton=$("#send-button");
sendButton.click(function( event ) {
var parameters={
name: name.val()
};
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameters),
dataType: "json",
url: "myPage.htm",
success: function (data) {
stateBar.html(data.response);
}, error: function(data){
stateBar.html("Server Error.");
}
});
});
}
</script>
<script src="resources/js/jquery.js"></script>
</body>
Controller Class
package com.company.controllers;
import org.springframework.stereotype.Controller;
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;
#Controller
public class TestController {
#RequestMapping(value="/testPage.htm",method=RequestMethod.GET)
public String testPage(){
return "testPage";
}
#RequestMapping(value="/myPage.htm",method=RequestMethod.POST)
#ResponseBody
public MyPageResponse myPage(#RequestBody MyPageModel myPageModel){
MyPageResponse res= new MyPageResponse();
res.setResponse("Your name is : "+myPageModel.getName());
return res;
}
}
Input VO
package com.company.controllers;
public class MyPageModel {
private String name="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Output VO
package com.company.controllers;
public class MyPageResponse {
private String response="";
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
web.xml
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com.company" />
<mvc:interceptors>
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptors>
<mvc:annotation-driven />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
It's happening because the default action for a submit button is sending the request as a normal request (not ajax).
You have to change your form to:
<form onsubmit="return false;" class="navbar-form navbar-right" action="${logoutUrl}"
method="post">
<button onclick="function_ajax_to_send_form()" class="btn btn-default" type="submit">
<spring:message code="label.logoutbutton" />
</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
I would like to determine which link is being click, and set a request attribute accordingly; to be processed in the controller. The controller is generic. It will dispatch to another page according to the attribute set in the JSP. How can I achieve this?
EDIT:
I have followed the BalusC's advice where
Register
Login
RandomController :
#WebServlet(name = "RandomController", urlPatterns = {"/RandomController/*"})
public class RandomController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int theRandom = 0;
Random myRandom = new Random();
RequestDispatcher dispatcher = null;
String pathInfo = request.getPathInfo();
String contextPath = request.getContextPath();
String dispatchesPath = contextPath + pathInfo;
System.out.println(pathInfo);
System.out.println(contextPath);
System.out.println(dispatchesPath);
theRandom = myRandom.nextInt(MAX_RANDOM);
request.setAttribute("random", theRandom);
if(pathInfo.equals("/Login")) {
dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
dispatcher = request.getRequestDispatcher("Register.jsp");
dispatcher.forward(request, response);
}
}
}
I have tried this approach but the Exception about maximum depth for nested request dispatchers : 20 is throw.
The generic controller is RandomController which servers two produces random number and set as attribute in request object and sent it to login or register page.
Login.jsp :
<%--
Document : Register
Created on : May 28, 2011, 5:49:35 PM
Author : nicholas_tse
--%>
<%#page contentType="text/html" 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>Online Store Register Page</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<jsp:useBean id="randomBean" class="Helper.RandomInt"
scope="request">
</jsp:useBean>
<h1>Online Store</h1>
<p></p>
<div align="right">
<h3>
<c:if test="${not empty sessionScope.username}">
! Welcome ${sessionScope["username"]} !
<form action="LogoutController" method="POST">
<input type="submit" name="submit" value="Logout"/>
</form>
</c:if>
</h3>
</div>
<ul id="nav_list">
<li>Home</li>
<li>Product</li>
<li>Add Stock</li>
<li>Shopping Cart</li>
<li>Order Status</li>
<li>Register</li>
<li>Login</li>
</ul>
<br></br>
<p></p>
<c:if test="${!not empty sessionScope.username}">
<div id="registerForm" align="center"
style="border:1px solid black; width:760px" >
<form name="RegisterForm" action="RegisterController"
method="POST">
<p>
Username : <input type="text" id="username" name="username">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Password : <input type="password" id="password" name="password"
</p>
<p>
Name : <input type="text" id="name" name="name">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Address : <input type="text" id="address" name="address">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
State :
<select>
<option>Selangor</option>
<option>Kuala Lumpur</option>
<option>Cyberjaya</option>
<option>Putrajaya</option>
</select>
</p>
<p></p>
<input type="submit" name="submit" value="Register">
<input type="reset" name="clear" value="Clear">
<p></p>
</form>
</div>
</c:if>
</body>
</html>
Without further info the only suggestion I can think of is to add a querystring to your URLs. Like this:
Page 1
This way you can look at the actiuon parameter in the request to determine what to do in your controller.
You can add a request parameter. This can be done in 2 ways depending on whether your form has a method of POST or GET.
You have implemented the submit buttons in the forms with a name attribute of submit and different value attributes. This should mean that the requests will include a submit parameter in the query string or the POST form data. On the server side, you can use this to figure out which of the submit buttons was clicked.