I am using spring mvc + spring security to build a simple web application. I implemented the login/logout (spring mvc) but i want to provide also a registration jsp accessible directly from the login.jsp. Basically i just need a simple link from the login.jsp to the regsiter.jsp without passing any parameters or whatever. I just want to ask you what is the best practice to achieve this?
Is there any way to navigate directly between the two jsps without routing the request down to the controller? (or this is not really a spring mvc way?) To be honest my only "problem" is just to have a separate method in the register controller which does nothing just routes the request to the register jsp. I mean:
RegisterController
#Controller
public class RegisterController {
#RequestMapping(value="/view_register.htm", method = RequestMethod.POST)
/** Navigates to the register page */
public String navigateToRegistration(ModelMap model) {
return "register";
}
#RequestMapping(value="/register.htm", method = RequestMethod.POST)
/** Handles request from the registration page and registers the user */
public String registerUser(ModelMap model) {
// hard stuff to register the user
return "welcome";
}
}
WEB-INF/pages/login.jsp
......
<tr>
<td>Don't have an account yet.</td>
<td> Register here
</td>
</tr>
......
WEB-INF/pages/register.jsp
......
<form name='registration' action="<c:url value='register.htm' />"
method='POST'>
......
WEB-INF/web.xml - routing each request to spring mvc
......
mvc-dispatcher
/
WEB-INF/mvc-dispatcher-servlet
<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"
xsi:schemaLocation="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">
<import resource="classpath:/applicationContext.xml" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Is my implementation correct? This is the mvc way? I just want to know whether i understand this well and not doing any antipattern stuff. The thing what confuses me is really this additional small method in the regsitration controller which does nothing just navigates from the login to register. Is there at least any naming convention for this kind of methods? Would you recommend rather a ForwardController which could act as a Manager/Dispatcher and would just manage this kind of navigation requests?
Your structure looks correct: One exception is that the /view_register.htm should be a GET, not a POST. Spring MVC uses a front controller pattern, and so every request does go through a controller. When the only thing a request does is to return a view, you can configure your mappings using the ParameterizableViewController instead of coding a controller, but I tend to code a method like you have when there are multiple related requests within a controller. As your app evolves, you might find there is some session setup you will add, and this just keeps all of the registration requests in the same class.
Don't forget to configure security to allow anonymous access to your registration requests.
Related
I have a Spring project. When I call the URL it is calling the controller and printing the result in console. But the requestmapping method prints the output but not displaying the view / jsp page.
Please find the below link for better understanding.
My Spring Project Structure:
the controller is called and printing 'IN' as output:
The controller i been using.
#Controller
public class BaseController {
#RequestMapping(value="/")
public String getRespnse(Model m) {
System.out.println("IN");
return "home";
}
}
This the view resolver I'm using.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
I cannot able view the jsp output in browser.Please suggest a way to handle.
If you map your DispatcherServlet to url pattern /* in your web.xml it overrides all other url mappings specified. To handle JSPs web containers includes a mapping *.jsp to handle JSPs.
So you mapping overrides the container`s *.jsp servlet and requests for servlets are now going through your DispatcherServlet which doesnt know how to handle JSPs.
Change your url-pattern from /* to /
I'm a beginner with Spring and I'm trying to understand how a controller works.
I have several methods annotated with #RequestMapping and everything works fine, but I don't know how to handle simple page requests.
Suppose I have to redirect from one page to another, without making server logic. If I create the url redirecting to PageA.jsp it seems that I always need to define the method catching the request in the Controller, declaring a method that is pratically empty, like this:
#RequestMapping(value="/PageA.jsp")
public String redirectToPageA(){
return "PageA";
}
If I don't follow this approach I get 404 error as the controller can't find the mapping. I don't like this approach very much as it fills my controller with useless empty methods.
Which is the suggested approach?
I suggest using a view resolver.
Read more about it here - 17.5.1 Resolving views with the ViewResolver interface from 17. Web MVC framework.
In that section you have
As an example with JSP as a view technology, you can use the
UrlBasedViewResolver. This view resolver translates a view name to a
URL and hands the request over to the RequestDispatcher to render the
view
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
When returning test as a logical view name, this view resolver
forwards the request to the RequestDispatcher that will send the
request to /WEB-INF/jsp/test.jsp. including the code.
And this answer has the annotation based configuration of a view resolver (except you could use the UrlBasedViewResolver).
I have a spring security MVC application. In few JSP files I have code that looks like this:
<sec:authorize access="hasAnyRole('ROLE_FOO', 'ROLE_BAR')">
<!--do something here-->
</sec:authorize>
I have to make code changes (changing ROLE_FOO to something else) when deploying the app to production because it has different role names. So I was wondering whether there is a way to configure these role names in a property file and then pick those inside the <sec:authorize> tag.
So the code would look something like this:
Property File:
Admin_Roles = ROLE_FOO ROLE_BAR
and JSP
<sec:authorize access="hasAnyRole(<get roles from Admin_Roles in prop file>)">
<!--do something here-->
</sec:authorize>
btw, I am using Active Directory for authentication so these roles are pre-configured in the active directory for test and production.
Not sure it is the easiest way. But you can write your own expression.
This link should be very useful. link
Since there are some differences between each version. You had better take a look at the source code of DefaultWebSecurityExpressionHandler to make sure you do not miss anything when override createSecurityExpressionRoot
Not sure how you would do this for a variable number of roles, but for a fixed number have you tried something like this?
JSP:
<sec:authorize access="hasAnyRole('${adminRole1}', '${adminRole2}')">
<!--do something here-->
</sec:authorize>
Controller:
#Value("#{myprops.admin_role_1}"}
private String adminRole1;
#Value("#{myprops.admin_role_2}"}
private String adminRole2;
...
#RequestMapping("/hello")
public String hello(final Model model) {
model.addAttribute("adminRole1", adminRole1);
model.addAttribute("adminRole2", adminRole2);
...
}
and config XML:
<bean id="myprops"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<!-- External property files -->
<value>file:${somepathvar}/adminroles.properties</value>
</list>
</property>
</bean>
the title of this post might be confusing.I'll try be best to clarify it.
I Started a project using Spring MVC it works fine no problem.After that i've realized
that i was a bit overkill and found that i needed a front controller dispatcher because
all a wanted was nice urls without extensions.
So instead of implementing a whole new font controller i will like to take advantage of the existing Spring MVC setup. here is an example of a controller
#RequestMapping("/accounts")
public String home() {
return "accounts";
}
#RequestMapping(value="/")
public String Home(){
return "home";
}
as you can see, the return string is the one indicating the view based on the resourceviewresolver
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
now i don't want to use the controller, but need a mechanism to map the request to a physical page.i'm wondering if that could be possible.
How can i do that? i should simply create another dispatcher?
thanks for reading this and helping out.
Spring 3 supports <mvc:view-controller> element for such cases:
<mvc:view-controller path="/" view-name="home" />
<mvc:view-controller path="/accounts" view-name="accounts" />
See also:
MVC Simplifications in Spring 3.0
I want to define a set of error messages so that when validation errors generate codes, those codes pick up the corresponding error message and print them.
For the sake of learning, and to develop an extendable web app, I'd like to follow the proper i18n path, though I only need to define one (english) set of messages now.
So the locales should all default to english when they don't find their own resources (which I'm yet to define).
I've never used any of the i18n functionality of Java. And the spring docs assume that I have this knowledge.
Could someone just give me a gental nudge in the right direction?
I've defined a messageSource in my dispatcher-servlet.xml webapp context. I have a validator which produces a BindingResult object with a rejected field "username", with code "username.taken". I can generate the default message.
Now I just need to get the error message from the errormessages.properties file in my view.
How do I resolve an error code to a message?
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>errormessages</value>
</list>
</property>
</bean>
It depends on what you want to do with this text. The first possibility is to get the message programmatically:
#Autowired
private MessageSource messageSource;
#RenderMapping(params = "render=details")
public String showDetails (Model model, Locale locale) {
messageSource.getMessage(<your key goes here>, null, locale);
}
This way is very uncommon, cause you have to get the message keys form the Errors object by yourself.
Another more common way is to use the build in view extensions shipped with spring mvc. You didn't wrote it but I guess your using JSPs. In that case you can simply write something like this in your JSP:
<!-- showing errors -->
<div>
<form:errors path="*" />
</div>
<!-- showing arbitrary messages -->
<div>
<spring:message code="${success.messageKey}"/>
</div>
For further reading I suggest you http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html