I am new in the servlet programming, so I want to ask how to call servlet from a html file.Basically I am using eclipse oxygen 3.0 for it, and already tried everything but did't success to call servlet from html.I also mention servlet in web.xml file as below
<servlet>
<servlet-name>ShowParameters</servlet-name>
<servlet-class>coreservlets.ShowParameters</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowParameters</servlet-name>
<url-pattern>/ShowParameters</url-pattern>
</servlet-mapping>
I am using coreservlets as a package.
There are two ways:
1) by using anchor tag:
<a href='ShowParameters?name=myname'> some url </a>
2) by using below form:
<form action="ShowParameters" method="post">
Name: <input maxlength="100" type="text" name="name" class="form-control" placeholder="" />
<input type="submit" value="submit">
</form>
Related
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.
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.
I am using spring-security on top of spring-mvc application. Few points about the application I am working on.
Home page is login page i.e /users(). Login menu served as HTML dropdown menu.
Implementing userDetailsService() and UserDetails() instead of AuthenticationManager/provider
Required is person to view the home page without any roles.
Current situation :
Redirects it to 403 page mentioned in the entrypoint-ref.
No idea how to redirect it to user.jsp or /users
All examples I can find on net somehow show same stuff which is implementing `AuthenticationManager. Some code :
security-context.xml
<import resource="servlet-context.xml" />
<!-- Global Security settings -->
<security:global-method-security pre-post-annotations="enabled" />
<!-- Spring Security framework settings -->
<security:http pattern="/users" use-expressions="true" auto-config="true" disable-url-rewriting="true" entry-point-ref="formAuthenticationEntryPoint">
<security:session-management>
<security:concurrency-control max-sessions="5" error-if-maximum-exceeded="false"/>
</security:session-management>
<security:intercept-url pattern="/*" requires-channel="any" access="permitAll" />
<security:intercept-url pattern="/**" requires-channel="any" access="permitAll" />
</security:http>
<!-- queries to be run on data -->
<beans:bean id="formAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
<bean id="LoginServiceImplementation" class="com.WirTauschen.service.LoginServiceImpl"></bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="userDetailsService" />
</security:authentication-manager>
</beans>
LoginServiceImpl :
#Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{
#Autowired private UserDao userDao;
#Autowired private Assembler assembler;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails userDetails = null;
User user = userDao.findByName(username);
if(user == null) { throw new UsernameNotFoundException("Wrong username or password");} //Never specify which one was it exactly
return assembler.buildUserFromUserEntity(user);
}
}
Login-form(part of hompage HTML code enveloped in user.jsp)
<nav class="col-lg-5 col-md-5 col-sm-5">
<ul class="pull-right">
<li class="purple"><i class="icons icon-user-3"></i> Login
<ul id="login-dropdown" class="box-dropdown">
<li>
<form id="form" action="<c:url value='/login'/>" method="POST">
<div class="box-wrapper">
<h4>LOGIN</h4>
<div class="iconic-input">
<input type="text" placeholder="Username" name="username" id="username" value="">
<i class="icons icon-user-3"></i>
</div>
<div class="iconic-input">
<input type="password" placeholder="Password" name="password" id="password" value="">
<i class="icons icon-lock"></i>
</div>
<input type="checkbox" id="loginremember"> <label for="loginremember">Remember me</label>
<br>
<br>
<div class="pull-left">
<input name="submit" type="submit" class="orange" value="Login">
</div>
<div class="pull-right">
Forgot your password?
<br>
Forgot your username?
<br>
</div>
<br class="clearfix">
</div>
<div class="footer">
<h4 class="pull-left">NEW CUSTOMER?</h4>
<a class="button pull-right" href="create_an_account.html">Create an account</a>
</div>
</form>
</li>
</ul>
</li>
<li><i class="icons icon-lock"></i> Create an Account</li>
</ul>
</nav>
Form-login from security-applicationContext.xml
<security:form-login login-page="/users" default-target-url="/users"/>
Any help would be nice. Never knew spring-security will be nothing but torture.
UPDATE
You have to understand how Spring works: the client tries to get to a protected resource (users page, for example); if he did not login yet, he is being redirected (Spring redirects him) to the login page.
In your Spring beans.xml you declare what is your login page. If you put there "/login.html", you have to make sure that you have this kind of page, with the login form. After the user logs in, Spring will redirect him back to the /users.
Makes sense?
UPDATE II
You can make (like Amazon...) a landing page (e.g. index.html) which is public, meaning users can see it without logging in. Then, there are links there to 'protected resources', and if a user try to click on it and get the protected resource, Spring will redirect him to the login page. If you wanna do that, you put you 'protected resources' under a specific directory (e.g. /secured) and you place there all protected resources HTML/JSP/etc. You configure this in the beans.xml: (note here that 'welcome' page is non-secured, everybody will be able to see it without login)
<sec:http pattern="/welcome" security="none" />
<sec:http authentication-manager-ref="authenticationManager">
<sec:intercept-url pattern="/secure/**" access="ROLE_USER" />
I need to use unicode in my Spring MVC application and I faced with some troubles.
After I submit my hidden form with unicode using jQuery $('.form').submit() data sends to the Spring Controller and there it looks like "%D0%9C%D1%96%D0%B9%20%". In result I can't handle and manipulate with normal string on the server side. What did I do wrong?
I have following form:
<form style="display: hidden" action="${contextPath}/somePage.htm" method="POST" class="form">
<input type="hidden" class="name" name="name" value=""/>
</form>
And Spring controller:
#RequestMapping(value = "/somePage", method = RequestMethod.POST)
public String showSomePage(#RequestParam("name") String name, Model model) {
}
In my web.xml:
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In server.xml of Tomcat:
<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Fixed. I hadn't to use encodeURIComponent() for input value in case of POST method
I'm writing a spring webflow with MVC and persistence scaffolded by Spring Roo. In this flow, the user is supposed to be creating multiple instances of one entity, which in turn is to be referenced from another entity. For simplicity, I'll dub these entities MyClass1 and MyClass2. I'm having a hard time figuring out how to keep a list of persisted entities, which is needed at confirmation.
I have previously posted a question regarding the same topic. I do feel, however, that editing the original question (even more) in order to further clarify my issue would violate the SO-"protocol", and so I've decided to ask a refined version of the original question. In retrospect, I realize that the original question should've been more accurate. I'm probably gonna get some heat for this, but I feel the question is important enough (at least to me!) to take it. :)
I'm including my roo-script to let anyone easily reproduce my setup. Here it is:
project --topLevelPackage com.test.webflow
persistence setup --provider HIBERNATE --database HYPERSONIC_IN_MEMORY
entity --class ~.domain.Class1 --testAutomatically
field string --fieldName name
entity --class ~.domain.Class2 --testAutomatically
field string --fieldName name
field reference --fieldName class1 --type ~.domain.Class1
controller scaffold --class ~.web.Class1Controller --entity ~.domain.Class1
controller scaffold --class ~.web.Class2Controller --entity ~.domain.Class2
web flow --flowName registration
The flow.xml in /WEB-INF/views/registration looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<flow xmlns="http://www.springframework.org/schema/webflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
<on-start>
<evaluate expression="new java.util.ArrayList()" result="flowScope.myList" result-type="java.io.Serializable"/>
</on-start>
<view-state id="view-state-1" view="registration/view-state-1" model="class1">
<on-entry>
<evaluate expression="new com.test.webflow.domain.Class1()" result="flowScope.class1"/>
</on-entry>
<transition on="repeat" to="view-state-1"/>
<transition on="success" to="view-state-2"/>
<transition on="cancel" to="end-state"/>
<on-exit>
<evaluate expression="class1.persist()" result="flowScope.class1"/>
<evaluate expression="myList.add(class1)"/>
</on-exit>
</view-state>
<view-state id="view-state-2" view="registration/view-state-2">
<transition on="cancel" to="end-state"/>
</view-state>
<end-state id="end-state" view="registration/end-state"/>
</flow>
(In a real-life version of the flow, there would be another view-state in which entities of Class2 would be registered.) The view-state-1.jspx looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:spring="http://www.springframework.org/tags" xmlns:form="http://www.springframework.org/tags/form" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:util="urn:jsptagdir:/WEB-INF/tags/util" xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<spring:message var="title" code="webflow_state1_title" htmlEscape="false" />
<util:panel id="title" title="${title}">
<h1>${fn:escapeXml(title)}</h1>
<p>
<spring:message code="webflow_state1_message" />
</p>
<form:form commandName="class1">
<input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}" />
<p>Enter name: <form:input path="name"/></p>
<div class="submit">
<spring:message var="cancel" code="button_cancel" htmlEscape="false" />
<spring:message var="proceed" code="button_proceed" htmlEscape="false" />
<spring:message var="repeat" code="button_repeat" htmlEscape="false" />
<input type="submit" id="cancel" name="_eventId_cancel" value="${fn:escapeXml(cancel)}" />
<input type="submit" id="success" name="_eventId_success" value="${fn:escapeXml(proceed)}" />
<input type="submit" id="repeat" name="_eventId_repeat" value="${fn:escapeXml(repeat)}" />
</div>
</form:form>
</util:panel>
</div>
The view-state-2.jspx looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:spring="http://www.springframework.org/tags" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:util="urn:jsptagdir:/WEB-INF/tags/util" xmlns:form="http://www.springframework.org/tags/form" xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<spring:message var="title" code="webflow_state2_title" htmlEscape="false" />
<util:panel id="title" title="${title}">
<h1>${fn:escapeXml(title)}</h1>
<p>
<spring:message code="webflow_state2_message" />
</p>
<p>
<c:forEach var="class1" items="${myList}">
<li><c:out value="${class1.name}"/></li>
</c:forEach>
</p>
</util:panel>
</div>
From all I've read so far, I think my solution should work. However, I still don't get the expected output; i.e. a print out of every name-field. I get the same number of <li>-elements as I put in, but they all seem to be evaluated to null, as explained in my previous post. Can anyone explain to me why this code doesn't display the contents of the persisted Class1.name-fields? (Btw: they do show up in the CRUD.)
Thanks in advance!
D-O-(freakin')-H! The signature of Class1.persist() is public void Class1.persist(). Ahem. So
<evaluate expression="class1.persist()" result="flowScope.class1"/>
will, apparently, quite effectively set the flowScope.class1 variable to null. By dropping the result-attribute will solve your (and my!) problem. :)