Forward call to Action class when validation fails - struts

I'm working on struts 1.1 application.
I have added validation for JSP form page(i.e. adduser.jsp).
It get validated after clicking on add button. And my validation in "Validator-XSS.xml" working fine.
But when validation fails then it forward to input attribute which is jsp form page(i.e. adduser.jsp).
Here I need to forward callto another action
(i. e.openAddUser.do)
which open JSP form page(i.e. adduser.jsp) insted of JSP page.
UPDATE
struts-config.xml
<struts-config>
<!-- some another entries -->
<form-bean name="UserForm" type="com.UserForm"/>
<action path="/createuser" type="com.CreateUserAction" name="UserForm"
scope="request">
<forward name="adduser" path="/jsp/adduser.jsp"/>
</action>
<action path="/adduser" type="com.AddUserAction" input="/jsp/adduser.jsp"
name="UserForm" scope="request">
<forward name="showuser" path="/showUserDetails.do"/>
</action>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/User-Validator.xml"/>
</plug-in>
</struts-config>
XSS-validator.xml
<form-validation>
<formset>
<form name="UserForm">
<field property="userName" depends="mask">
<msg name="mask" key="ui.field.invalidvalue" bundle="appResources"/>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z0-9-_]*$</var-value>
</var>
</field>
</form>
</formset>
on clicking on create user in jsp file it will call createuser.do It will open adduser.jsp
after entering details in form and click on add button it will adduser.do
also it get vlidated through XSS-validator.xml
but call goes to jsp/adduser.jsp but i need it has to call createuser.do
ActionForm is extended by ValidatorForm
public class UserForm extends ValidatorForm{
String userName;
String userId;
//getter setter
}
ActionClass
Public Class CreateUserAction{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//some code to bring list and other details
mapping.findForward("adduser");
}
Public Class AddUserAction{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//some code to add user and other details
mapping.findForward("showuser");
}

That is because you are not calling that action with the path. try this use this way to call that method that will work and will solve you problem.
Call Method and action
That will work accordingly. to call that action.

Related

How can I log information to a dividual file by Nlog?

I am about to log information of the Spider in some IActionResult to a dividual file with the date.
For example:
C:\20210317spider.txt
C:\20210318spider.txt
C:\20210319spider.txt
I don't want to use some method such as Logger.LogInformation to log all information into a file.
How can I achieve this? Thank you.
You can use the ${shortdate} layoutrenderer inside the FileName-Layout for the NLog FileTarget:
<nlog>
<targets>
<target type="file" name="spiderFile" fileName="C:/${shortdate}spider.txt" />
</targets>
<rules>
<logger name="Spider" writeTo="spiderFile" final="true" />
</rules>
</nlog>
See also the NLog Tutorial and the list of available layoutrenders that can be used with NLog Layout.
Then you can do this with Microsoft ILoggerFactory:
public class MyClass
{
private readonly ILogger _spiderLogger;
public MyClass(ILoggerFactory loggerFactory)
{
_spiderLogger = loggerFactory.CreateLogger("Spider");
_spiderLogger.LogInformation("Hello little spider");
}
}

Entlib Custom exception handler missing mappings

I implemented custom exception handler which works, except mappings from xml configuration policy. Those mapping works with standard Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler
My implementation
[ConfigurationElementType(typeof(CustomHandlerData))]
public class IdentityFaultContractExceptionHandler : IExceptionHandler
{
public IdentityFaultContractExceptionHandler(NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(Type faultContractType, NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(Type faultContractType, string exceptionMessage, NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(IStringResolver exceptionMessageResolver, Type faultContractType, NameValueCollection attributes)
{
}
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
return new Exception();
}
and part of the configuration
<add name="All Exceptions" type="System.Exception, mscorlib" postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add type="MyClass.IdentityFaultContractExceptionHandler, MyClass" exceptionMessage="An error occurred in the service." faultContractType="MyClass.UnexpectedServerFault, MyClass" name="Fault Contract Exception Handler" >
<mappings>
<add source="{Message}" name="Message" />
</mappings>
</add>
</exceptionHandlers>
</add>
When I remove mappping node service works, when I add, then I got error : unrecognize element mappings.
If you are using a CustomHandlerData attribute then your configuration needs to use XML Attributes which then get passed in as a NameValueCollection to the custom handler constructor. If you want to have custom XML then you will have to use Full Design-time Integration. If you want to go down that road then you should look at the FaultContractExceptionHandlerData source code since your code would probably be quite similar.

why Application_Error can not handlle some errors?

i developed a website(MVC 5) and upload it on a iis7 on a web server.
i handle errors on method
protected void Application_Error(){}
on the Global.asax.
yesterday i did some tests on it and i saw when i enter this url
http://www.xxxx.com/.
i can get invalid rout on Application_Error method but when i entered that URL with 3dotes or more like this URL
http://www.xxxx.com/...
i saw a webpage with this content and Application_Error not works because i have no default page or view with this content on my project.
The page cannot be displayed because an internal server error has occurred.
i did some test on another website on the internet and i saw some of theme has the same issue and i think i should do some config on my IIS.
if yes , what config(s) i should set on my IIS and if no what i can do with my project until i can handle it?
You can try this configuration in the web.config file:
<customErrors mode="On|Off|RemoteOnly" defaultRedirect="URL">
<error statusCode="404" redirect="URL" />
<error statusCode="402" redirect="URL" />
<error statusCode="500" redirect="URL" />
</customErrors>
Example:
I created a ErrorHandlerController with the following ActionResult's:
//This action return a view that show the http error you specified.
public ActionResult Error()
{
return View();
}
//This action return a view that show the 404 http error captured.
public ActionResult NotFoud()
{
return View();
}
//This action return a view that show the 402 http error captured.
public ActionResult Unauthorized()
{
return View();
}
In the web.config file of my project:
<customErrors mode="RemoteOnly" defaultRedirect="~/ErrorHandler/Error">
<error statusCode="404" redirect="~/ErrorHandler/NotFoud" />
<error statusCode="402" redirect="~/ErrorHandler/Unauthorized" />
<error statusCode="500" redirect="~/ErrorHandler/Error" />
</customErrors>
NOTE: Change the URL with your CustomURL desired.
Help: https://msdn.microsoft.com/en-us/library/h0hfz6fc%28v=vs.85%29.aspx

Spring Security - Get username in AuthenticationSuccessHandler without UserDetails/UserDetailsService

I'm trying to set the LastLogin time for a user in a custom AuthenticationSuccessHandler, however I don't know of a way of retrieving the username (since all the authority functions seem to return null because I'm not working with UserDetails).
The user data is stored in a MYSQL table and I'm using Hibernate to retrieve/create/update users. Within my application I'm using a self-written User class that doesn't have anything to do with the Spring User class. I don't have any custom UserDetails/UserDetailsService and I would like to avoid them, since I cannot change the DB table layout (as in add additional values)
The AuthenticationSuccessHandler looks like this:
public class PostSuccessfulAuthenticationHandler extends SimpleUrlAuthenticationSuccessHandler {
#Autowired
private UserService userService;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException
{
userService.trackUserLogin(authentication.getName()); //Doesn't work, getName seems to return null
super.onAuthenticationSuccess(request, response, authentication);
}
}
My applicationContext-security.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<global-method-security pre-post-annotations="enabled"/>
<!-- authentication-success-handler-ref='authSuccHandler' -->
<http use-expressions="true" disable-url-rewriting="true">
<intercept-url pattern="..." access="hasRole('ROLE_USER')" />
<form-login login-page="/index.htm"
authentication-failure-handler-ref='authFailureHandler'
authentication-success-handler-ref='authSuccHandler'
default-target-url='...'
always-use-default-target='true'/>
<logout logout-success-url="..."/>
<session-management invalid-session-url="/index.htm">
<concurrency-control max-sessions="2" error-if-maximum-exceeded="true" />
</session-management>
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="mysqldataSource"
authorities-by-username-query="select username, authority from benutzer where username = ?"
users-by-username-query="select username, password, enabled from benutzer where username = ?"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
The login itself works fine (even if I just comment out the trackUserLogin line in my AuthenticationSuccessHandler) which leads me to believe that there has to be a way to get that username. Can anyone help?
Try authentication.getPrincipal().

Accessing Authentication variable from LogoutHandler or LogoutFilter in Spring security

In one of my project I have configured Spring Security to handle user authentication.
My config file looks like this:
<http use-expressions="true">
<intercept-url pattern="/" access="permitAll()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login default-target-url="/main" login-page="/" always-use-default-target="true" username-parameter="userId" password-parameter="password" />
<custom-filter ref="customLogoutFilter" position="LOGOUT_FILTER"/-->
<session-management invalid-session-url="/" session-authentication-strategy-ref="sas" />
</http>
<beans:bean id="sas" class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy" />
<beans:bean id="customLogoutHandler" class="com.somepack.CustomLogoutHandler"/>
<beans:bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<beans:constructor-arg index="0" ref="customLogoutHandler"/>
<beans:constructor-arg index="1" ref="customLogoutFilter"/>
<beans:property name="filterProcessesUrl" value="/"/>
</beans:bean>
<beans:bean id="customLogoutFilter" class="com.somepack.CustomLogoutFilter">
<beans:property name="reportDir" value="/tmp/reports"/>
</beans:bean>
My CustomLogoutFilter class looks like
public class CustomLogoutFilter implements LogoutHandler {
private String reportDir;
public String getReportDir() {
return reportDir;
}
public void setReportDir(String reportDir) {
this.reportDir = reportDir;
}
#Override
public void logout(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) {
String userName = authentication.getName();
File folder = new File(reportDir, userName);
deleteDir(folder); //delete function to delete Logged User specific directory
logService.info("Logout", userName, EventCode.LOGOUT,
String.format("User %s logged out successfully", userName));
for (Cookie cookie : request.getCookies()) {
printcookies(cookie);
if (cookie.equals("JSESSIONID")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
request.getSession().invalidate();
}
}
But this piece of code is not working as the filter is getting called at the very first request for the Login page (even it may would get called in every request) and I am getting an NullPointerException in the
String userName = authentication.getName() line.
In fact instead of Using LogoutFilter if I use Logouthandler, I get the same error:
My handler looks like this:
public class CustomLogoutHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler{
private String reportDir;
public String getReportDir() {
return reportDir;
}
public void setReportDir(String reportDir) {
this.reportDir = reportDir;
}
#Override
public void onLogoutSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
String userName = authentication.getName();
File folder = new File(reportDir, userName);
deleteDir(folder);
logService.info("Logout", userName, EventCode.LOGOUT, String.format("User %s logged out successfully", userName));
super.handle(request, response, authentication);
}
and config file changed to:
<http use-expressions="true">
<intercept-url pattern="/" access="permitAll()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login default-target-url="/main" login-page="/" always-use-default-target="true" username-parameter="userId" password-parameter="password" />
<logout delete-cookies="JSESSIONID" invalidate-session="true" success-handler-ref="customLogoutHandler" logout-url="/logout" />
<session-management invalid-session-url="/" session-authentication-strategy-ref="sas" />
</http>
<beans:bean id="customLogoutHandler" class="sequent.ui.security.CustomLogoutHandler">
<beans:property name="reportDir" value="/tmp/reports" />
</beans:bean>
Not sure how can I resolve this issue.
Please help.
In short my basic requirement is that, I need to access the User Principal in the Logout mechanism which triggered when either User clicks on the Logout button or the session expires. I need the User information because the application creates temporary folder in the name of logged user which I need to delete at the time when he log off.
Appreciate your help please!!
-Raul
You have set the filerProcessesUrl of the LogoutFilter to "/" which means that every time a user browses to the domain root, the filter will attempt to logout the user. Use a specific logout URL (or the default value) and check whether the user is actually authenticated before you try to do a logout (make sure the Authentication instance isn't null).
If you need to deal with session timeouts, where the user fails to logout, then you will also have to implement an HttpSessionListener which identifies the user from the session and performs whatever clean-up you need. This would be added to your web.xml file. Note that this class isn't invoked during a user request, so you can't use the SecurityContext to obtain information about the user, you must get it from the session object which is passed to the listener before the session is invalidated.