I have deployed my tomcat war succesfully on Amazon EC2 today.
On my local machine the following link: localhost:8080/login works totally fine
But on my EC2 instance, the link always has to have the .war name in the link:
http://some-amazon-link:8080/the-war-name/login
Now im struggling how and where i have to add that "/the-war-name/" in my Spring MVC project.
wether its in the
web.xml
the views
the controllers.
With the code below i can access the login with the following link:
localhost:8080/login
but i want it to be
localhost:8080/some-war-name/login
I've tried adding the /some-war-name/ to the #RequestMapping, changing the dispatcher
My login.jsp:
<html>
<head>
<title>Login ProV</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<p><font color="red">${errorMessage}</font></p>
<form action="/login" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Benutzername</label>
<input name="name" type="text" class="form-control" id="exampleInputUsername1" placeholder="Benutzernamen eingeben">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<input class="btn btn-primary" type="submit" />
</form>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
My web.xml
<web-app 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_3_0.xsd"
version="3.0">
<display-name>To do List</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/todo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
My LoginController
package com.mschm.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.mschm.login.LoginService;
#Controller
#SessionAttributes("name")
public class LoginController {
#Autowired
LoginService service;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginPage() {
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String handleLoginRequest(#RequestParam String name, #RequestParam String password, ModelMap model) {
if(!service.validateUser(name, password)) {
model.put("errorMessage", "Invalid Credentials");
return "login";
} else {
model.put("name", name);
model.put("password", password);
return "welcome";
}
}
}
that "/the-war-name/"
is called the context path for your application.
You need to configure tomcat to use an empty context path in your case. There are several ways to achieve this.
One of them is to add following to $CATALINA_BASE/conf/server.xml:
<Host name="your.host.name" >
<Context path="" docBase="/path/to/the-war-name.war"/>
</Host>
Further Reading:
Defining a context in Apache Tomcat 8 Configuration Reference.
Related
1.The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." I am completely new to SpringMVC and not able to solve this 404 please help me so that i can move forward to learn the subject . I tried everything that i got on internet
index.jsp
<%response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0);
%>
<html>
<body>
<form action="add">
<input type="text" name="t1"><br>
<input type="text" name="t2"><br>
<input type="submit">
</form>
</body>
</html>
first-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:ctx="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-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
<ctx:annotation-config></ctx:annotation-config>
<ctx:component-scan base-package="com.Tutorial"></ctx:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
AddControllerTYpe.java
package com.Tutorial.FirstWebProject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AddControllerType
{
#RequestMapping("/add")
public void add()
{
System.out.println("-----its here-----");
}
}
I practise Java EE 7 nowadays. I come across a problem when trying to authenticate a user by using container provided way, i.e., j_security_check .
Application server: Apache Tomcat 7
Project/Application name: ServletDrill
Resource (Servlet) annotated with #WebServlet
My 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletDrill</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>To_Auth</web-resource-name>
<url-pattern>/auth/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>valid</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/FormAuth.jsp</form-login-page>
<form-error-page>/LogInErr.jsp</form-error-page>
</form-login-config>
</login-config>
</web-app>
My tomcat-users.xml:
<tomcat-users>
<role rolename="valid"/>
<user username="username" password="pass" roles="valid"/>
</tomcat-users>
My <form>:
<form action="/ServletDrill/j_security_check" accept-charset="UTF-8" method="post">
<fieldset id="postForm">
<legend>j_security_check method</legend>
<div class="partContainer">
<div class="left"><label for="user" >User Name: </label></div>
<div class="right"><input type="text" name="j_username" id="user" required="required" maxlength="20"></div>
</div>
<hr/>
<div class="partContainer">
<div class="left"><label for="pass" >Pass: </label></div>
<div class="right"><input type="password" name="j_password" id="pass" required="required" maxlength="20"></div>
</div>
<hr/>
<div class="partContainer">
<div class="left"><input type="submit" value="Log In"></div>
<div class="right"><input type="reset" value="Reset"></div>
</div>
</fieldset>
</form>
My protected resource (Servlet):
#WebServlet("/auth/NeedsPriorAuth")
public final class NeedsPriorAuth extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Welcome, "+request.getRemoteUser()+". The user has been authenticated before hand").append("\n Auth Type: "+request.getAuthType());
}
}
When I execute the following link,
Access Protected Servlet
,the user redirected for authentication on the following page,
<form-login-page>/FormAuth.jsp</form-login-page>
(the <form> that I posted above).
Despite passing in correct credentials (posted above at tomcat-users.xml) the user redirected to the following Error page (posted above at Web.xml):
<form-error-page>/LogInErr.jsp</form-error-page>
What is the culprit which causes such an inconvenience for me? I've been stuck on this problem for several days now.
What about <realm>, do I need it?
Any ideas?
There you go, in the end, I have resolved the problem. The modification that I needed to apply:
<form action="j_security_check" accept-charset="UTF-8" method="post">
That is, the action has no application context prefix.
The other thing, is that there are, in my case, 2 instances of tomcat-users.xml file:
Under Apache Tomcat v7 directory (The server app)
And the one accessible from Project Explorer in Eclipse, under Servers2 name
When you modify the role(s), username, and password, if you want to see an affect to take place, modify it under the latter instance example; the server restart comes after.
Neither BindingResult nor plain target object for bean name 'command' available as request attribute
this is my index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>
<form:form action="loginform" method="post">
<form:input type="text" path="name" id="userName" />
<form:input type="password" path="pass" id="password" />
<form:button value="submit"></form:button>
</form:form>
</body>
</html>
this is my Bean
package com.ews.usman.controller;
public class loginBean {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
this is my Controller
package com.ews.usman.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginFormController {
#RequestMapping(value="/loginform", method=RequestMethod.POST)
public ModelAndView formReader(#ModelAttribute("loginBean") loginBean
loginbean, BindingResult result){
ModelAndView model = new ModelAndView();
model.addObject("name", loginbean.getName());
model.addObject("pass", loginbean.getPass());
model.setViewName("result");
return model;
}
}
this is my Servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up
static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.ews.usman" />
<bean name="/loginform"
class="com.ews.usman.controller.LoginFormController"></bean>
</beans:beans>
this is my web.xml
<?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">
<!-- 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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>`
You need to add a modelAttribute with a proper name to your form, otherwise the form backing bean name will default to 'command' hence you get your error
<form:form action="loginform" modelAttribute="loginBean" method="post">
To deploy the project I have purchased java server online with www.net4.in and created the database using phpmyadmin access given by them. I have deployed the project by transferring .war file of my project.
I have adjusted all the links like:
servlet path
form submission path
web.xml
all the required ones.
In servlet path if I add .java to servlet it is showing the code online, however the same path is giving error when I am submitting the form to Servlet.
<html>
<body>
<form id="theForm" name="form1" method="post" action="../../../db/src/com/mayuri/servlet/SelectCustServlet" enctype="multipart/form-data" target="_self" onSubmit="return verify()">
<fieldset class="login"><br>
<legend>Customer Details - Fill Customer Details</legend>
<div>
<label for="Ac_No">Account Number</label>
<input type="text" id="Ac_No" name="Ac_No" autocomplete="off" onKeyPress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
</div>
<div>
<label for="Center_No">Center Number</label> <input type="text" id="Center_No" autocomplete="off" class="input username" name="Center_No" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
</div>
</fieldset><br>
<center>
<button type="submit" >Submit</button>
</center>
</form>
</body>
</html>
Servlet Code
package com.mayuri.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
//#WebServlet("/FileUploadDBServlet")
#MultipartConfig(maxFileSize = 10177215) // upload file's size up to 16MB
public class SelectCustServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SelectCustServlet() {
super();
}
private String dbURL = "jdbc:mysql://118.67.244.52/databasename";
private String dbUser = "loginid";
private String dbPass = "pwd";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Connection conn = null; // connection to the database
PrintWriter out = response.getWriter();
String message = null; // message will be sent back to client
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// gets values of text fields
String Ac_No = request.getParameter("Ac_No");
System.out.println("in Servlettttttttttttttttttttttttt" + Ac_No);
String Center_No = request.getParameter("Center_No");
try {
// connects to the database
// constructs SQL statement
String sql = "INSERT INTO cust (Ac_No, Center_No ) values (?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, Ac_No);
statement.setString(2, Center_No);
out.println("dfsfsdf");
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
// message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
// request.setAttribute("Message", message);
// forwards to the message page
//request.getRequestDispatcher("Message.jsp").forward(request, response);
}
}
}
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"
id="WebApp_ID" version="2.5">
<display-name>softwarematcs</display-name>
<servlet>
<description></description>
<display-name>SelectCustServlet</display-name>
<servlet-name>SelectCustServlet</servlet-name>
<servlet-class>db.src.com.mayuri.servlet.SelectCustServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectCustServlet</servlet-name>
<url-pattern>../../src/com/mayuri/servlet/SelectCustServlet</url-pattern>
</servlet-mapping>
</web-app>
Use short and valid Servlet URL pattern and don't forget to prefix form action with context root path. Servlet URL pattern shows in the browser URL.
Either use JSP Expression Language ${pageContext.request.contextPath} or core tag library <c:url> for getting context root relative URL path.
For example:
JSP:
<form action="${pageContext.request.contextPath}/myServlet" method="post">
web.xml:
<servlet>
<servlet-name>SelectCustServlet</servlet-name>
<servlet-class>db.src.com.mayuri.servlet.SelectCustServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectCustServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
Read more...
Try the following pieces of code. I've modified the web.xml to the correct servlet-class name com.mayuri.servlet.SelectCustServlet and the servlet's url-pattern to /SelectCustServlet.
Also, I've updated the HTML form's action to the correct servlet url pattern.
HTML form:
<html>
<body>
<form id="theForm" name="form1" method="post" action="<%=request.getContextPath()%>/SelectCustServlet" enctype="multipart/form-data" target="_self" onSubmit="return verify()">
<fieldset class="login"><br>
<legend>Customer Details - Fill Customer Details</legend>
<div>
<label for="Ac_No">Account Number</label>
<input type="text" id="Ac_No" name="Ac_No" autocomplete="off" onKeyPress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
</div>
<div>
<label for="Center_No">Center Number</label> <input type="text" id="Center_No" autocomplete="off" class="input username" name="Center_No" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
</div>
</fieldset><br>
<center>
<button type="submit" >Submit</button>
</center>
</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://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>softwarematcs</display-name>
<servlet>
<description></description>
<display-name>SelectCustServlet</display-name>
<servlet-name>SelectCustServlet</servlet-name>
<servlet-class>com.mayuri.servlet.SelectCustServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectCustServlet</servlet-name>
<url-pattern>/SelectCustServlet</url-pattern>
</servlet-mapping>
</web-app>
I am new to Spring MVC .
please excuse if this is a dumb question , i have tried a lot on my own , but couldn't able to resolve
I am facing here a issue which is my controller is never being getting called
Here is the code
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/hello.html" method="post">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
dispatcher-servlet.xml
<context:component-scan base-package="com.javatpoint" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
hellopage.jsp
Message is: ${message}
errorpage.jsp
${message}
<jsp:include page="/index.jsp"></jsp:include>
HelloWorldController.java
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public ModelAndView helloWorld(HttpServletRequest request,HttpServletResponse res) {
String name=request.getParameter("name");
String password=request.getParameter("password");
System.out.println("The Name is"+name);
System.out.println("The password is"+password);
if(password.equals("admin")){
String message = "HELLO "+name;
return new ModelAndView("hellopage", "message", message);
}
else{
return new ModelAndView("errorpage", "message","Sorry, username or password error");
}
}
}
web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Include your app context path in the form action:
<form action="${pageContext.request.contextPath}/hello.html" method="post">
Try changing your form's action from /hello.html to /hello, as that's what you have in your controller's #RequestMapping